1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for expressions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TreeTransform.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/EvaluatedExprVisitor.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/ExprOpenMP.h"
26 #include "clang/AST/RecursiveASTVisitor.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/Basic/FixedPoint.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/Overload.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/SemaFixItUtils.h"
45 #include "clang/Sema/SemaInternal.h"
46 #include "clang/Sema/Template.h"
47 #include "llvm/Support/ConvertUTF.h"
48 using namespace clang;
49 using namespace sema;
50 
51 /// Determine whether the use of this declaration is valid, without
52 /// emitting diagnostics.
53 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
54   // See if this is an auto-typed variable whose initializer we are parsing.
55   if (ParsingInitForAutoVars.count(D))
56     return false;
57 
58   // See if this is a deleted function.
59   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
60     if (FD->isDeleted())
61       return false;
62 
63     // If the function has a deduced return type, and we can't deduce it,
64     // then we can't use it either.
65     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
66         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
67       return false;
68 
69     // See if this is an aligned allocation/deallocation function that is
70     // unavailable.
71     if (TreatUnavailableAsInvalid &&
72         isUnavailableAlignedAllocationFunction(*FD))
73       return false;
74   }
75 
76   // See if this function is unavailable.
77   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
78       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
79     return false;
80 
81   return true;
82 }
83 
84 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
85   // Warn if this is used but marked unused.
86   if (const auto *A = D->getAttr<UnusedAttr>()) {
87     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
88     // should diagnose them.
89     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
90         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
91       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
92       if (DC && !DC->hasAttr<UnusedAttr>())
93         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
94     }
95   }
96 }
97 
98 /// Emit a note explaining that this function is deleted.
99 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
100   assert(Decl->isDeleted());
101 
102   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
103 
104   if (Method && Method->isDeleted() && Method->isDefaulted()) {
105     // If the method was explicitly defaulted, point at that declaration.
106     if (!Method->isImplicit())
107       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
108 
109     // Try to diagnose why this special member function was implicitly
110     // deleted. This might fail, if that reason no longer applies.
111     CXXSpecialMember CSM = getSpecialMember(Method);
112     if (CSM != CXXInvalid)
113       ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
114 
115     return;
116   }
117 
118   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
119   if (Ctor && Ctor->isInheritingConstructor())
120     return NoteDeletedInheritingConstructor(Ctor);
121 
122   Diag(Decl->getLocation(), diag::note_availability_specified_here)
123     << Decl << 1;
124 }
125 
126 /// Determine whether a FunctionDecl was ever declared with an
127 /// explicit storage class.
128 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
129   for (auto I : D->redecls()) {
130     if (I->getStorageClass() != SC_None)
131       return true;
132   }
133   return false;
134 }
135 
136 /// Check whether we're in an extern inline function and referring to a
137 /// variable or function with internal linkage (C11 6.7.4p3).
138 ///
139 /// This is only a warning because we used to silently accept this code, but
140 /// in many cases it will not behave correctly. This is not enabled in C++ mode
141 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
142 /// and so while there may still be user mistakes, most of the time we can't
143 /// prove that there are errors.
144 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
145                                                       const NamedDecl *D,
146                                                       SourceLocation Loc) {
147   // This is disabled under C++; there are too many ways for this to fire in
148   // contexts where the warning is a false positive, or where it is technically
149   // correct but benign.
150   if (S.getLangOpts().CPlusPlus)
151     return;
152 
153   // Check if this is an inlined function or method.
154   FunctionDecl *Current = S.getCurFunctionDecl();
155   if (!Current)
156     return;
157   if (!Current->isInlined())
158     return;
159   if (!Current->isExternallyVisible())
160     return;
161 
162   // Check if the decl has internal linkage.
163   if (D->getFormalLinkage() != InternalLinkage)
164     return;
165 
166   // Downgrade from ExtWarn to Extension if
167   //  (1) the supposedly external inline function is in the main file,
168   //      and probably won't be included anywhere else.
169   //  (2) the thing we're referencing is a pure function.
170   //  (3) the thing we're referencing is another inline function.
171   // This last can give us false negatives, but it's better than warning on
172   // wrappers for simple C library functions.
173   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
174   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
175   if (!DowngradeWarning && UsedFn)
176     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
177 
178   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
179                                : diag::ext_internal_in_extern_inline)
180     << /*IsVar=*/!UsedFn << D;
181 
182   S.MaybeSuggestAddingStaticToDecl(Current);
183 
184   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
185       << D;
186 }
187 
188 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
189   const FunctionDecl *First = Cur->getFirstDecl();
190 
191   // Suggest "static" on the function, if possible.
192   if (!hasAnyExplicitStorageClass(First)) {
193     SourceLocation DeclBegin = First->getSourceRange().getBegin();
194     Diag(DeclBegin, diag::note_convert_inline_to_static)
195       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
196   }
197 }
198 
199 /// Determine whether the use of this declaration is valid, and
200 /// emit any corresponding diagnostics.
201 ///
202 /// This routine diagnoses various problems with referencing
203 /// declarations that can occur when using a declaration. For example,
204 /// it might warn if a deprecated or unavailable declaration is being
205 /// used, or produce an error (and return true) if a C++0x deleted
206 /// function is being used.
207 ///
208 /// \returns true if there was an error (this declaration cannot be
209 /// referenced), false otherwise.
210 ///
211 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
212                              const ObjCInterfaceDecl *UnknownObjCClass,
213                              bool ObjCPropertyAccess,
214                              bool AvoidPartialAvailabilityChecks,
215                              ObjCInterfaceDecl *ClassReceiver) {
216   SourceLocation Loc = Locs.front();
217   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
218     // If there were any diagnostics suppressed by template argument deduction,
219     // emit them now.
220     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
221     if (Pos != SuppressedDiagnostics.end()) {
222       for (const PartialDiagnosticAt &Suppressed : Pos->second)
223         Diag(Suppressed.first, Suppressed.second);
224 
225       // Clear out the list of suppressed diagnostics, so that we don't emit
226       // them again for this specialization. However, we don't obsolete this
227       // entry from the table, because we want to avoid ever emitting these
228       // diagnostics again.
229       Pos->second.clear();
230     }
231 
232     // C++ [basic.start.main]p3:
233     //   The function 'main' shall not be used within a program.
234     if (cast<FunctionDecl>(D)->isMain())
235       Diag(Loc, diag::ext_main_used);
236 
237     diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
238   }
239 
240   // See if this is an auto-typed variable whose initializer we are parsing.
241   if (ParsingInitForAutoVars.count(D)) {
242     if (isa<BindingDecl>(D)) {
243       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
244         << D->getDeclName();
245     } else {
246       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
247         << D->getDeclName() << cast<VarDecl>(D)->getType();
248     }
249     return true;
250   }
251 
252   // See if this is a deleted function.
253   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
254     if (FD->isDeleted()) {
255       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
256       if (Ctor && Ctor->isInheritingConstructor())
257         Diag(Loc, diag::err_deleted_inherited_ctor_use)
258             << Ctor->getParent()
259             << Ctor->getInheritedConstructor().getConstructor()->getParent();
260       else
261         Diag(Loc, diag::err_deleted_function_use);
262       NoteDeletedFunction(FD);
263       return true;
264     }
265 
266     // If the function has a deduced return type, and we can't deduce it,
267     // then we can't use it either.
268     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
269         DeduceReturnType(FD, Loc))
270       return true;
271 
272     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
273       return true;
274   }
275 
276   if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
277     // Lambdas are only default-constructible or assignable in C++2a onwards.
278     if (MD->getParent()->isLambda() &&
279         ((isa<CXXConstructorDecl>(MD) &&
280           cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
281          MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
282       Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
283         << !isa<CXXConstructorDecl>(MD);
284     }
285   }
286 
287   auto getReferencedObjCProp = [](const NamedDecl *D) ->
288                                       const ObjCPropertyDecl * {
289     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
290       return MD->findPropertyDecl();
291     return nullptr;
292   };
293   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
294     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
295       return true;
296   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
297       return true;
298   }
299 
300   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
301   // Only the variables omp_in and omp_out are allowed in the combiner.
302   // Only the variables omp_priv and omp_orig are allowed in the
303   // initializer-clause.
304   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
305   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
306       isa<VarDecl>(D)) {
307     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
308         << getCurFunction()->HasOMPDeclareReductionCombiner;
309     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
310     return true;
311   }
312 
313   // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
314   //  List-items in map clauses on this construct may only refer to the declared
315   //  variable var and entities that could be referenced by a procedure defined
316   //  at the same location
317   auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext);
318   if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) &&
319       isa<VarDecl>(D)) {
320     Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
321         << DMD->getVarName().getAsString();
322     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
323     return true;
324   }
325 
326   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
327                              AvoidPartialAvailabilityChecks, ClassReceiver);
328 
329   DiagnoseUnusedOfDecl(*this, D, Loc);
330 
331   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
332 
333   return false;
334 }
335 
336 /// DiagnoseSentinelCalls - This routine checks whether a call or
337 /// message-send is to a declaration with the sentinel attribute, and
338 /// if so, it checks that the requirements of the sentinel are
339 /// satisfied.
340 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
341                                  ArrayRef<Expr *> Args) {
342   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
343   if (!attr)
344     return;
345 
346   // The number of formal parameters of the declaration.
347   unsigned numFormalParams;
348 
349   // The kind of declaration.  This is also an index into a %select in
350   // the diagnostic.
351   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
352 
353   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
354     numFormalParams = MD->param_size();
355     calleeType = CT_Method;
356   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
357     numFormalParams = FD->param_size();
358     calleeType = CT_Function;
359   } else if (isa<VarDecl>(D)) {
360     QualType type = cast<ValueDecl>(D)->getType();
361     const FunctionType *fn = nullptr;
362     if (const PointerType *ptr = type->getAs<PointerType>()) {
363       fn = ptr->getPointeeType()->getAs<FunctionType>();
364       if (!fn) return;
365       calleeType = CT_Function;
366     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
367       fn = ptr->getPointeeType()->castAs<FunctionType>();
368       calleeType = CT_Block;
369     } else {
370       return;
371     }
372 
373     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
374       numFormalParams = proto->getNumParams();
375     } else {
376       numFormalParams = 0;
377     }
378   } else {
379     return;
380   }
381 
382   // "nullPos" is the number of formal parameters at the end which
383   // effectively count as part of the variadic arguments.  This is
384   // useful if you would prefer to not have *any* formal parameters,
385   // but the language forces you to have at least one.
386   unsigned nullPos = attr->getNullPos();
387   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
388   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
389 
390   // The number of arguments which should follow the sentinel.
391   unsigned numArgsAfterSentinel = attr->getSentinel();
392 
393   // If there aren't enough arguments for all the formal parameters,
394   // the sentinel, and the args after the sentinel, complain.
395   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
396     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
397     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
398     return;
399   }
400 
401   // Otherwise, find the sentinel expression.
402   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
403   if (!sentinelExpr) return;
404   if (sentinelExpr->isValueDependent()) return;
405   if (Context.isSentinelNullExpr(sentinelExpr)) return;
406 
407   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
408   // or 'NULL' if those are actually defined in the context.  Only use
409   // 'nil' for ObjC methods, where it's much more likely that the
410   // variadic arguments form a list of object pointers.
411   SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
412   std::string NullValue;
413   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
414     NullValue = "nil";
415   else if (getLangOpts().CPlusPlus11)
416     NullValue = "nullptr";
417   else if (PP.isMacroDefined("NULL"))
418     NullValue = "NULL";
419   else
420     NullValue = "(void*) 0";
421 
422   if (MissingNilLoc.isInvalid())
423     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
424   else
425     Diag(MissingNilLoc, diag::warn_missing_sentinel)
426       << int(calleeType)
427       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
428   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
429 }
430 
431 SourceRange Sema::getExprRange(Expr *E) const {
432   return E ? E->getSourceRange() : SourceRange();
433 }
434 
435 //===----------------------------------------------------------------------===//
436 //  Standard Promotions and Conversions
437 //===----------------------------------------------------------------------===//
438 
439 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
440 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
441   // Handle any placeholder expressions which made it here.
442   if (E->getType()->isPlaceholderType()) {
443     ExprResult result = CheckPlaceholderExpr(E);
444     if (result.isInvalid()) return ExprError();
445     E = result.get();
446   }
447 
448   QualType Ty = E->getType();
449   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
450 
451   if (Ty->isFunctionType()) {
452     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
453       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
454         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
455           return ExprError();
456 
457     E = ImpCastExprToType(E, Context.getPointerType(Ty),
458                           CK_FunctionToPointerDecay).get();
459   } else if (Ty->isArrayType()) {
460     // In C90 mode, arrays only promote to pointers if the array expression is
461     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
462     // type 'array of type' is converted to an expression that has type 'pointer
463     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
464     // that has type 'array of type' ...".  The relevant change is "an lvalue"
465     // (C90) to "an expression" (C99).
466     //
467     // C++ 4.2p1:
468     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
469     // T" can be converted to an rvalue of type "pointer to T".
470     //
471     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
472       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
473                             CK_ArrayToPointerDecay).get();
474   }
475   return E;
476 }
477 
478 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
479   // Check to see if we are dereferencing a null pointer.  If so,
480   // and if not volatile-qualified, this is undefined behavior that the
481   // optimizer will delete, so warn about it.  People sometimes try to use this
482   // to get a deterministic trap and are surprised by clang's behavior.  This
483   // only handles the pattern "*null", which is a very syntactic check.
484   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
485     if (UO->getOpcode() == UO_Deref &&
486         UO->getSubExpr()->IgnoreParenCasts()->
487           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
488         !UO->getType().isVolatileQualified()) {
489     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
490                           S.PDiag(diag::warn_indirection_through_null)
491                             << UO->getSubExpr()->getSourceRange());
492     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
493                         S.PDiag(diag::note_indirection_through_null));
494   }
495 }
496 
497 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
498                                     SourceLocation AssignLoc,
499                                     const Expr* RHS) {
500   const ObjCIvarDecl *IV = OIRE->getDecl();
501   if (!IV)
502     return;
503 
504   DeclarationName MemberName = IV->getDeclName();
505   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
506   if (!Member || !Member->isStr("isa"))
507     return;
508 
509   const Expr *Base = OIRE->getBase();
510   QualType BaseType = Base->getType();
511   if (OIRE->isArrow())
512     BaseType = BaseType->getPointeeType();
513   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
514     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
515       ObjCInterfaceDecl *ClassDeclared = nullptr;
516       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
517       if (!ClassDeclared->getSuperClass()
518           && (*ClassDeclared->ivar_begin()) == IV) {
519         if (RHS) {
520           NamedDecl *ObjectSetClass =
521             S.LookupSingleName(S.TUScope,
522                                &S.Context.Idents.get("object_setClass"),
523                                SourceLocation(), S.LookupOrdinaryName);
524           if (ObjectSetClass) {
525             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
526             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
527                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
528                                               "object_setClass(")
529                 << FixItHint::CreateReplacement(
530                        SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
531                 << FixItHint::CreateInsertion(RHSLocEnd, ")");
532           }
533           else
534             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
535         } else {
536           NamedDecl *ObjectGetClass =
537             S.LookupSingleName(S.TUScope,
538                                &S.Context.Idents.get("object_getClass"),
539                                SourceLocation(), S.LookupOrdinaryName);
540           if (ObjectGetClass)
541             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
542                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
543                                               "object_getClass(")
544                 << FixItHint::CreateReplacement(
545                        SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
546           else
547             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
548         }
549         S.Diag(IV->getLocation(), diag::note_ivar_decl);
550       }
551     }
552 }
553 
554 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
555   // Handle any placeholder expressions which made it here.
556   if (E->getType()->isPlaceholderType()) {
557     ExprResult result = CheckPlaceholderExpr(E);
558     if (result.isInvalid()) return ExprError();
559     E = result.get();
560   }
561 
562   // C++ [conv.lval]p1:
563   //   A glvalue of a non-function, non-array type T can be
564   //   converted to a prvalue.
565   if (!E->isGLValue()) return E;
566 
567   QualType T = E->getType();
568   assert(!T.isNull() && "r-value conversion on typeless expression?");
569 
570   // We don't want to throw lvalue-to-rvalue casts on top of
571   // expressions of certain types in C++.
572   if (getLangOpts().CPlusPlus &&
573       (E->getType() == Context.OverloadTy ||
574        T->isDependentType() ||
575        T->isRecordType()))
576     return E;
577 
578   // The C standard is actually really unclear on this point, and
579   // DR106 tells us what the result should be but not why.  It's
580   // generally best to say that void types just doesn't undergo
581   // lvalue-to-rvalue at all.  Note that expressions of unqualified
582   // 'void' type are never l-values, but qualified void can be.
583   if (T->isVoidType())
584     return E;
585 
586   // OpenCL usually rejects direct accesses to values of 'half' type.
587   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
588       T->isHalfType()) {
589     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
590       << 0 << T;
591     return ExprError();
592   }
593 
594   CheckForNullPointerDereference(*this, E);
595   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
596     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
597                                      &Context.Idents.get("object_getClass"),
598                                      SourceLocation(), LookupOrdinaryName);
599     if (ObjectGetClass)
600       Diag(E->getExprLoc(), diag::warn_objc_isa_use)
601           << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
602           << FixItHint::CreateReplacement(
603                  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
604     else
605       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
606   }
607   else if (const ObjCIvarRefExpr *OIRE =
608             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
609     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
610 
611   // C++ [conv.lval]p1:
612   //   [...] If T is a non-class type, the type of the prvalue is the
613   //   cv-unqualified version of T. Otherwise, the type of the
614   //   rvalue is T.
615   //
616   // C99 6.3.2.1p2:
617   //   If the lvalue has qualified type, the value has the unqualified
618   //   version of the type of the lvalue; otherwise, the value has the
619   //   type of the lvalue.
620   if (T.hasQualifiers())
621     T = T.getUnqualifiedType();
622 
623   // Under the MS ABI, lock down the inheritance model now.
624   if (T->isMemberPointerType() &&
625       Context.getTargetInfo().getCXXABI().isMicrosoft())
626     (void)isCompleteType(E->getExprLoc(), T);
627 
628   ExprResult Res = CheckLValueToRValueConversionOperand(E);
629   if (Res.isInvalid())
630     return Res;
631   E = Res.get();
632 
633   // Loading a __weak object implicitly retains the value, so we need a cleanup to
634   // balance that.
635   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
636     Cleanup.setExprNeedsCleanups(true);
637 
638   // C++ [conv.lval]p3:
639   //   If T is cv std::nullptr_t, the result is a null pointer constant.
640   CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
641   Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue);
642 
643   // C11 6.3.2.1p2:
644   //   ... if the lvalue has atomic type, the value has the non-atomic version
645   //   of the type of the lvalue ...
646   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
647     T = Atomic->getValueType().getUnqualifiedType();
648     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
649                                    nullptr, VK_RValue);
650   }
651 
652   return Res;
653 }
654 
655 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
656   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
657   if (Res.isInvalid())
658     return ExprError();
659   Res = DefaultLvalueConversion(Res.get());
660   if (Res.isInvalid())
661     return ExprError();
662   return Res;
663 }
664 
665 /// CallExprUnaryConversions - a special case of an unary conversion
666 /// performed on a function designator of a call expression.
667 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
668   QualType Ty = E->getType();
669   ExprResult Res = E;
670   // Only do implicit cast for a function type, but not for a pointer
671   // to function type.
672   if (Ty->isFunctionType()) {
673     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
674                             CK_FunctionToPointerDecay).get();
675     if (Res.isInvalid())
676       return ExprError();
677   }
678   Res = DefaultLvalueConversion(Res.get());
679   if (Res.isInvalid())
680     return ExprError();
681   return Res.get();
682 }
683 
684 /// UsualUnaryConversions - Performs various conversions that are common to most
685 /// operators (C99 6.3). The conversions of array and function types are
686 /// sometimes suppressed. For example, the array->pointer conversion doesn't
687 /// apply if the array is an argument to the sizeof or address (&) operators.
688 /// In these instances, this routine should *not* be called.
689 ExprResult Sema::UsualUnaryConversions(Expr *E) {
690   // First, convert to an r-value.
691   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
692   if (Res.isInvalid())
693     return ExprError();
694   E = Res.get();
695 
696   QualType Ty = E->getType();
697   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
698 
699   // Half FP have to be promoted to float unless it is natively supported
700   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
701     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
702 
703   // Try to perform integral promotions if the object has a theoretically
704   // promotable type.
705   if (Ty->isIntegralOrUnscopedEnumerationType()) {
706     // C99 6.3.1.1p2:
707     //
708     //   The following may be used in an expression wherever an int or
709     //   unsigned int may be used:
710     //     - an object or expression with an integer type whose integer
711     //       conversion rank is less than or equal to the rank of int
712     //       and unsigned int.
713     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
714     //
715     //   If an int can represent all values of the original type, the
716     //   value is converted to an int; otherwise, it is converted to an
717     //   unsigned int. These are called the integer promotions. All
718     //   other types are unchanged by the integer promotions.
719 
720     QualType PTy = Context.isPromotableBitField(E);
721     if (!PTy.isNull()) {
722       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
723       return E;
724     }
725     if (Ty->isPromotableIntegerType()) {
726       QualType PT = Context.getPromotedIntegerType(Ty);
727       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
728       return E;
729     }
730   }
731   return E;
732 }
733 
734 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
735 /// do not have a prototype. Arguments that have type float or __fp16
736 /// are promoted to double. All other argument types are converted by
737 /// UsualUnaryConversions().
738 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
739   QualType Ty = E->getType();
740   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
741 
742   ExprResult Res = UsualUnaryConversions(E);
743   if (Res.isInvalid())
744     return ExprError();
745   E = Res.get();
746 
747   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
748   // promote to double.
749   // Note that default argument promotion applies only to float (and
750   // half/fp16); it does not apply to _Float16.
751   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
752   if (BTy && (BTy->getKind() == BuiltinType::Half ||
753               BTy->getKind() == BuiltinType::Float)) {
754     if (getLangOpts().OpenCL &&
755         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
756         if (BTy->getKind() == BuiltinType::Half) {
757             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
758         }
759     } else {
760       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
761     }
762   }
763 
764   // C++ performs lvalue-to-rvalue conversion as a default argument
765   // promotion, even on class types, but note:
766   //   C++11 [conv.lval]p2:
767   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
768   //     operand or a subexpression thereof the value contained in the
769   //     referenced object is not accessed. Otherwise, if the glvalue
770   //     has a class type, the conversion copy-initializes a temporary
771   //     of type T from the glvalue and the result of the conversion
772   //     is a prvalue for the temporary.
773   // FIXME: add some way to gate this entire thing for correctness in
774   // potentially potentially evaluated contexts.
775   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
776     ExprResult Temp = PerformCopyInitialization(
777                        InitializedEntity::InitializeTemporary(E->getType()),
778                                                 E->getExprLoc(), E);
779     if (Temp.isInvalid())
780       return ExprError();
781     E = Temp.get();
782   }
783 
784   return E;
785 }
786 
787 /// Determine the degree of POD-ness for an expression.
788 /// Incomplete types are considered POD, since this check can be performed
789 /// when we're in an unevaluated context.
790 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
791   if (Ty->isIncompleteType()) {
792     // C++11 [expr.call]p7:
793     //   After these conversions, if the argument does not have arithmetic,
794     //   enumeration, pointer, pointer to member, or class type, the program
795     //   is ill-formed.
796     //
797     // Since we've already performed array-to-pointer and function-to-pointer
798     // decay, the only such type in C++ is cv void. This also handles
799     // initializer lists as variadic arguments.
800     if (Ty->isVoidType())
801       return VAK_Invalid;
802 
803     if (Ty->isObjCObjectType())
804       return VAK_Invalid;
805     return VAK_Valid;
806   }
807 
808   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
809     return VAK_Invalid;
810 
811   if (Ty.isCXX98PODType(Context))
812     return VAK_Valid;
813 
814   // C++11 [expr.call]p7:
815   //   Passing a potentially-evaluated argument of class type (Clause 9)
816   //   having a non-trivial copy constructor, a non-trivial move constructor,
817   //   or a non-trivial destructor, with no corresponding parameter,
818   //   is conditionally-supported with implementation-defined semantics.
819   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
820     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
821       if (!Record->hasNonTrivialCopyConstructor() &&
822           !Record->hasNonTrivialMoveConstructor() &&
823           !Record->hasNonTrivialDestructor())
824         return VAK_ValidInCXX11;
825 
826   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
827     return VAK_Valid;
828 
829   if (Ty->isObjCObjectType())
830     return VAK_Invalid;
831 
832   if (getLangOpts().MSVCCompat)
833     return VAK_MSVCUndefined;
834 
835   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
836   // permitted to reject them. We should consider doing so.
837   return VAK_Undefined;
838 }
839 
840 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
841   // Don't allow one to pass an Objective-C interface to a vararg.
842   const QualType &Ty = E->getType();
843   VarArgKind VAK = isValidVarArgType(Ty);
844 
845   // Complain about passing non-POD types through varargs.
846   switch (VAK) {
847   case VAK_ValidInCXX11:
848     DiagRuntimeBehavior(
849         E->getBeginLoc(), nullptr,
850         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
851     LLVM_FALLTHROUGH;
852   case VAK_Valid:
853     if (Ty->isRecordType()) {
854       // This is unlikely to be what the user intended. If the class has a
855       // 'c_str' member function, the user probably meant to call that.
856       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
857                           PDiag(diag::warn_pass_class_arg_to_vararg)
858                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
859     }
860     break;
861 
862   case VAK_Undefined:
863   case VAK_MSVCUndefined:
864     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
865                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
866                             << getLangOpts().CPlusPlus11 << Ty << CT);
867     break;
868 
869   case VAK_Invalid:
870     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
871       Diag(E->getBeginLoc(),
872            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
873           << Ty << CT;
874     else if (Ty->isObjCObjectType())
875       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
876                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
877                               << Ty << CT);
878     else
879       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
880           << isa<InitListExpr>(E) << Ty << CT;
881     break;
882   }
883 }
884 
885 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
886 /// will create a trap if the resulting type is not a POD type.
887 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
888                                                   FunctionDecl *FDecl) {
889   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
890     // Strip the unbridged-cast placeholder expression off, if applicable.
891     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
892         (CT == VariadicMethod ||
893          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
894       E = stripARCUnbridgedCast(E);
895 
896     // Otherwise, do normal placeholder checking.
897     } else {
898       ExprResult ExprRes = CheckPlaceholderExpr(E);
899       if (ExprRes.isInvalid())
900         return ExprError();
901       E = ExprRes.get();
902     }
903   }
904 
905   ExprResult ExprRes = DefaultArgumentPromotion(E);
906   if (ExprRes.isInvalid())
907     return ExprError();
908   E = ExprRes.get();
909 
910   // Diagnostics regarding non-POD argument types are
911   // emitted along with format string checking in Sema::CheckFunctionCall().
912   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
913     // Turn this into a trap.
914     CXXScopeSpec SS;
915     SourceLocation TemplateKWLoc;
916     UnqualifiedId Name;
917     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
918                        E->getBeginLoc());
919     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
920                                           /*HasTrailingLParen=*/true,
921                                           /*IsAddressOfOperand=*/false);
922     if (TrapFn.isInvalid())
923       return ExprError();
924 
925     ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
926                                     None, E->getEndLoc());
927     if (Call.isInvalid())
928       return ExprError();
929 
930     ExprResult Comma =
931         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
932     if (Comma.isInvalid())
933       return ExprError();
934     return Comma.get();
935   }
936 
937   if (!getLangOpts().CPlusPlus &&
938       RequireCompleteType(E->getExprLoc(), E->getType(),
939                           diag::err_call_incomplete_argument))
940     return ExprError();
941 
942   return E;
943 }
944 
945 /// Converts an integer to complex float type.  Helper function of
946 /// UsualArithmeticConversions()
947 ///
948 /// \return false if the integer expression is an integer type and is
949 /// successfully converted to the complex type.
950 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
951                                                   ExprResult &ComplexExpr,
952                                                   QualType IntTy,
953                                                   QualType ComplexTy,
954                                                   bool SkipCast) {
955   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
956   if (SkipCast) return false;
957   if (IntTy->isIntegerType()) {
958     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
959     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
960     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
961                                   CK_FloatingRealToComplex);
962   } else {
963     assert(IntTy->isComplexIntegerType());
964     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
965                                   CK_IntegralComplexToFloatingComplex);
966   }
967   return false;
968 }
969 
970 /// Handle arithmetic conversion with complex types.  Helper function of
971 /// UsualArithmeticConversions()
972 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
973                                              ExprResult &RHS, QualType LHSType,
974                                              QualType RHSType,
975                                              bool IsCompAssign) {
976   // if we have an integer operand, the result is the complex type.
977   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
978                                              /*skipCast*/false))
979     return LHSType;
980   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
981                                              /*skipCast*/IsCompAssign))
982     return RHSType;
983 
984   // This handles complex/complex, complex/float, or float/complex.
985   // When both operands are complex, the shorter operand is converted to the
986   // type of the longer, and that is the type of the result. This corresponds
987   // to what is done when combining two real floating-point operands.
988   // The fun begins when size promotion occur across type domains.
989   // From H&S 6.3.4: When one operand is complex and the other is a real
990   // floating-point type, the less precise type is converted, within it's
991   // real or complex domain, to the precision of the other type. For example,
992   // when combining a "long double" with a "double _Complex", the
993   // "double _Complex" is promoted to "long double _Complex".
994 
995   // Compute the rank of the two types, regardless of whether they are complex.
996   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
997 
998   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
999   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1000   QualType LHSElementType =
1001       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1002   QualType RHSElementType =
1003       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1004 
1005   QualType ResultType = S.Context.getComplexType(LHSElementType);
1006   if (Order < 0) {
1007     // Promote the precision of the LHS if not an assignment.
1008     ResultType = S.Context.getComplexType(RHSElementType);
1009     if (!IsCompAssign) {
1010       if (LHSComplexType)
1011         LHS =
1012             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1013       else
1014         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1015     }
1016   } else if (Order > 0) {
1017     // Promote the precision of the RHS.
1018     if (RHSComplexType)
1019       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1020     else
1021       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1022   }
1023   return ResultType;
1024 }
1025 
1026 /// Handle arithmetic conversion from integer to float.  Helper function
1027 /// of UsualArithmeticConversions()
1028 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1029                                            ExprResult &IntExpr,
1030                                            QualType FloatTy, QualType IntTy,
1031                                            bool ConvertFloat, bool ConvertInt) {
1032   if (IntTy->isIntegerType()) {
1033     if (ConvertInt)
1034       // Convert intExpr to the lhs floating point type.
1035       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1036                                     CK_IntegralToFloating);
1037     return FloatTy;
1038   }
1039 
1040   // Convert both sides to the appropriate complex float.
1041   assert(IntTy->isComplexIntegerType());
1042   QualType result = S.Context.getComplexType(FloatTy);
1043 
1044   // _Complex int -> _Complex float
1045   if (ConvertInt)
1046     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1047                                   CK_IntegralComplexToFloatingComplex);
1048 
1049   // float -> _Complex float
1050   if (ConvertFloat)
1051     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1052                                     CK_FloatingRealToComplex);
1053 
1054   return result;
1055 }
1056 
1057 /// Handle arithmethic conversion with floating point types.  Helper
1058 /// function of UsualArithmeticConversions()
1059 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1060                                       ExprResult &RHS, QualType LHSType,
1061                                       QualType RHSType, bool IsCompAssign) {
1062   bool LHSFloat = LHSType->isRealFloatingType();
1063   bool RHSFloat = RHSType->isRealFloatingType();
1064 
1065   // If we have two real floating types, convert the smaller operand
1066   // to the bigger result.
1067   if (LHSFloat && RHSFloat) {
1068     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1069     if (order > 0) {
1070       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1071       return LHSType;
1072     }
1073 
1074     assert(order < 0 && "illegal float comparison");
1075     if (!IsCompAssign)
1076       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1077     return RHSType;
1078   }
1079 
1080   if (LHSFloat) {
1081     // Half FP has to be promoted to float unless it is natively supported
1082     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1083       LHSType = S.Context.FloatTy;
1084 
1085     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1086                                       /*convertFloat=*/!IsCompAssign,
1087                                       /*convertInt=*/ true);
1088   }
1089   assert(RHSFloat);
1090   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1091                                     /*convertInt=*/ true,
1092                                     /*convertFloat=*/!IsCompAssign);
1093 }
1094 
1095 /// Diagnose attempts to convert between __float128 and long double if
1096 /// there is no support for such conversion. Helper function of
1097 /// UsualArithmeticConversions().
1098 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1099                                       QualType RHSType) {
1100   /*  No issue converting if at least one of the types is not a floating point
1101       type or the two types have the same rank.
1102   */
1103   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1104       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1105     return false;
1106 
1107   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1108          "The remaining types must be floating point types.");
1109 
1110   auto *LHSComplex = LHSType->getAs<ComplexType>();
1111   auto *RHSComplex = RHSType->getAs<ComplexType>();
1112 
1113   QualType LHSElemType = LHSComplex ?
1114     LHSComplex->getElementType() : LHSType;
1115   QualType RHSElemType = RHSComplex ?
1116     RHSComplex->getElementType() : RHSType;
1117 
1118   // No issue if the two types have the same representation
1119   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1120       &S.Context.getFloatTypeSemantics(RHSElemType))
1121     return false;
1122 
1123   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1124                                 RHSElemType == S.Context.LongDoubleTy);
1125   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1126                             RHSElemType == S.Context.Float128Ty);
1127 
1128   // We've handled the situation where __float128 and long double have the same
1129   // representation. We allow all conversions for all possible long double types
1130   // except PPC's double double.
1131   return Float128AndLongDouble &&
1132     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1133      &llvm::APFloat::PPCDoubleDouble());
1134 }
1135 
1136 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1137 
1138 namespace {
1139 /// These helper callbacks are placed in an anonymous namespace to
1140 /// permit their use as function template parameters.
1141 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1142   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1143 }
1144 
1145 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1146   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1147                              CK_IntegralComplexCast);
1148 }
1149 }
1150 
1151 /// Handle integer arithmetic conversions.  Helper function of
1152 /// UsualArithmeticConversions()
1153 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1154 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1155                                         ExprResult &RHS, QualType LHSType,
1156                                         QualType RHSType, bool IsCompAssign) {
1157   // The rules for this case are in C99 6.3.1.8
1158   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1159   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1160   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1161   if (LHSSigned == RHSSigned) {
1162     // Same signedness; use the higher-ranked type
1163     if (order >= 0) {
1164       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1165       return LHSType;
1166     } else if (!IsCompAssign)
1167       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1168     return RHSType;
1169   } else if (order != (LHSSigned ? 1 : -1)) {
1170     // The unsigned type has greater than or equal rank to the
1171     // signed type, so use the unsigned type
1172     if (RHSSigned) {
1173       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1174       return LHSType;
1175     } else if (!IsCompAssign)
1176       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1177     return RHSType;
1178   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1179     // The two types are different widths; if we are here, that
1180     // means the signed type is larger than the unsigned type, so
1181     // use the signed type.
1182     if (LHSSigned) {
1183       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1184       return LHSType;
1185     } else if (!IsCompAssign)
1186       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1187     return RHSType;
1188   } else {
1189     // The signed type is higher-ranked than the unsigned type,
1190     // but isn't actually any bigger (like unsigned int and long
1191     // on most 32-bit systems).  Use the unsigned type corresponding
1192     // to the signed type.
1193     QualType result =
1194       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1195     RHS = (*doRHSCast)(S, RHS.get(), result);
1196     if (!IsCompAssign)
1197       LHS = (*doLHSCast)(S, LHS.get(), result);
1198     return result;
1199   }
1200 }
1201 
1202 /// Handle conversions with GCC complex int extension.  Helper function
1203 /// of UsualArithmeticConversions()
1204 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1205                                            ExprResult &RHS, QualType LHSType,
1206                                            QualType RHSType,
1207                                            bool IsCompAssign) {
1208   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1209   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1210 
1211   if (LHSComplexInt && RHSComplexInt) {
1212     QualType LHSEltType = LHSComplexInt->getElementType();
1213     QualType RHSEltType = RHSComplexInt->getElementType();
1214     QualType ScalarType =
1215       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1216         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1217 
1218     return S.Context.getComplexType(ScalarType);
1219   }
1220 
1221   if (LHSComplexInt) {
1222     QualType LHSEltType = LHSComplexInt->getElementType();
1223     QualType ScalarType =
1224       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1225         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1226     QualType ComplexType = S.Context.getComplexType(ScalarType);
1227     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1228                               CK_IntegralRealToComplex);
1229 
1230     return ComplexType;
1231   }
1232 
1233   assert(RHSComplexInt);
1234 
1235   QualType RHSEltType = RHSComplexInt->getElementType();
1236   QualType ScalarType =
1237     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1238       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1239   QualType ComplexType = S.Context.getComplexType(ScalarType);
1240 
1241   if (!IsCompAssign)
1242     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1243                               CK_IntegralRealToComplex);
1244   return ComplexType;
1245 }
1246 
1247 /// Return the rank of a given fixed point or integer type. The value itself
1248 /// doesn't matter, but the values must be increasing with proper increasing
1249 /// rank as described in N1169 4.1.1.
1250 static unsigned GetFixedPointRank(QualType Ty) {
1251   const auto *BTy = Ty->getAs<BuiltinType>();
1252   assert(BTy && "Expected a builtin type.");
1253 
1254   switch (BTy->getKind()) {
1255   case BuiltinType::ShortFract:
1256   case BuiltinType::UShortFract:
1257   case BuiltinType::SatShortFract:
1258   case BuiltinType::SatUShortFract:
1259     return 1;
1260   case BuiltinType::Fract:
1261   case BuiltinType::UFract:
1262   case BuiltinType::SatFract:
1263   case BuiltinType::SatUFract:
1264     return 2;
1265   case BuiltinType::LongFract:
1266   case BuiltinType::ULongFract:
1267   case BuiltinType::SatLongFract:
1268   case BuiltinType::SatULongFract:
1269     return 3;
1270   case BuiltinType::ShortAccum:
1271   case BuiltinType::UShortAccum:
1272   case BuiltinType::SatShortAccum:
1273   case BuiltinType::SatUShortAccum:
1274     return 4;
1275   case BuiltinType::Accum:
1276   case BuiltinType::UAccum:
1277   case BuiltinType::SatAccum:
1278   case BuiltinType::SatUAccum:
1279     return 5;
1280   case BuiltinType::LongAccum:
1281   case BuiltinType::ULongAccum:
1282   case BuiltinType::SatLongAccum:
1283   case BuiltinType::SatULongAccum:
1284     return 6;
1285   default:
1286     if (BTy->isInteger())
1287       return 0;
1288     llvm_unreachable("Unexpected fixed point or integer type");
1289   }
1290 }
1291 
1292 /// handleFixedPointConversion - Fixed point operations between fixed
1293 /// point types and integers or other fixed point types do not fall under
1294 /// usual arithmetic conversion since these conversions could result in loss
1295 /// of precsision (N1169 4.1.4). These operations should be calculated with
1296 /// the full precision of their result type (N1169 4.1.6.2.1).
1297 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1298                                            QualType RHSTy) {
1299   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1300          "Expected at least one of the operands to be a fixed point type");
1301   assert((LHSTy->isFixedPointOrIntegerType() ||
1302           RHSTy->isFixedPointOrIntegerType()) &&
1303          "Special fixed point arithmetic operation conversions are only "
1304          "applied to ints or other fixed point types");
1305 
1306   // If one operand has signed fixed-point type and the other operand has
1307   // unsigned fixed-point type, then the unsigned fixed-point operand is
1308   // converted to its corresponding signed fixed-point type and the resulting
1309   // type is the type of the converted operand.
1310   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1311     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1312   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1313     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1314 
1315   // The result type is the type with the highest rank, whereby a fixed-point
1316   // conversion rank is always greater than an integer conversion rank; if the
1317   // type of either of the operands is a saturating fixedpoint type, the result
1318   // type shall be the saturating fixed-point type corresponding to the type
1319   // with the highest rank; the resulting value is converted (taking into
1320   // account rounding and overflow) to the precision of the resulting type.
1321   // Same ranks between signed and unsigned types are resolved earlier, so both
1322   // types are either signed or both unsigned at this point.
1323   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1324   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1325 
1326   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1327 
1328   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1329     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1330 
1331   return ResultTy;
1332 }
1333 
1334 /// UsualArithmeticConversions - Performs various conversions that are common to
1335 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1336 /// routine returns the first non-arithmetic type found. The client is
1337 /// responsible for emitting appropriate error diagnostics.
1338 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1339                                           bool IsCompAssign) {
1340   if (!IsCompAssign) {
1341     LHS = UsualUnaryConversions(LHS.get());
1342     if (LHS.isInvalid())
1343       return QualType();
1344   }
1345 
1346   RHS = UsualUnaryConversions(RHS.get());
1347   if (RHS.isInvalid())
1348     return QualType();
1349 
1350   // For conversion purposes, we ignore any qualifiers.
1351   // For example, "const float" and "float" are equivalent.
1352   QualType LHSType =
1353     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1354   QualType RHSType =
1355     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1356 
1357   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1358   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1359     LHSType = AtomicLHS->getValueType();
1360 
1361   // If both types are identical, no conversion is needed.
1362   if (LHSType == RHSType)
1363     return LHSType;
1364 
1365   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1366   // The caller can deal with this (e.g. pointer + int).
1367   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1368     return QualType();
1369 
1370   // Apply unary and bitfield promotions to the LHS's type.
1371   QualType LHSUnpromotedType = LHSType;
1372   if (LHSType->isPromotableIntegerType())
1373     LHSType = Context.getPromotedIntegerType(LHSType);
1374   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1375   if (!LHSBitfieldPromoteTy.isNull())
1376     LHSType = LHSBitfieldPromoteTy;
1377   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1378     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1379 
1380   // If both types are identical, no conversion is needed.
1381   if (LHSType == RHSType)
1382     return LHSType;
1383 
1384   // At this point, we have two different arithmetic types.
1385 
1386   // Diagnose attempts to convert between __float128 and long double where
1387   // such conversions currently can't be handled.
1388   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1389     return QualType();
1390 
1391   // Handle complex types first (C99 6.3.1.8p1).
1392   if (LHSType->isComplexType() || RHSType->isComplexType())
1393     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1394                                         IsCompAssign);
1395 
1396   // Now handle "real" floating types (i.e. float, double, long double).
1397   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1398     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1399                                  IsCompAssign);
1400 
1401   // Handle GCC complex int extension.
1402   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1403     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1404                                       IsCompAssign);
1405 
1406   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1407     return handleFixedPointConversion(*this, LHSType, RHSType);
1408 
1409   // Finally, we have two differing integer types.
1410   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1411            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1412 }
1413 
1414 //===----------------------------------------------------------------------===//
1415 //  Semantic Analysis for various Expression Types
1416 //===----------------------------------------------------------------------===//
1417 
1418 
1419 ExprResult
1420 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1421                                 SourceLocation DefaultLoc,
1422                                 SourceLocation RParenLoc,
1423                                 Expr *ControllingExpr,
1424                                 ArrayRef<ParsedType> ArgTypes,
1425                                 ArrayRef<Expr *> ArgExprs) {
1426   unsigned NumAssocs = ArgTypes.size();
1427   assert(NumAssocs == ArgExprs.size());
1428 
1429   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1430   for (unsigned i = 0; i < NumAssocs; ++i) {
1431     if (ArgTypes[i])
1432       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1433     else
1434       Types[i] = nullptr;
1435   }
1436 
1437   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1438                                              ControllingExpr,
1439                                              llvm::makeArrayRef(Types, NumAssocs),
1440                                              ArgExprs);
1441   delete [] Types;
1442   return ER;
1443 }
1444 
1445 ExprResult
1446 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1447                                  SourceLocation DefaultLoc,
1448                                  SourceLocation RParenLoc,
1449                                  Expr *ControllingExpr,
1450                                  ArrayRef<TypeSourceInfo *> Types,
1451                                  ArrayRef<Expr *> Exprs) {
1452   unsigned NumAssocs = Types.size();
1453   assert(NumAssocs == Exprs.size());
1454 
1455   // Decay and strip qualifiers for the controlling expression type, and handle
1456   // placeholder type replacement. See committee discussion from WG14 DR423.
1457   {
1458     EnterExpressionEvaluationContext Unevaluated(
1459         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1460     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1461     if (R.isInvalid())
1462       return ExprError();
1463     ControllingExpr = R.get();
1464   }
1465 
1466   // The controlling expression is an unevaluated operand, so side effects are
1467   // likely unintended.
1468   if (!inTemplateInstantiation() &&
1469       ControllingExpr->HasSideEffects(Context, false))
1470     Diag(ControllingExpr->getExprLoc(),
1471          diag::warn_side_effects_unevaluated_context);
1472 
1473   bool TypeErrorFound = false,
1474        IsResultDependent = ControllingExpr->isTypeDependent(),
1475        ContainsUnexpandedParameterPack
1476          = ControllingExpr->containsUnexpandedParameterPack();
1477 
1478   for (unsigned i = 0; i < NumAssocs; ++i) {
1479     if (Exprs[i]->containsUnexpandedParameterPack())
1480       ContainsUnexpandedParameterPack = true;
1481 
1482     if (Types[i]) {
1483       if (Types[i]->getType()->containsUnexpandedParameterPack())
1484         ContainsUnexpandedParameterPack = true;
1485 
1486       if (Types[i]->getType()->isDependentType()) {
1487         IsResultDependent = true;
1488       } else {
1489         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1490         // complete object type other than a variably modified type."
1491         unsigned D = 0;
1492         if (Types[i]->getType()->isIncompleteType())
1493           D = diag::err_assoc_type_incomplete;
1494         else if (!Types[i]->getType()->isObjectType())
1495           D = diag::err_assoc_type_nonobject;
1496         else if (Types[i]->getType()->isVariablyModifiedType())
1497           D = diag::err_assoc_type_variably_modified;
1498 
1499         if (D != 0) {
1500           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1501             << Types[i]->getTypeLoc().getSourceRange()
1502             << Types[i]->getType();
1503           TypeErrorFound = true;
1504         }
1505 
1506         // C11 6.5.1.1p2 "No two generic associations in the same generic
1507         // selection shall specify compatible types."
1508         for (unsigned j = i+1; j < NumAssocs; ++j)
1509           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1510               Context.typesAreCompatible(Types[i]->getType(),
1511                                          Types[j]->getType())) {
1512             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1513                  diag::err_assoc_compatible_types)
1514               << Types[j]->getTypeLoc().getSourceRange()
1515               << Types[j]->getType()
1516               << Types[i]->getType();
1517             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1518                  diag::note_compat_assoc)
1519               << Types[i]->getTypeLoc().getSourceRange()
1520               << Types[i]->getType();
1521             TypeErrorFound = true;
1522           }
1523       }
1524     }
1525   }
1526   if (TypeErrorFound)
1527     return ExprError();
1528 
1529   // If we determined that the generic selection is result-dependent, don't
1530   // try to compute the result expression.
1531   if (IsResultDependent)
1532     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1533                                         Exprs, DefaultLoc, RParenLoc,
1534                                         ContainsUnexpandedParameterPack);
1535 
1536   SmallVector<unsigned, 1> CompatIndices;
1537   unsigned DefaultIndex = -1U;
1538   for (unsigned i = 0; i < NumAssocs; ++i) {
1539     if (!Types[i])
1540       DefaultIndex = i;
1541     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1542                                         Types[i]->getType()))
1543       CompatIndices.push_back(i);
1544   }
1545 
1546   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1547   // type compatible with at most one of the types named in its generic
1548   // association list."
1549   if (CompatIndices.size() > 1) {
1550     // We strip parens here because the controlling expression is typically
1551     // parenthesized in macro definitions.
1552     ControllingExpr = ControllingExpr->IgnoreParens();
1553     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1554         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1555         << (unsigned)CompatIndices.size();
1556     for (unsigned I : CompatIndices) {
1557       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1558            diag::note_compat_assoc)
1559         << Types[I]->getTypeLoc().getSourceRange()
1560         << Types[I]->getType();
1561     }
1562     return ExprError();
1563   }
1564 
1565   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1566   // its controlling expression shall have type compatible with exactly one of
1567   // the types named in its generic association list."
1568   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1569     // We strip parens here because the controlling expression is typically
1570     // parenthesized in macro definitions.
1571     ControllingExpr = ControllingExpr->IgnoreParens();
1572     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1573         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1574     return ExprError();
1575   }
1576 
1577   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1578   // type name that is compatible with the type of the controlling expression,
1579   // then the result expression of the generic selection is the expression
1580   // in that generic association. Otherwise, the result expression of the
1581   // generic selection is the expression in the default generic association."
1582   unsigned ResultIndex =
1583     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1584 
1585   return GenericSelectionExpr::Create(
1586       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1587       ContainsUnexpandedParameterPack, ResultIndex);
1588 }
1589 
1590 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1591 /// location of the token and the offset of the ud-suffix within it.
1592 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1593                                      unsigned Offset) {
1594   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1595                                         S.getLangOpts());
1596 }
1597 
1598 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1599 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1600 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1601                                                  IdentifierInfo *UDSuffix,
1602                                                  SourceLocation UDSuffixLoc,
1603                                                  ArrayRef<Expr*> Args,
1604                                                  SourceLocation LitEndLoc) {
1605   assert(Args.size() <= 2 && "too many arguments for literal operator");
1606 
1607   QualType ArgTy[2];
1608   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1609     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1610     if (ArgTy[ArgIdx]->isArrayType())
1611       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1612   }
1613 
1614   DeclarationName OpName =
1615     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1616   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1617   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1618 
1619   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1620   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1621                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1622                               /*AllowStringTemplate*/ false,
1623                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1624     return ExprError();
1625 
1626   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1627 }
1628 
1629 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1630 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1631 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1632 /// multiple tokens.  However, the common case is that StringToks points to one
1633 /// string.
1634 ///
1635 ExprResult
1636 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1637   assert(!StringToks.empty() && "Must have at least one string!");
1638 
1639   StringLiteralParser Literal(StringToks, PP);
1640   if (Literal.hadError)
1641     return ExprError();
1642 
1643   SmallVector<SourceLocation, 4> StringTokLocs;
1644   for (const Token &Tok : StringToks)
1645     StringTokLocs.push_back(Tok.getLocation());
1646 
1647   QualType CharTy = Context.CharTy;
1648   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1649   if (Literal.isWide()) {
1650     CharTy = Context.getWideCharType();
1651     Kind = StringLiteral::Wide;
1652   } else if (Literal.isUTF8()) {
1653     if (getLangOpts().Char8)
1654       CharTy = Context.Char8Ty;
1655     Kind = StringLiteral::UTF8;
1656   } else if (Literal.isUTF16()) {
1657     CharTy = Context.Char16Ty;
1658     Kind = StringLiteral::UTF16;
1659   } else if (Literal.isUTF32()) {
1660     CharTy = Context.Char32Ty;
1661     Kind = StringLiteral::UTF32;
1662   } else if (Literal.isPascal()) {
1663     CharTy = Context.UnsignedCharTy;
1664   }
1665 
1666   // Warn on initializing an array of char from a u8 string literal; this
1667   // becomes ill-formed in C++2a.
1668   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a &&
1669       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1670     Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string);
1671 
1672     // Create removals for all 'u8' prefixes in the string literal(s). This
1673     // ensures C++2a compatibility (but may change the program behavior when
1674     // built by non-Clang compilers for which the execution character set is
1675     // not always UTF-8).
1676     auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8);
1677     SourceLocation RemovalDiagLoc;
1678     for (const Token &Tok : StringToks) {
1679       if (Tok.getKind() == tok::utf8_string_literal) {
1680         if (RemovalDiagLoc.isInvalid())
1681           RemovalDiagLoc = Tok.getLocation();
1682         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1683             Tok.getLocation(),
1684             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1685                                            getSourceManager(), getLangOpts())));
1686       }
1687     }
1688     Diag(RemovalDiagLoc, RemovalDiag);
1689   }
1690 
1691   QualType StrTy =
1692       Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1693 
1694   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1695   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1696                                              Kind, Literal.Pascal, StrTy,
1697                                              &StringTokLocs[0],
1698                                              StringTokLocs.size());
1699   if (Literal.getUDSuffix().empty())
1700     return Lit;
1701 
1702   // We're building a user-defined literal.
1703   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1704   SourceLocation UDSuffixLoc =
1705     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1706                    Literal.getUDSuffixOffset());
1707 
1708   // Make sure we're allowed user-defined literals here.
1709   if (!UDLScope)
1710     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1711 
1712   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1713   //   operator "" X (str, len)
1714   QualType SizeType = Context.getSizeType();
1715 
1716   DeclarationName OpName =
1717     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1718   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1719   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1720 
1721   QualType ArgTy[] = {
1722     Context.getArrayDecayedType(StrTy), SizeType
1723   };
1724 
1725   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1726   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1727                                 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1728                                 /*AllowStringTemplate*/ true,
1729                                 /*DiagnoseMissing*/ true)) {
1730 
1731   case LOLR_Cooked: {
1732     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1733     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1734                                                     StringTokLocs[0]);
1735     Expr *Args[] = { Lit, LenArg };
1736 
1737     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1738   }
1739 
1740   case LOLR_StringTemplate: {
1741     TemplateArgumentListInfo ExplicitArgs;
1742 
1743     unsigned CharBits = Context.getIntWidth(CharTy);
1744     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1745     llvm::APSInt Value(CharBits, CharIsUnsigned);
1746 
1747     TemplateArgument TypeArg(CharTy);
1748     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1749     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1750 
1751     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1752       Value = Lit->getCodeUnit(I);
1753       TemplateArgument Arg(Context, Value, CharTy);
1754       TemplateArgumentLocInfo ArgInfo;
1755       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1756     }
1757     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1758                                     &ExplicitArgs);
1759   }
1760   case LOLR_Raw:
1761   case LOLR_Template:
1762   case LOLR_ErrorNoDiagnostic:
1763     llvm_unreachable("unexpected literal operator lookup result");
1764   case LOLR_Error:
1765     return ExprError();
1766   }
1767   llvm_unreachable("unexpected literal operator lookup result");
1768 }
1769 
1770 DeclRefExpr *
1771 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1772                        SourceLocation Loc,
1773                        const CXXScopeSpec *SS) {
1774   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1775   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1776 }
1777 
1778 DeclRefExpr *
1779 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1780                        const DeclarationNameInfo &NameInfo,
1781                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1782                        SourceLocation TemplateKWLoc,
1783                        const TemplateArgumentListInfo *TemplateArgs) {
1784   NestedNameSpecifierLoc NNS =
1785       SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1786   return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1787                           TemplateArgs);
1788 }
1789 
1790 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1791   // A declaration named in an unevaluated operand never constitutes an odr-use.
1792   if (isUnevaluatedContext())
1793     return NOUR_Unevaluated;
1794 
1795   // C++2a [basic.def.odr]p4:
1796   //   A variable x whose name appears as a potentially-evaluated expression e
1797   //   is odr-used by e unless [...] x is a reference that is usable in
1798   //   constant expressions.
1799   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1800     if (VD->getType()->isReferenceType() &&
1801         !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
1802         VD->isUsableInConstantExpressions(Context))
1803       return NOUR_Constant;
1804   }
1805 
1806   // All remaining non-variable cases constitute an odr-use. For variables, we
1807   // need to wait and see how the expression is used.
1808   return NOUR_None;
1809 }
1810 
1811 /// BuildDeclRefExpr - Build an expression that references a
1812 /// declaration that does not require a closure capture.
1813 DeclRefExpr *
1814 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1815                        const DeclarationNameInfo &NameInfo,
1816                        NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
1817                        SourceLocation TemplateKWLoc,
1818                        const TemplateArgumentListInfo *TemplateArgs) {
1819   bool RefersToCapturedVariable =
1820       isa<VarDecl>(D) &&
1821       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1822 
1823   DeclRefExpr *E = DeclRefExpr::Create(
1824       Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
1825       VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
1826   MarkDeclRefReferenced(E);
1827 
1828   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1829       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1830       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1831     getCurFunction()->recordUseOfWeak(E);
1832 
1833   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1834   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1835     FD = IFD->getAnonField();
1836   if (FD) {
1837     UnusedPrivateFields.remove(FD);
1838     // Just in case we're building an illegal pointer-to-member.
1839     if (FD->isBitField())
1840       E->setObjectKind(OK_BitField);
1841   }
1842 
1843   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1844   // designates a bit-field.
1845   if (auto *BD = dyn_cast<BindingDecl>(D))
1846     if (auto *BE = BD->getBinding())
1847       E->setObjectKind(BE->getObjectKind());
1848 
1849   return E;
1850 }
1851 
1852 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1853 /// possibly a list of template arguments.
1854 ///
1855 /// If this produces template arguments, it is permitted to call
1856 /// DecomposeTemplateName.
1857 ///
1858 /// This actually loses a lot of source location information for
1859 /// non-standard name kinds; we should consider preserving that in
1860 /// some way.
1861 void
1862 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1863                              TemplateArgumentListInfo &Buffer,
1864                              DeclarationNameInfo &NameInfo,
1865                              const TemplateArgumentListInfo *&TemplateArgs) {
1866   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
1867     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1868     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1869 
1870     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1871                                        Id.TemplateId->NumArgs);
1872     translateTemplateArguments(TemplateArgsPtr, Buffer);
1873 
1874     TemplateName TName = Id.TemplateId->Template.get();
1875     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1876     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1877     TemplateArgs = &Buffer;
1878   } else {
1879     NameInfo = GetNameFromUnqualifiedId(Id);
1880     TemplateArgs = nullptr;
1881   }
1882 }
1883 
1884 static void emitEmptyLookupTypoDiagnostic(
1885     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1886     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1887     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1888   DeclContext *Ctx =
1889       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1890   if (!TC) {
1891     // Emit a special diagnostic for failed member lookups.
1892     // FIXME: computing the declaration context might fail here (?)
1893     if (Ctx)
1894       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1895                                                  << SS.getRange();
1896     else
1897       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1898     return;
1899   }
1900 
1901   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1902   bool DroppedSpecifier =
1903       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1904   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1905                         ? diag::note_implicit_param_decl
1906                         : diag::note_previous_decl;
1907   if (!Ctx)
1908     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1909                          SemaRef.PDiag(NoteID));
1910   else
1911     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1912                                  << Typo << Ctx << DroppedSpecifier
1913                                  << SS.getRange(),
1914                          SemaRef.PDiag(NoteID));
1915 }
1916 
1917 /// Diagnose an empty lookup.
1918 ///
1919 /// \return false if new lookup candidates were found
1920 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1921                                CorrectionCandidateCallback &CCC,
1922                                TemplateArgumentListInfo *ExplicitTemplateArgs,
1923                                ArrayRef<Expr *> Args, TypoExpr **Out) {
1924   DeclarationName Name = R.getLookupName();
1925 
1926   unsigned diagnostic = diag::err_undeclared_var_use;
1927   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1928   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1929       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1930       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1931     diagnostic = diag::err_undeclared_use;
1932     diagnostic_suggest = diag::err_undeclared_use_suggest;
1933   }
1934 
1935   // If the original lookup was an unqualified lookup, fake an
1936   // unqualified lookup.  This is useful when (for example) the
1937   // original lookup would not have found something because it was a
1938   // dependent name.
1939   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1940   while (DC) {
1941     if (isa<CXXRecordDecl>(DC)) {
1942       LookupQualifiedName(R, DC);
1943 
1944       if (!R.empty()) {
1945         // Don't give errors about ambiguities in this lookup.
1946         R.suppressDiagnostics();
1947 
1948         // During a default argument instantiation the CurContext points
1949         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1950         // function parameter list, hence add an explicit check.
1951         bool isDefaultArgument =
1952             !CodeSynthesisContexts.empty() &&
1953             CodeSynthesisContexts.back().Kind ==
1954                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
1955         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1956         bool isInstance = CurMethod &&
1957                           CurMethod->isInstance() &&
1958                           DC == CurMethod->getParent() && !isDefaultArgument;
1959 
1960         // Give a code modification hint to insert 'this->'.
1961         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1962         // Actually quite difficult!
1963         if (getLangOpts().MSVCCompat)
1964           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1965         if (isInstance) {
1966           Diag(R.getNameLoc(), diagnostic) << Name
1967             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1968           CheckCXXThisCapture(R.getNameLoc());
1969         } else {
1970           Diag(R.getNameLoc(), diagnostic) << Name;
1971         }
1972 
1973         // Do we really want to note all of these?
1974         for (NamedDecl *D : R)
1975           Diag(D->getLocation(), diag::note_dependent_var_use);
1976 
1977         // Return true if we are inside a default argument instantiation
1978         // and the found name refers to an instance member function, otherwise
1979         // the function calling DiagnoseEmptyLookup will try to create an
1980         // implicit member call and this is wrong for default argument.
1981         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1982           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1983           return true;
1984         }
1985 
1986         // Tell the callee to try to recover.
1987         return false;
1988       }
1989 
1990       R.clear();
1991     }
1992 
1993     // In Microsoft mode, if we are performing lookup from within a friend
1994     // function definition declared at class scope then we must set
1995     // DC to the lexical parent to be able to search into the parent
1996     // class.
1997     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1998         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1999         DC->getLexicalParent()->isRecord())
2000       DC = DC->getLexicalParent();
2001     else
2002       DC = DC->getParent();
2003   }
2004 
2005   // We didn't find anything, so try to correct for a typo.
2006   TypoCorrection Corrected;
2007   if (S && Out) {
2008     SourceLocation TypoLoc = R.getNameLoc();
2009     assert(!ExplicitTemplateArgs &&
2010            "Diagnosing an empty lookup with explicit template args!");
2011     *Out = CorrectTypoDelayed(
2012         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2013         [=](const TypoCorrection &TC) {
2014           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2015                                         diagnostic, diagnostic_suggest);
2016         },
2017         nullptr, CTK_ErrorRecovery);
2018     if (*Out)
2019       return true;
2020   } else if (S &&
2021              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2022                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2023     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2024     bool DroppedSpecifier =
2025         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2026     R.setLookupName(Corrected.getCorrection());
2027 
2028     bool AcceptableWithRecovery = false;
2029     bool AcceptableWithoutRecovery = false;
2030     NamedDecl *ND = Corrected.getFoundDecl();
2031     if (ND) {
2032       if (Corrected.isOverloaded()) {
2033         OverloadCandidateSet OCS(R.getNameLoc(),
2034                                  OverloadCandidateSet::CSK_Normal);
2035         OverloadCandidateSet::iterator Best;
2036         for (NamedDecl *CD : Corrected) {
2037           if (FunctionTemplateDecl *FTD =
2038                    dyn_cast<FunctionTemplateDecl>(CD))
2039             AddTemplateOverloadCandidate(
2040                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2041                 Args, OCS);
2042           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2043             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2044               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2045                                    Args, OCS);
2046         }
2047         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2048         case OR_Success:
2049           ND = Best->FoundDecl;
2050           Corrected.setCorrectionDecl(ND);
2051           break;
2052         default:
2053           // FIXME: Arbitrarily pick the first declaration for the note.
2054           Corrected.setCorrectionDecl(ND);
2055           break;
2056         }
2057       }
2058       R.addDecl(ND);
2059       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2060         CXXRecordDecl *Record = nullptr;
2061         if (Corrected.getCorrectionSpecifier()) {
2062           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2063           Record = Ty->getAsCXXRecordDecl();
2064         }
2065         if (!Record)
2066           Record = cast<CXXRecordDecl>(
2067               ND->getDeclContext()->getRedeclContext());
2068         R.setNamingClass(Record);
2069       }
2070 
2071       auto *UnderlyingND = ND->getUnderlyingDecl();
2072       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2073                                isa<FunctionTemplateDecl>(UnderlyingND);
2074       // FIXME: If we ended up with a typo for a type name or
2075       // Objective-C class name, we're in trouble because the parser
2076       // is in the wrong place to recover. Suggest the typo
2077       // correction, but don't make it a fix-it since we're not going
2078       // to recover well anyway.
2079       AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2080                                   getAsTypeTemplateDecl(UnderlyingND) ||
2081                                   isa<ObjCInterfaceDecl>(UnderlyingND);
2082     } else {
2083       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2084       // because we aren't able to recover.
2085       AcceptableWithoutRecovery = true;
2086     }
2087 
2088     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2089       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2090                             ? diag::note_implicit_param_decl
2091                             : diag::note_previous_decl;
2092       if (SS.isEmpty())
2093         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2094                      PDiag(NoteID), AcceptableWithRecovery);
2095       else
2096         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2097                                   << Name << computeDeclContext(SS, false)
2098                                   << DroppedSpecifier << SS.getRange(),
2099                      PDiag(NoteID), AcceptableWithRecovery);
2100 
2101       // Tell the callee whether to try to recover.
2102       return !AcceptableWithRecovery;
2103     }
2104   }
2105   R.clear();
2106 
2107   // Emit a special diagnostic for failed member lookups.
2108   // FIXME: computing the declaration context might fail here (?)
2109   if (!SS.isEmpty()) {
2110     Diag(R.getNameLoc(), diag::err_no_member)
2111       << Name << computeDeclContext(SS, false)
2112       << SS.getRange();
2113     return true;
2114   }
2115 
2116   // Give up, we can't recover.
2117   Diag(R.getNameLoc(), diagnostic) << Name;
2118   return true;
2119 }
2120 
2121 /// In Microsoft mode, if we are inside a template class whose parent class has
2122 /// dependent base classes, and we can't resolve an unqualified identifier, then
2123 /// assume the identifier is a member of a dependent base class.  We can only
2124 /// recover successfully in static methods, instance methods, and other contexts
2125 /// where 'this' is available.  This doesn't precisely match MSVC's
2126 /// instantiation model, but it's close enough.
2127 static Expr *
2128 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2129                                DeclarationNameInfo &NameInfo,
2130                                SourceLocation TemplateKWLoc,
2131                                const TemplateArgumentListInfo *TemplateArgs) {
2132   // Only try to recover from lookup into dependent bases in static methods or
2133   // contexts where 'this' is available.
2134   QualType ThisType = S.getCurrentThisType();
2135   const CXXRecordDecl *RD = nullptr;
2136   if (!ThisType.isNull())
2137     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2138   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2139     RD = MD->getParent();
2140   if (!RD || !RD->hasAnyDependentBases())
2141     return nullptr;
2142 
2143   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2144   // is available, suggest inserting 'this->' as a fixit.
2145   SourceLocation Loc = NameInfo.getLoc();
2146   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2147   DB << NameInfo.getName() << RD;
2148 
2149   if (!ThisType.isNull()) {
2150     DB << FixItHint::CreateInsertion(Loc, "this->");
2151     return CXXDependentScopeMemberExpr::Create(
2152         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2153         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2154         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2155   }
2156 
2157   // Synthesize a fake NNS that points to the derived class.  This will
2158   // perform name lookup during template instantiation.
2159   CXXScopeSpec SS;
2160   auto *NNS =
2161       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2162   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2163   return DependentScopeDeclRefExpr::Create(
2164       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2165       TemplateArgs);
2166 }
2167 
2168 ExprResult
2169 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2170                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2171                         bool HasTrailingLParen, bool IsAddressOfOperand,
2172                         CorrectionCandidateCallback *CCC,
2173                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2174   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2175          "cannot be direct & operand and have a trailing lparen");
2176   if (SS.isInvalid())
2177     return ExprError();
2178 
2179   TemplateArgumentListInfo TemplateArgsBuffer;
2180 
2181   // Decompose the UnqualifiedId into the following data.
2182   DeclarationNameInfo NameInfo;
2183   const TemplateArgumentListInfo *TemplateArgs;
2184   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2185 
2186   DeclarationName Name = NameInfo.getName();
2187   IdentifierInfo *II = Name.getAsIdentifierInfo();
2188   SourceLocation NameLoc = NameInfo.getLoc();
2189 
2190   if (II && II->isEditorPlaceholder()) {
2191     // FIXME: When typed placeholders are supported we can create a typed
2192     // placeholder expression node.
2193     return ExprError();
2194   }
2195 
2196   // C++ [temp.dep.expr]p3:
2197   //   An id-expression is type-dependent if it contains:
2198   //     -- an identifier that was declared with a dependent type,
2199   //        (note: handled after lookup)
2200   //     -- a template-id that is dependent,
2201   //        (note: handled in BuildTemplateIdExpr)
2202   //     -- a conversion-function-id that specifies a dependent type,
2203   //     -- a nested-name-specifier that contains a class-name that
2204   //        names a dependent type.
2205   // Determine whether this is a member of an unknown specialization;
2206   // we need to handle these differently.
2207   bool DependentID = false;
2208   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2209       Name.getCXXNameType()->isDependentType()) {
2210     DependentID = true;
2211   } else if (SS.isSet()) {
2212     if (DeclContext *DC = computeDeclContext(SS, false)) {
2213       if (RequireCompleteDeclContext(SS, DC))
2214         return ExprError();
2215     } else {
2216       DependentID = true;
2217     }
2218   }
2219 
2220   if (DependentID)
2221     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2222                                       IsAddressOfOperand, TemplateArgs);
2223 
2224   // Perform the required lookup.
2225   LookupResult R(*this, NameInfo,
2226                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2227                      ? LookupObjCImplicitSelfParam
2228                      : LookupOrdinaryName);
2229   if (TemplateKWLoc.isValid() || TemplateArgs) {
2230     // Lookup the template name again to correctly establish the context in
2231     // which it was found. This is really unfortunate as we already did the
2232     // lookup to determine that it was a template name in the first place. If
2233     // this becomes a performance hit, we can work harder to preserve those
2234     // results until we get here but it's likely not worth it.
2235     bool MemberOfUnknownSpecialization;
2236     AssumedTemplateKind AssumedTemplate;
2237     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2238                            MemberOfUnknownSpecialization, TemplateKWLoc,
2239                            &AssumedTemplate))
2240       return ExprError();
2241 
2242     if (MemberOfUnknownSpecialization ||
2243         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2244       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2245                                         IsAddressOfOperand, TemplateArgs);
2246   } else {
2247     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2248     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2249 
2250     // If the result might be in a dependent base class, this is a dependent
2251     // id-expression.
2252     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2253       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2254                                         IsAddressOfOperand, TemplateArgs);
2255 
2256     // If this reference is in an Objective-C method, then we need to do
2257     // some special Objective-C lookup, too.
2258     if (IvarLookupFollowUp) {
2259       ExprResult E(LookupInObjCMethod(R, S, II, true));
2260       if (E.isInvalid())
2261         return ExprError();
2262 
2263       if (Expr *Ex = E.getAs<Expr>())
2264         return Ex;
2265     }
2266   }
2267 
2268   if (R.isAmbiguous())
2269     return ExprError();
2270 
2271   // This could be an implicitly declared function reference (legal in C90,
2272   // extension in C99, forbidden in C++).
2273   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2274     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2275     if (D) R.addDecl(D);
2276   }
2277 
2278   // Determine whether this name might be a candidate for
2279   // argument-dependent lookup.
2280   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2281 
2282   if (R.empty() && !ADL) {
2283     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2284       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2285                                                    TemplateKWLoc, TemplateArgs))
2286         return E;
2287     }
2288 
2289     // Don't diagnose an empty lookup for inline assembly.
2290     if (IsInlineAsmIdentifier)
2291       return ExprError();
2292 
2293     // If this name wasn't predeclared and if this is not a function
2294     // call, diagnose the problem.
2295     TypoExpr *TE = nullptr;
2296     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2297                                                        : nullptr);
2298     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2299     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2300            "Typo correction callback misconfigured");
2301     if (CCC) {
2302       // Make sure the callback knows what the typo being diagnosed is.
2303       CCC->setTypoName(II);
2304       if (SS.isValid())
2305         CCC->setTypoNNS(SS.getScopeRep());
2306     }
2307     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2308     // a template name, but we happen to have always already looked up the name
2309     // before we get here if it must be a template name.
2310     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2311                             None, &TE)) {
2312       if (TE && KeywordReplacement) {
2313         auto &State = getTypoExprState(TE);
2314         auto BestTC = State.Consumer->getNextCorrection();
2315         if (BestTC.isKeyword()) {
2316           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2317           if (State.DiagHandler)
2318             State.DiagHandler(BestTC);
2319           KeywordReplacement->startToken();
2320           KeywordReplacement->setKind(II->getTokenID());
2321           KeywordReplacement->setIdentifierInfo(II);
2322           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2323           // Clean up the state associated with the TypoExpr, since it has
2324           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2325           clearDelayedTypo(TE);
2326           // Signal that a correction to a keyword was performed by returning a
2327           // valid-but-null ExprResult.
2328           return (Expr*)nullptr;
2329         }
2330         State.Consumer->resetCorrectionStream();
2331       }
2332       return TE ? TE : ExprError();
2333     }
2334 
2335     assert(!R.empty() &&
2336            "DiagnoseEmptyLookup returned false but added no results");
2337 
2338     // If we found an Objective-C instance variable, let
2339     // LookupInObjCMethod build the appropriate expression to
2340     // reference the ivar.
2341     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2342       R.clear();
2343       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2344       // In a hopelessly buggy code, Objective-C instance variable
2345       // lookup fails and no expression will be built to reference it.
2346       if (!E.isInvalid() && !E.get())
2347         return ExprError();
2348       return E;
2349     }
2350   }
2351 
2352   // This is guaranteed from this point on.
2353   assert(!R.empty() || ADL);
2354 
2355   // Check whether this might be a C++ implicit instance member access.
2356   // C++ [class.mfct.non-static]p3:
2357   //   When an id-expression that is not part of a class member access
2358   //   syntax and not used to form a pointer to member is used in the
2359   //   body of a non-static member function of class X, if name lookup
2360   //   resolves the name in the id-expression to a non-static non-type
2361   //   member of some class C, the id-expression is transformed into a
2362   //   class member access expression using (*this) as the
2363   //   postfix-expression to the left of the . operator.
2364   //
2365   // But we don't actually need to do this for '&' operands if R
2366   // resolved to a function or overloaded function set, because the
2367   // expression is ill-formed if it actually works out to be a
2368   // non-static member function:
2369   //
2370   // C++ [expr.ref]p4:
2371   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2372   //   [t]he expression can be used only as the left-hand operand of a
2373   //   member function call.
2374   //
2375   // There are other safeguards against such uses, but it's important
2376   // to get this right here so that we don't end up making a
2377   // spuriously dependent expression if we're inside a dependent
2378   // instance method.
2379   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2380     bool MightBeImplicitMember;
2381     if (!IsAddressOfOperand)
2382       MightBeImplicitMember = true;
2383     else if (!SS.isEmpty())
2384       MightBeImplicitMember = false;
2385     else if (R.isOverloadedResult())
2386       MightBeImplicitMember = false;
2387     else if (R.isUnresolvableResult())
2388       MightBeImplicitMember = true;
2389     else
2390       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2391                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2392                               isa<MSPropertyDecl>(R.getFoundDecl());
2393 
2394     if (MightBeImplicitMember)
2395       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2396                                              R, TemplateArgs, S);
2397   }
2398 
2399   if (TemplateArgs || TemplateKWLoc.isValid()) {
2400 
2401     // In C++1y, if this is a variable template id, then check it
2402     // in BuildTemplateIdExpr().
2403     // The single lookup result must be a variable template declaration.
2404     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2405         Id.TemplateId->Kind == TNK_Var_template) {
2406       assert(R.getAsSingle<VarTemplateDecl>() &&
2407              "There should only be one declaration found.");
2408     }
2409 
2410     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2411   }
2412 
2413   return BuildDeclarationNameExpr(SS, R, ADL);
2414 }
2415 
2416 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2417 /// declaration name, generally during template instantiation.
2418 /// There's a large number of things which don't need to be done along
2419 /// this path.
2420 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2421     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2422     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2423   DeclContext *DC = computeDeclContext(SS, false);
2424   if (!DC)
2425     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2426                                      NameInfo, /*TemplateArgs=*/nullptr);
2427 
2428   if (RequireCompleteDeclContext(SS, DC))
2429     return ExprError();
2430 
2431   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2432   LookupQualifiedName(R, DC);
2433 
2434   if (R.isAmbiguous())
2435     return ExprError();
2436 
2437   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2438     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2439                                      NameInfo, /*TemplateArgs=*/nullptr);
2440 
2441   if (R.empty()) {
2442     Diag(NameInfo.getLoc(), diag::err_no_member)
2443       << NameInfo.getName() << DC << SS.getRange();
2444     return ExprError();
2445   }
2446 
2447   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2448     // Diagnose a missing typename if this resolved unambiguously to a type in
2449     // a dependent context.  If we can recover with a type, downgrade this to
2450     // a warning in Microsoft compatibility mode.
2451     unsigned DiagID = diag::err_typename_missing;
2452     if (RecoveryTSI && getLangOpts().MSVCCompat)
2453       DiagID = diag::ext_typename_missing;
2454     SourceLocation Loc = SS.getBeginLoc();
2455     auto D = Diag(Loc, DiagID);
2456     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2457       << SourceRange(Loc, NameInfo.getEndLoc());
2458 
2459     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2460     // context.
2461     if (!RecoveryTSI)
2462       return ExprError();
2463 
2464     // Only issue the fixit if we're prepared to recover.
2465     D << FixItHint::CreateInsertion(Loc, "typename ");
2466 
2467     // Recover by pretending this was an elaborated type.
2468     QualType Ty = Context.getTypeDeclType(TD);
2469     TypeLocBuilder TLB;
2470     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2471 
2472     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2473     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2474     QTL.setElaboratedKeywordLoc(SourceLocation());
2475     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2476 
2477     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2478 
2479     return ExprEmpty();
2480   }
2481 
2482   // Defend against this resolving to an implicit member access. We usually
2483   // won't get here if this might be a legitimate a class member (we end up in
2484   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2485   // a pointer-to-member or in an unevaluated context in C++11.
2486   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2487     return BuildPossibleImplicitMemberExpr(SS,
2488                                            /*TemplateKWLoc=*/SourceLocation(),
2489                                            R, /*TemplateArgs=*/nullptr, S);
2490 
2491   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2492 }
2493 
2494 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2495 /// detected that we're currently inside an ObjC method.  Perform some
2496 /// additional lookup.
2497 ///
2498 /// Ideally, most of this would be done by lookup, but there's
2499 /// actually quite a lot of extra work involved.
2500 ///
2501 /// Returns a null sentinel to indicate trivial success.
2502 ExprResult
2503 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2504                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2505   SourceLocation Loc = Lookup.getNameLoc();
2506   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2507 
2508   // Check for error condition which is already reported.
2509   if (!CurMethod)
2510     return ExprError();
2511 
2512   // There are two cases to handle here.  1) scoped lookup could have failed,
2513   // in which case we should look for an ivar.  2) scoped lookup could have
2514   // found a decl, but that decl is outside the current instance method (i.e.
2515   // a global variable).  In these two cases, we do a lookup for an ivar with
2516   // this name, if the lookup sucedes, we replace it our current decl.
2517 
2518   // If we're in a class method, we don't normally want to look for
2519   // ivars.  But if we don't find anything else, and there's an
2520   // ivar, that's an error.
2521   bool IsClassMethod = CurMethod->isClassMethod();
2522 
2523   bool LookForIvars;
2524   if (Lookup.empty())
2525     LookForIvars = true;
2526   else if (IsClassMethod)
2527     LookForIvars = false;
2528   else
2529     LookForIvars = (Lookup.isSingleResult() &&
2530                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2531   ObjCInterfaceDecl *IFace = nullptr;
2532   if (LookForIvars) {
2533     IFace = CurMethod->getClassInterface();
2534     ObjCInterfaceDecl *ClassDeclared;
2535     ObjCIvarDecl *IV = nullptr;
2536     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2537       // Diagnose using an ivar in a class method.
2538       if (IsClassMethod)
2539         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2540                          << IV->getDeclName());
2541 
2542       // If we're referencing an invalid decl, just return this as a silent
2543       // error node.  The error diagnostic was already emitted on the decl.
2544       if (IV->isInvalidDecl())
2545         return ExprError();
2546 
2547       // Check if referencing a field with __attribute__((deprecated)).
2548       if (DiagnoseUseOfDecl(IV, Loc))
2549         return ExprError();
2550 
2551       // Diagnose the use of an ivar outside of the declaring class.
2552       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2553           !declaresSameEntity(ClassDeclared, IFace) &&
2554           !getLangOpts().DebuggerSupport)
2555         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2556 
2557       // FIXME: This should use a new expr for a direct reference, don't
2558       // turn this into Self->ivar, just return a BareIVarExpr or something.
2559       IdentifierInfo &II = Context.Idents.get("self");
2560       UnqualifiedId SelfName;
2561       SelfName.setIdentifier(&II, SourceLocation());
2562       SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2563       CXXScopeSpec SelfScopeSpec;
2564       SourceLocation TemplateKWLoc;
2565       ExprResult SelfExpr =
2566           ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2567                             /*HasTrailingLParen=*/false,
2568                             /*IsAddressOfOperand=*/false);
2569       if (SelfExpr.isInvalid())
2570         return ExprError();
2571 
2572       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2573       if (SelfExpr.isInvalid())
2574         return ExprError();
2575 
2576       MarkAnyDeclReferenced(Loc, IV, true);
2577 
2578       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2579       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2580           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2581         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2582 
2583       ObjCIvarRefExpr *Result = new (Context)
2584           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2585                           IV->getLocation(), SelfExpr.get(), true, true);
2586 
2587       if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2588         if (!isUnevaluatedContext() &&
2589             !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2590           getCurFunction()->recordUseOfWeak(Result);
2591       }
2592       if (getLangOpts().ObjCAutoRefCount)
2593         if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2594           ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2595 
2596       return Result;
2597     }
2598   } else if (CurMethod->isInstanceMethod()) {
2599     // We should warn if a local variable hides an ivar.
2600     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2601       ObjCInterfaceDecl *ClassDeclared;
2602       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2603         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2604             declaresSameEntity(IFace, ClassDeclared))
2605           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2606       }
2607     }
2608   } else if (Lookup.isSingleResult() &&
2609              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2610     // If accessing a stand-alone ivar in a class method, this is an error.
2611     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2612       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2613                        << IV->getDeclName());
2614   }
2615 
2616   if (Lookup.empty() && II && AllowBuiltinCreation) {
2617     // FIXME. Consolidate this with similar code in LookupName.
2618     if (unsigned BuiltinID = II->getBuiltinID()) {
2619       if (!(getLangOpts().CPlusPlus &&
2620             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2621         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2622                                            S, Lookup.isForRedeclaration(),
2623                                            Lookup.getNameLoc());
2624         if (D) Lookup.addDecl(D);
2625       }
2626     }
2627   }
2628   // Sentinel value saying that we didn't do anything special.
2629   return ExprResult((Expr *)nullptr);
2630 }
2631 
2632 /// Cast a base object to a member's actual type.
2633 ///
2634 /// Logically this happens in three phases:
2635 ///
2636 /// * First we cast from the base type to the naming class.
2637 ///   The naming class is the class into which we were looking
2638 ///   when we found the member;  it's the qualifier type if a
2639 ///   qualifier was provided, and otherwise it's the base type.
2640 ///
2641 /// * Next we cast from the naming class to the declaring class.
2642 ///   If the member we found was brought into a class's scope by
2643 ///   a using declaration, this is that class;  otherwise it's
2644 ///   the class declaring the member.
2645 ///
2646 /// * Finally we cast from the declaring class to the "true"
2647 ///   declaring class of the member.  This conversion does not
2648 ///   obey access control.
2649 ExprResult
2650 Sema::PerformObjectMemberConversion(Expr *From,
2651                                     NestedNameSpecifier *Qualifier,
2652                                     NamedDecl *FoundDecl,
2653                                     NamedDecl *Member) {
2654   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2655   if (!RD)
2656     return From;
2657 
2658   QualType DestRecordType;
2659   QualType DestType;
2660   QualType FromRecordType;
2661   QualType FromType = From->getType();
2662   bool PointerConversions = false;
2663   if (isa<FieldDecl>(Member)) {
2664     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2665     auto FromPtrType = FromType->getAs<PointerType>();
2666     DestRecordType = Context.getAddrSpaceQualType(
2667         DestRecordType, FromPtrType
2668                             ? FromType->getPointeeType().getAddressSpace()
2669                             : FromType.getAddressSpace());
2670 
2671     if (FromPtrType) {
2672       DestType = Context.getPointerType(DestRecordType);
2673       FromRecordType = FromPtrType->getPointeeType();
2674       PointerConversions = true;
2675     } else {
2676       DestType = DestRecordType;
2677       FromRecordType = FromType;
2678     }
2679   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2680     if (Method->isStatic())
2681       return From;
2682 
2683     DestType = Method->getThisType();
2684     DestRecordType = DestType->getPointeeType();
2685 
2686     if (FromType->getAs<PointerType>()) {
2687       FromRecordType = FromType->getPointeeType();
2688       PointerConversions = true;
2689     } else {
2690       FromRecordType = FromType;
2691       DestType = DestRecordType;
2692     }
2693   } else {
2694     // No conversion necessary.
2695     return From;
2696   }
2697 
2698   if (DestType->isDependentType() || FromType->isDependentType())
2699     return From;
2700 
2701   // If the unqualified types are the same, no conversion is necessary.
2702   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2703     return From;
2704 
2705   SourceRange FromRange = From->getSourceRange();
2706   SourceLocation FromLoc = FromRange.getBegin();
2707 
2708   ExprValueKind VK = From->getValueKind();
2709 
2710   // C++ [class.member.lookup]p8:
2711   //   [...] Ambiguities can often be resolved by qualifying a name with its
2712   //   class name.
2713   //
2714   // If the member was a qualified name and the qualified referred to a
2715   // specific base subobject type, we'll cast to that intermediate type
2716   // first and then to the object in which the member is declared. That allows
2717   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2718   //
2719   //   class Base { public: int x; };
2720   //   class Derived1 : public Base { };
2721   //   class Derived2 : public Base { };
2722   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2723   //
2724   //   void VeryDerived::f() {
2725   //     x = 17; // error: ambiguous base subobjects
2726   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2727   //   }
2728   if (Qualifier && Qualifier->getAsType()) {
2729     QualType QType = QualType(Qualifier->getAsType(), 0);
2730     assert(QType->isRecordType() && "lookup done with non-record type");
2731 
2732     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2733 
2734     // In C++98, the qualifier type doesn't actually have to be a base
2735     // type of the object type, in which case we just ignore it.
2736     // Otherwise build the appropriate casts.
2737     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2738       CXXCastPath BasePath;
2739       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2740                                        FromLoc, FromRange, &BasePath))
2741         return ExprError();
2742 
2743       if (PointerConversions)
2744         QType = Context.getPointerType(QType);
2745       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2746                                VK, &BasePath).get();
2747 
2748       FromType = QType;
2749       FromRecordType = QRecordType;
2750 
2751       // If the qualifier type was the same as the destination type,
2752       // we're done.
2753       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2754         return From;
2755     }
2756   }
2757 
2758   bool IgnoreAccess = false;
2759 
2760   // If we actually found the member through a using declaration, cast
2761   // down to the using declaration's type.
2762   //
2763   // Pointer equality is fine here because only one declaration of a
2764   // class ever has member declarations.
2765   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2766     assert(isa<UsingShadowDecl>(FoundDecl));
2767     QualType URecordType = Context.getTypeDeclType(
2768                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2769 
2770     // We only need to do this if the naming-class to declaring-class
2771     // conversion is non-trivial.
2772     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2773       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2774       CXXCastPath BasePath;
2775       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2776                                        FromLoc, FromRange, &BasePath))
2777         return ExprError();
2778 
2779       QualType UType = URecordType;
2780       if (PointerConversions)
2781         UType = Context.getPointerType(UType);
2782       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2783                                VK, &BasePath).get();
2784       FromType = UType;
2785       FromRecordType = URecordType;
2786     }
2787 
2788     // We don't do access control for the conversion from the
2789     // declaring class to the true declaring class.
2790     IgnoreAccess = true;
2791   }
2792 
2793   CXXCastPath BasePath;
2794   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2795                                    FromLoc, FromRange, &BasePath,
2796                                    IgnoreAccess))
2797     return ExprError();
2798 
2799   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2800                            VK, &BasePath);
2801 }
2802 
2803 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2804                                       const LookupResult &R,
2805                                       bool HasTrailingLParen) {
2806   // Only when used directly as the postfix-expression of a call.
2807   if (!HasTrailingLParen)
2808     return false;
2809 
2810   // Never if a scope specifier was provided.
2811   if (SS.isSet())
2812     return false;
2813 
2814   // Only in C++ or ObjC++.
2815   if (!getLangOpts().CPlusPlus)
2816     return false;
2817 
2818   // Turn off ADL when we find certain kinds of declarations during
2819   // normal lookup:
2820   for (NamedDecl *D : R) {
2821     // C++0x [basic.lookup.argdep]p3:
2822     //     -- a declaration of a class member
2823     // Since using decls preserve this property, we check this on the
2824     // original decl.
2825     if (D->isCXXClassMember())
2826       return false;
2827 
2828     // C++0x [basic.lookup.argdep]p3:
2829     //     -- a block-scope function declaration that is not a
2830     //        using-declaration
2831     // NOTE: we also trigger this for function templates (in fact, we
2832     // don't check the decl type at all, since all other decl types
2833     // turn off ADL anyway).
2834     if (isa<UsingShadowDecl>(D))
2835       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2836     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2837       return false;
2838 
2839     // C++0x [basic.lookup.argdep]p3:
2840     //     -- a declaration that is neither a function or a function
2841     //        template
2842     // And also for builtin functions.
2843     if (isa<FunctionDecl>(D)) {
2844       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2845 
2846       // But also builtin functions.
2847       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2848         return false;
2849     } else if (!isa<FunctionTemplateDecl>(D))
2850       return false;
2851   }
2852 
2853   return true;
2854 }
2855 
2856 
2857 /// Diagnoses obvious problems with the use of the given declaration
2858 /// as an expression.  This is only actually called for lookups that
2859 /// were not overloaded, and it doesn't promise that the declaration
2860 /// will in fact be used.
2861 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2862   if (D->isInvalidDecl())
2863     return true;
2864 
2865   if (isa<TypedefNameDecl>(D)) {
2866     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2867     return true;
2868   }
2869 
2870   if (isa<ObjCInterfaceDecl>(D)) {
2871     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2872     return true;
2873   }
2874 
2875   if (isa<NamespaceDecl>(D)) {
2876     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2877     return true;
2878   }
2879 
2880   return false;
2881 }
2882 
2883 // Certain multiversion types should be treated as overloaded even when there is
2884 // only one result.
2885 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
2886   assert(R.isSingleResult() && "Expected only a single result");
2887   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
2888   return FD &&
2889          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
2890 }
2891 
2892 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2893                                           LookupResult &R, bool NeedsADL,
2894                                           bool AcceptInvalidDecl) {
2895   // If this is a single, fully-resolved result and we don't need ADL,
2896   // just build an ordinary singleton decl ref.
2897   if (!NeedsADL && R.isSingleResult() &&
2898       !R.getAsSingle<FunctionTemplateDecl>() &&
2899       !ShouldLookupResultBeMultiVersionOverload(R))
2900     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2901                                     R.getRepresentativeDecl(), nullptr,
2902                                     AcceptInvalidDecl);
2903 
2904   // We only need to check the declaration if there's exactly one
2905   // result, because in the overloaded case the results can only be
2906   // functions and function templates.
2907   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
2908       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2909     return ExprError();
2910 
2911   // Otherwise, just build an unresolved lookup expression.  Suppress
2912   // any lookup-related diagnostics; we'll hash these out later, when
2913   // we've picked a target.
2914   R.suppressDiagnostics();
2915 
2916   UnresolvedLookupExpr *ULE
2917     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2918                                    SS.getWithLocInContext(Context),
2919                                    R.getLookupNameInfo(),
2920                                    NeedsADL, R.isOverloadedResult(),
2921                                    R.begin(), R.end());
2922 
2923   return ULE;
2924 }
2925 
2926 static void
2927 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2928                                    ValueDecl *var, DeclContext *DC);
2929 
2930 /// Complete semantic analysis for a reference to the given declaration.
2931 ExprResult Sema::BuildDeclarationNameExpr(
2932     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2933     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2934     bool AcceptInvalidDecl) {
2935   assert(D && "Cannot refer to a NULL declaration");
2936   assert(!isa<FunctionTemplateDecl>(D) &&
2937          "Cannot refer unambiguously to a function template");
2938 
2939   SourceLocation Loc = NameInfo.getLoc();
2940   if (CheckDeclInExpr(*this, Loc, D))
2941     return ExprError();
2942 
2943   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2944     // Specifically diagnose references to class templates that are missing
2945     // a template argument list.
2946     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
2947     return ExprError();
2948   }
2949 
2950   // Make sure that we're referring to a value.
2951   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2952   if (!VD) {
2953     Diag(Loc, diag::err_ref_non_value)
2954       << D << SS.getRange();
2955     Diag(D->getLocation(), diag::note_declared_at);
2956     return ExprError();
2957   }
2958 
2959   // Check whether this declaration can be used. Note that we suppress
2960   // this check when we're going to perform argument-dependent lookup
2961   // on this function name, because this might not be the function
2962   // that overload resolution actually selects.
2963   if (DiagnoseUseOfDecl(VD, Loc))
2964     return ExprError();
2965 
2966   // Only create DeclRefExpr's for valid Decl's.
2967   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2968     return ExprError();
2969 
2970   // Handle members of anonymous structs and unions.  If we got here,
2971   // and the reference is to a class member indirect field, then this
2972   // must be the subject of a pointer-to-member expression.
2973   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2974     if (!indirectField->isCXXClassMember())
2975       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2976                                                       indirectField);
2977 
2978   {
2979     QualType type = VD->getType();
2980     if (type.isNull())
2981       return ExprError();
2982     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2983       // C++ [except.spec]p17:
2984       //   An exception-specification is considered to be needed when:
2985       //   - in an expression, the function is the unique lookup result or
2986       //     the selected member of a set of overloaded functions.
2987       ResolveExceptionSpec(Loc, FPT);
2988       type = VD->getType();
2989     }
2990     ExprValueKind valueKind = VK_RValue;
2991 
2992     switch (D->getKind()) {
2993     // Ignore all the non-ValueDecl kinds.
2994 #define ABSTRACT_DECL(kind)
2995 #define VALUE(type, base)
2996 #define DECL(type, base) \
2997     case Decl::type:
2998 #include "clang/AST/DeclNodes.inc"
2999       llvm_unreachable("invalid value decl kind");
3000 
3001     // These shouldn't make it here.
3002     case Decl::ObjCAtDefsField:
3003       llvm_unreachable("forming non-member reference to ivar?");
3004 
3005     // Enum constants are always r-values and never references.
3006     // Unresolved using declarations are dependent.
3007     case Decl::EnumConstant:
3008     case Decl::UnresolvedUsingValue:
3009     case Decl::OMPDeclareReduction:
3010     case Decl::OMPDeclareMapper:
3011       valueKind = VK_RValue;
3012       break;
3013 
3014     // Fields and indirect fields that got here must be for
3015     // pointer-to-member expressions; we just call them l-values for
3016     // internal consistency, because this subexpression doesn't really
3017     // exist in the high-level semantics.
3018     case Decl::Field:
3019     case Decl::IndirectField:
3020     case Decl::ObjCIvar:
3021       assert(getLangOpts().CPlusPlus &&
3022              "building reference to field in C?");
3023 
3024       // These can't have reference type in well-formed programs, but
3025       // for internal consistency we do this anyway.
3026       type = type.getNonReferenceType();
3027       valueKind = VK_LValue;
3028       break;
3029 
3030     // Non-type template parameters are either l-values or r-values
3031     // depending on the type.
3032     case Decl::NonTypeTemplateParm: {
3033       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3034         type = reftype->getPointeeType();
3035         valueKind = VK_LValue; // even if the parameter is an r-value reference
3036         break;
3037       }
3038 
3039       // For non-references, we need to strip qualifiers just in case
3040       // the template parameter was declared as 'const int' or whatever.
3041       valueKind = VK_RValue;
3042       type = type.getUnqualifiedType();
3043       break;
3044     }
3045 
3046     case Decl::Var:
3047     case Decl::VarTemplateSpecialization:
3048     case Decl::VarTemplatePartialSpecialization:
3049     case Decl::Decomposition:
3050     case Decl::OMPCapturedExpr:
3051       // In C, "extern void blah;" is valid and is an r-value.
3052       if (!getLangOpts().CPlusPlus &&
3053           !type.hasQualifiers() &&
3054           type->isVoidType()) {
3055         valueKind = VK_RValue;
3056         break;
3057       }
3058       LLVM_FALLTHROUGH;
3059 
3060     case Decl::ImplicitParam:
3061     case Decl::ParmVar: {
3062       // These are always l-values.
3063       valueKind = VK_LValue;
3064       type = type.getNonReferenceType();
3065 
3066       // FIXME: Does the addition of const really only apply in
3067       // potentially-evaluated contexts? Since the variable isn't actually
3068       // captured in an unevaluated context, it seems that the answer is no.
3069       if (!isUnevaluatedContext()) {
3070         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3071         if (!CapturedType.isNull())
3072           type = CapturedType;
3073       }
3074 
3075       break;
3076     }
3077 
3078     case Decl::Binding: {
3079       // These are always lvalues.
3080       valueKind = VK_LValue;
3081       type = type.getNonReferenceType();
3082       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3083       // decides how that's supposed to work.
3084       auto *BD = cast<BindingDecl>(VD);
3085       if (BD->getDeclContext() != CurContext) {
3086         auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3087         if (DD && DD->hasLocalStorage())
3088           diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3089       }
3090       break;
3091     }
3092 
3093     case Decl::Function: {
3094       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3095         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3096           type = Context.BuiltinFnTy;
3097           valueKind = VK_RValue;
3098           break;
3099         }
3100       }
3101 
3102       const FunctionType *fty = type->castAs<FunctionType>();
3103 
3104       // If we're referring to a function with an __unknown_anytype
3105       // result type, make the entire expression __unknown_anytype.
3106       if (fty->getReturnType() == Context.UnknownAnyTy) {
3107         type = Context.UnknownAnyTy;
3108         valueKind = VK_RValue;
3109         break;
3110       }
3111 
3112       // Functions are l-values in C++.
3113       if (getLangOpts().CPlusPlus) {
3114         valueKind = VK_LValue;
3115         break;
3116       }
3117 
3118       // C99 DR 316 says that, if a function type comes from a
3119       // function definition (without a prototype), that type is only
3120       // used for checking compatibility. Therefore, when referencing
3121       // the function, we pretend that we don't have the full function
3122       // type.
3123       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3124           isa<FunctionProtoType>(fty))
3125         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3126                                               fty->getExtInfo());
3127 
3128       // Functions are r-values in C.
3129       valueKind = VK_RValue;
3130       break;
3131     }
3132 
3133     case Decl::CXXDeductionGuide:
3134       llvm_unreachable("building reference to deduction guide");
3135 
3136     case Decl::MSProperty:
3137       valueKind = VK_LValue;
3138       break;
3139 
3140     case Decl::CXXMethod:
3141       // If we're referring to a method with an __unknown_anytype
3142       // result type, make the entire expression __unknown_anytype.
3143       // This should only be possible with a type written directly.
3144       if (const FunctionProtoType *proto
3145             = dyn_cast<FunctionProtoType>(VD->getType()))
3146         if (proto->getReturnType() == Context.UnknownAnyTy) {
3147           type = Context.UnknownAnyTy;
3148           valueKind = VK_RValue;
3149           break;
3150         }
3151 
3152       // C++ methods are l-values if static, r-values if non-static.
3153       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3154         valueKind = VK_LValue;
3155         break;
3156       }
3157       LLVM_FALLTHROUGH;
3158 
3159     case Decl::CXXConversion:
3160     case Decl::CXXDestructor:
3161     case Decl::CXXConstructor:
3162       valueKind = VK_RValue;
3163       break;
3164     }
3165 
3166     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3167                             /*FIXME: TemplateKWLoc*/ SourceLocation(),
3168                             TemplateArgs);
3169   }
3170 }
3171 
3172 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3173                                     SmallString<32> &Target) {
3174   Target.resize(CharByteWidth * (Source.size() + 1));
3175   char *ResultPtr = &Target[0];
3176   const llvm::UTF8 *ErrorPtr;
3177   bool success =
3178       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3179   (void)success;
3180   assert(success);
3181   Target.resize(ResultPtr - &Target[0]);
3182 }
3183 
3184 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3185                                      PredefinedExpr::IdentKind IK) {
3186   // Pick the current block, lambda, captured statement or function.
3187   Decl *currentDecl = nullptr;
3188   if (const BlockScopeInfo *BSI = getCurBlock())
3189     currentDecl = BSI->TheDecl;
3190   else if (const LambdaScopeInfo *LSI = getCurLambda())
3191     currentDecl = LSI->CallOperator;
3192   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3193     currentDecl = CSI->TheCapturedDecl;
3194   else
3195     currentDecl = getCurFunctionOrMethodDecl();
3196 
3197   if (!currentDecl) {
3198     Diag(Loc, diag::ext_predef_outside_function);
3199     currentDecl = Context.getTranslationUnitDecl();
3200   }
3201 
3202   QualType ResTy;
3203   StringLiteral *SL = nullptr;
3204   if (cast<DeclContext>(currentDecl)->isDependentContext())
3205     ResTy = Context.DependentTy;
3206   else {
3207     // Pre-defined identifiers are of type char[x], where x is the length of
3208     // the string.
3209     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3210     unsigned Length = Str.length();
3211 
3212     llvm::APInt LengthI(32, Length + 1);
3213     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3214       ResTy =
3215           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3216       SmallString<32> RawChars;
3217       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3218                               Str, RawChars);
3219       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3220                                            /*IndexTypeQuals*/ 0);
3221       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3222                                  /*Pascal*/ false, ResTy, Loc);
3223     } else {
3224       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3225       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3226                                            /*IndexTypeQuals*/ 0);
3227       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3228                                  /*Pascal*/ false, ResTy, Loc);
3229     }
3230   }
3231 
3232   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3233 }
3234 
3235 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3236   PredefinedExpr::IdentKind IK;
3237 
3238   switch (Kind) {
3239   default: llvm_unreachable("Unknown simple primary expr!");
3240   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3241   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3242   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3243   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3244   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3245   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3246   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3247   }
3248 
3249   return BuildPredefinedExpr(Loc, IK);
3250 }
3251 
3252 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3253   SmallString<16> CharBuffer;
3254   bool Invalid = false;
3255   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3256   if (Invalid)
3257     return ExprError();
3258 
3259   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3260                             PP, Tok.getKind());
3261   if (Literal.hadError())
3262     return ExprError();
3263 
3264   QualType Ty;
3265   if (Literal.isWide())
3266     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3267   else if (Literal.isUTF8() && getLangOpts().Char8)
3268     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3269   else if (Literal.isUTF16())
3270     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3271   else if (Literal.isUTF32())
3272     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3273   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3274     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3275   else
3276     Ty = Context.CharTy;  // 'x' -> char in C++
3277 
3278   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3279   if (Literal.isWide())
3280     Kind = CharacterLiteral::Wide;
3281   else if (Literal.isUTF16())
3282     Kind = CharacterLiteral::UTF16;
3283   else if (Literal.isUTF32())
3284     Kind = CharacterLiteral::UTF32;
3285   else if (Literal.isUTF8())
3286     Kind = CharacterLiteral::UTF8;
3287 
3288   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3289                                              Tok.getLocation());
3290 
3291   if (Literal.getUDSuffix().empty())
3292     return Lit;
3293 
3294   // We're building a user-defined literal.
3295   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3296   SourceLocation UDSuffixLoc =
3297     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3298 
3299   // Make sure we're allowed user-defined literals here.
3300   if (!UDLScope)
3301     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3302 
3303   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3304   //   operator "" X (ch)
3305   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3306                                         Lit, Tok.getLocation());
3307 }
3308 
3309 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3310   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3311   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3312                                 Context.IntTy, Loc);
3313 }
3314 
3315 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3316                                   QualType Ty, SourceLocation Loc) {
3317   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3318 
3319   using llvm::APFloat;
3320   APFloat Val(Format);
3321 
3322   APFloat::opStatus result = Literal.GetFloatValue(Val);
3323 
3324   // Overflow is always an error, but underflow is only an error if
3325   // we underflowed to zero (APFloat reports denormals as underflow).
3326   if ((result & APFloat::opOverflow) ||
3327       ((result & APFloat::opUnderflow) && Val.isZero())) {
3328     unsigned diagnostic;
3329     SmallString<20> buffer;
3330     if (result & APFloat::opOverflow) {
3331       diagnostic = diag::warn_float_overflow;
3332       APFloat::getLargest(Format).toString(buffer);
3333     } else {
3334       diagnostic = diag::warn_float_underflow;
3335       APFloat::getSmallest(Format).toString(buffer);
3336     }
3337 
3338     S.Diag(Loc, diagnostic)
3339       << Ty
3340       << StringRef(buffer.data(), buffer.size());
3341   }
3342 
3343   bool isExact = (result == APFloat::opOK);
3344   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3345 }
3346 
3347 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3348   assert(E && "Invalid expression");
3349 
3350   if (E->isValueDependent())
3351     return false;
3352 
3353   QualType QT = E->getType();
3354   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3355     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3356     return true;
3357   }
3358 
3359   llvm::APSInt ValueAPS;
3360   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3361 
3362   if (R.isInvalid())
3363     return true;
3364 
3365   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3366   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3367     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3368         << ValueAPS.toString(10) << ValueIsPositive;
3369     return true;
3370   }
3371 
3372   return false;
3373 }
3374 
3375 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3376   // Fast path for a single digit (which is quite common).  A single digit
3377   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3378   if (Tok.getLength() == 1) {
3379     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3380     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3381   }
3382 
3383   SmallString<128> SpellingBuffer;
3384   // NumericLiteralParser wants to overread by one character.  Add padding to
3385   // the buffer in case the token is copied to the buffer.  If getSpelling()
3386   // returns a StringRef to the memory buffer, it should have a null char at
3387   // the EOF, so it is also safe.
3388   SpellingBuffer.resize(Tok.getLength() + 1);
3389 
3390   // Get the spelling of the token, which eliminates trigraphs, etc.
3391   bool Invalid = false;
3392   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3393   if (Invalid)
3394     return ExprError();
3395 
3396   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3397   if (Literal.hadError)
3398     return ExprError();
3399 
3400   if (Literal.hasUDSuffix()) {
3401     // We're building a user-defined literal.
3402     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3403     SourceLocation UDSuffixLoc =
3404       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3405 
3406     // Make sure we're allowed user-defined literals here.
3407     if (!UDLScope)
3408       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3409 
3410     QualType CookedTy;
3411     if (Literal.isFloatingLiteral()) {
3412       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3413       // long double, the literal is treated as a call of the form
3414       //   operator "" X (f L)
3415       CookedTy = Context.LongDoubleTy;
3416     } else {
3417       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3418       // unsigned long long, the literal is treated as a call of the form
3419       //   operator "" X (n ULL)
3420       CookedTy = Context.UnsignedLongLongTy;
3421     }
3422 
3423     DeclarationName OpName =
3424       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3425     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3426     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3427 
3428     SourceLocation TokLoc = Tok.getLocation();
3429 
3430     // Perform literal operator lookup to determine if we're building a raw
3431     // literal or a cooked one.
3432     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3433     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3434                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3435                                   /*AllowStringTemplate*/ false,
3436                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3437     case LOLR_ErrorNoDiagnostic:
3438       // Lookup failure for imaginary constants isn't fatal, there's still the
3439       // GNU extension producing _Complex types.
3440       break;
3441     case LOLR_Error:
3442       return ExprError();
3443     case LOLR_Cooked: {
3444       Expr *Lit;
3445       if (Literal.isFloatingLiteral()) {
3446         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3447       } else {
3448         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3449         if (Literal.GetIntegerValue(ResultVal))
3450           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3451               << /* Unsigned */ 1;
3452         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3453                                      Tok.getLocation());
3454       }
3455       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3456     }
3457 
3458     case LOLR_Raw: {
3459       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3460       // literal is treated as a call of the form
3461       //   operator "" X ("n")
3462       unsigned Length = Literal.getUDSuffixOffset();
3463       QualType StrTy = Context.getConstantArrayType(
3464           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3465           llvm::APInt(32, Length + 1), ArrayType::Normal, 0);
3466       Expr *Lit = StringLiteral::Create(
3467           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3468           /*Pascal*/false, StrTy, &TokLoc, 1);
3469       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3470     }
3471 
3472     case LOLR_Template: {
3473       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3474       // template), L is treated as a call fo the form
3475       //   operator "" X <'c1', 'c2', ... 'ck'>()
3476       // where n is the source character sequence c1 c2 ... ck.
3477       TemplateArgumentListInfo ExplicitArgs;
3478       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3479       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3480       llvm::APSInt Value(CharBits, CharIsUnsigned);
3481       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3482         Value = TokSpelling[I];
3483         TemplateArgument Arg(Context, Value, Context.CharTy);
3484         TemplateArgumentLocInfo ArgInfo;
3485         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3486       }
3487       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3488                                       &ExplicitArgs);
3489     }
3490     case LOLR_StringTemplate:
3491       llvm_unreachable("unexpected literal operator lookup result");
3492     }
3493   }
3494 
3495   Expr *Res;
3496 
3497   if (Literal.isFixedPointLiteral()) {
3498     QualType Ty;
3499 
3500     if (Literal.isAccum) {
3501       if (Literal.isHalf) {
3502         Ty = Context.ShortAccumTy;
3503       } else if (Literal.isLong) {
3504         Ty = Context.LongAccumTy;
3505       } else {
3506         Ty = Context.AccumTy;
3507       }
3508     } else if (Literal.isFract) {
3509       if (Literal.isHalf) {
3510         Ty = Context.ShortFractTy;
3511       } else if (Literal.isLong) {
3512         Ty = Context.LongFractTy;
3513       } else {
3514         Ty = Context.FractTy;
3515       }
3516     }
3517 
3518     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3519 
3520     bool isSigned = !Literal.isUnsigned;
3521     unsigned scale = Context.getFixedPointScale(Ty);
3522     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3523 
3524     llvm::APInt Val(bit_width, 0, isSigned);
3525     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3526     bool ValIsZero = Val.isNullValue() && !Overflowed;
3527 
3528     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3529     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3530       // Clause 6.4.4 - The value of a constant shall be in the range of
3531       // representable values for its type, with exception for constants of a
3532       // fract type with a value of exactly 1; such a constant shall denote
3533       // the maximal value for the type.
3534       --Val;
3535     else if (Val.ugt(MaxVal) || Overflowed)
3536       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3537 
3538     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3539                                               Tok.getLocation(), scale);
3540   } else if (Literal.isFloatingLiteral()) {
3541     QualType Ty;
3542     if (Literal.isHalf){
3543       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3544         Ty = Context.HalfTy;
3545       else {
3546         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3547         return ExprError();
3548       }
3549     } else if (Literal.isFloat)
3550       Ty = Context.FloatTy;
3551     else if (Literal.isLong)
3552       Ty = Context.LongDoubleTy;
3553     else if (Literal.isFloat16)
3554       Ty = Context.Float16Ty;
3555     else if (Literal.isFloat128)
3556       Ty = Context.Float128Ty;
3557     else
3558       Ty = Context.DoubleTy;
3559 
3560     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3561 
3562     if (Ty == Context.DoubleTy) {
3563       if (getLangOpts().SinglePrecisionConstants) {
3564         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3565         if (BTy->getKind() != BuiltinType::Float) {
3566           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3567         }
3568       } else if (getLangOpts().OpenCL &&
3569                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3570         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3571         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3572         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3573       }
3574     }
3575   } else if (!Literal.isIntegerLiteral()) {
3576     return ExprError();
3577   } else {
3578     QualType Ty;
3579 
3580     // 'long long' is a C99 or C++11 feature.
3581     if (!getLangOpts().C99 && Literal.isLongLong) {
3582       if (getLangOpts().CPlusPlus)
3583         Diag(Tok.getLocation(),
3584              getLangOpts().CPlusPlus11 ?
3585              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3586       else
3587         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3588     }
3589 
3590     // Get the value in the widest-possible width.
3591     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3592     llvm::APInt ResultVal(MaxWidth, 0);
3593 
3594     if (Literal.GetIntegerValue(ResultVal)) {
3595       // If this value didn't fit into uintmax_t, error and force to ull.
3596       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3597           << /* Unsigned */ 1;
3598       Ty = Context.UnsignedLongLongTy;
3599       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3600              "long long is not intmax_t?");
3601     } else {
3602       // If this value fits into a ULL, try to figure out what else it fits into
3603       // according to the rules of C99 6.4.4.1p5.
3604 
3605       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3606       // be an unsigned int.
3607       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3608 
3609       // Check from smallest to largest, picking the smallest type we can.
3610       unsigned Width = 0;
3611 
3612       // Microsoft specific integer suffixes are explicitly sized.
3613       if (Literal.MicrosoftInteger) {
3614         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3615           Width = 8;
3616           Ty = Context.CharTy;
3617         } else {
3618           Width = Literal.MicrosoftInteger;
3619           Ty = Context.getIntTypeForBitwidth(Width,
3620                                              /*Signed=*/!Literal.isUnsigned);
3621         }
3622       }
3623 
3624       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3625         // Are int/unsigned possibilities?
3626         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3627 
3628         // Does it fit in a unsigned int?
3629         if (ResultVal.isIntN(IntSize)) {
3630           // Does it fit in a signed int?
3631           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3632             Ty = Context.IntTy;
3633           else if (AllowUnsigned)
3634             Ty = Context.UnsignedIntTy;
3635           Width = IntSize;
3636         }
3637       }
3638 
3639       // Are long/unsigned long possibilities?
3640       if (Ty.isNull() && !Literal.isLongLong) {
3641         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3642 
3643         // Does it fit in a unsigned long?
3644         if (ResultVal.isIntN(LongSize)) {
3645           // Does it fit in a signed long?
3646           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3647             Ty = Context.LongTy;
3648           else if (AllowUnsigned)
3649             Ty = Context.UnsignedLongTy;
3650           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3651           // is compatible.
3652           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3653             const unsigned LongLongSize =
3654                 Context.getTargetInfo().getLongLongWidth();
3655             Diag(Tok.getLocation(),
3656                  getLangOpts().CPlusPlus
3657                      ? Literal.isLong
3658                            ? diag::warn_old_implicitly_unsigned_long_cxx
3659                            : /*C++98 UB*/ diag::
3660                                  ext_old_implicitly_unsigned_long_cxx
3661                      : diag::warn_old_implicitly_unsigned_long)
3662                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3663                                             : /*will be ill-formed*/ 1);
3664             Ty = Context.UnsignedLongTy;
3665           }
3666           Width = LongSize;
3667         }
3668       }
3669 
3670       // Check long long if needed.
3671       if (Ty.isNull()) {
3672         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3673 
3674         // Does it fit in a unsigned long long?
3675         if (ResultVal.isIntN(LongLongSize)) {
3676           // Does it fit in a signed long long?
3677           // To be compatible with MSVC, hex integer literals ending with the
3678           // LL or i64 suffix are always signed in Microsoft mode.
3679           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3680               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3681             Ty = Context.LongLongTy;
3682           else if (AllowUnsigned)
3683             Ty = Context.UnsignedLongLongTy;
3684           Width = LongLongSize;
3685         }
3686       }
3687 
3688       // If we still couldn't decide a type, we probably have something that
3689       // does not fit in a signed long long, but has no U suffix.
3690       if (Ty.isNull()) {
3691         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3692         Ty = Context.UnsignedLongLongTy;
3693         Width = Context.getTargetInfo().getLongLongWidth();
3694       }
3695 
3696       if (ResultVal.getBitWidth() != Width)
3697         ResultVal = ResultVal.trunc(Width);
3698     }
3699     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3700   }
3701 
3702   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3703   if (Literal.isImaginary) {
3704     Res = new (Context) ImaginaryLiteral(Res,
3705                                         Context.getComplexType(Res->getType()));
3706 
3707     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3708   }
3709   return Res;
3710 }
3711 
3712 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3713   assert(E && "ActOnParenExpr() missing expr");
3714   return new (Context) ParenExpr(L, R, E);
3715 }
3716 
3717 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3718                                          SourceLocation Loc,
3719                                          SourceRange ArgRange) {
3720   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3721   // scalar or vector data type argument..."
3722   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3723   // type (C99 6.2.5p18) or void.
3724   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3725     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3726       << T << ArgRange;
3727     return true;
3728   }
3729 
3730   assert((T->isVoidType() || !T->isIncompleteType()) &&
3731          "Scalar types should always be complete");
3732   return false;
3733 }
3734 
3735 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3736                                            SourceLocation Loc,
3737                                            SourceRange ArgRange,
3738                                            UnaryExprOrTypeTrait TraitKind) {
3739   // Invalid types must be hard errors for SFINAE in C++.
3740   if (S.LangOpts.CPlusPlus)
3741     return true;
3742 
3743   // C99 6.5.3.4p1:
3744   if (T->isFunctionType() &&
3745       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3746        TraitKind == UETT_PreferredAlignOf)) {
3747     // sizeof(function)/alignof(function) is allowed as an extension.
3748     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3749       << TraitKind << ArgRange;
3750     return false;
3751   }
3752 
3753   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3754   // this is an error (OpenCL v1.1 s6.3.k)
3755   if (T->isVoidType()) {
3756     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3757                                         : diag::ext_sizeof_alignof_void_type;
3758     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3759     return false;
3760   }
3761 
3762   return true;
3763 }
3764 
3765 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3766                                              SourceLocation Loc,
3767                                              SourceRange ArgRange,
3768                                              UnaryExprOrTypeTrait TraitKind) {
3769   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3770   // runtime doesn't allow it.
3771   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3772     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3773       << T << (TraitKind == UETT_SizeOf)
3774       << ArgRange;
3775     return true;
3776   }
3777 
3778   return false;
3779 }
3780 
3781 /// Check whether E is a pointer from a decayed array type (the decayed
3782 /// pointer type is equal to T) and emit a warning if it is.
3783 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3784                                      Expr *E) {
3785   // Don't warn if the operation changed the type.
3786   if (T != E->getType())
3787     return;
3788 
3789   // Now look for array decays.
3790   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3791   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3792     return;
3793 
3794   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3795                                              << ICE->getType()
3796                                              << ICE->getSubExpr()->getType();
3797 }
3798 
3799 /// Check the constraints on expression operands to unary type expression
3800 /// and type traits.
3801 ///
3802 /// Completes any types necessary and validates the constraints on the operand
3803 /// expression. The logic mostly mirrors the type-based overload, but may modify
3804 /// the expression as it completes the type for that expression through template
3805 /// instantiation, etc.
3806 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3807                                             UnaryExprOrTypeTrait ExprKind) {
3808   QualType ExprTy = E->getType();
3809   assert(!ExprTy->isReferenceType());
3810 
3811   if (ExprKind == UETT_VecStep)
3812     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3813                                         E->getSourceRange());
3814 
3815   // Whitelist some types as extensions
3816   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3817                                       E->getSourceRange(), ExprKind))
3818     return false;
3819 
3820   // 'alignof' applied to an expression only requires the base element type of
3821   // the expression to be complete. 'sizeof' requires the expression's type to
3822   // be complete (and will attempt to complete it if it's an array of unknown
3823   // bound).
3824   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
3825     if (RequireCompleteType(E->getExprLoc(),
3826                             Context.getBaseElementType(E->getType()),
3827                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3828                             E->getSourceRange()))
3829       return true;
3830   } else {
3831     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3832                                 ExprKind, E->getSourceRange()))
3833       return true;
3834   }
3835 
3836   // Completing the expression's type may have changed it.
3837   ExprTy = E->getType();
3838   assert(!ExprTy->isReferenceType());
3839 
3840   if (ExprTy->isFunctionType()) {
3841     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3842       << ExprKind << E->getSourceRange();
3843     return true;
3844   }
3845 
3846   // The operand for sizeof and alignof is in an unevaluated expression context,
3847   // so side effects could result in unintended consequences.
3848   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
3849        ExprKind == UETT_PreferredAlignOf) &&
3850       !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3851     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3852 
3853   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3854                                        E->getSourceRange(), ExprKind))
3855     return true;
3856 
3857   if (ExprKind == UETT_SizeOf) {
3858     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3859       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3860         QualType OType = PVD->getOriginalType();
3861         QualType Type = PVD->getType();
3862         if (Type->isPointerType() && OType->isArrayType()) {
3863           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3864             << Type << OType;
3865           Diag(PVD->getLocation(), diag::note_declared_at);
3866         }
3867       }
3868     }
3869 
3870     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3871     // decays into a pointer and returns an unintended result. This is most
3872     // likely a typo for "sizeof(array) op x".
3873     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3874       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3875                                BO->getLHS());
3876       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3877                                BO->getRHS());
3878     }
3879   }
3880 
3881   return false;
3882 }
3883 
3884 /// Check the constraints on operands to unary expression and type
3885 /// traits.
3886 ///
3887 /// This will complete any types necessary, and validate the various constraints
3888 /// on those operands.
3889 ///
3890 /// The UsualUnaryConversions() function is *not* called by this routine.
3891 /// C99 6.3.2.1p[2-4] all state:
3892 ///   Except when it is the operand of the sizeof operator ...
3893 ///
3894 /// C++ [expr.sizeof]p4
3895 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3896 ///   standard conversions are not applied to the operand of sizeof.
3897 ///
3898 /// This policy is followed for all of the unary trait expressions.
3899 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3900                                             SourceLocation OpLoc,
3901                                             SourceRange ExprRange,
3902                                             UnaryExprOrTypeTrait ExprKind) {
3903   if (ExprType->isDependentType())
3904     return false;
3905 
3906   // C++ [expr.sizeof]p2:
3907   //     When applied to a reference or a reference type, the result
3908   //     is the size of the referenced type.
3909   // C++11 [expr.alignof]p3:
3910   //     When alignof is applied to a reference type, the result
3911   //     shall be the alignment of the referenced type.
3912   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3913     ExprType = Ref->getPointeeType();
3914 
3915   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3916   //   When alignof or _Alignof is applied to an array type, the result
3917   //   is the alignment of the element type.
3918   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
3919       ExprKind == UETT_OpenMPRequiredSimdAlign)
3920     ExprType = Context.getBaseElementType(ExprType);
3921 
3922   if (ExprKind == UETT_VecStep)
3923     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3924 
3925   // Whitelist some types as extensions
3926   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3927                                       ExprKind))
3928     return false;
3929 
3930   if (RequireCompleteType(OpLoc, ExprType,
3931                           diag::err_sizeof_alignof_incomplete_type,
3932                           ExprKind, ExprRange))
3933     return true;
3934 
3935   if (ExprType->isFunctionType()) {
3936     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3937       << ExprKind << ExprRange;
3938     return true;
3939   }
3940 
3941   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3942                                        ExprKind))
3943     return true;
3944 
3945   return false;
3946 }
3947 
3948 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
3949   E = E->IgnoreParens();
3950 
3951   // Cannot know anything else if the expression is dependent.
3952   if (E->isTypeDependent())
3953     return false;
3954 
3955   if (E->getObjectKind() == OK_BitField) {
3956     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3957        << 1 << E->getSourceRange();
3958     return true;
3959   }
3960 
3961   ValueDecl *D = nullptr;
3962   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3963     D = DRE->getDecl();
3964   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3965     D = ME->getMemberDecl();
3966   }
3967 
3968   // If it's a field, require the containing struct to have a
3969   // complete definition so that we can compute the layout.
3970   //
3971   // This can happen in C++11 onwards, either by naming the member
3972   // in a way that is not transformed into a member access expression
3973   // (in an unevaluated operand, for instance), or by naming the member
3974   // in a trailing-return-type.
3975   //
3976   // For the record, since __alignof__ on expressions is a GCC
3977   // extension, GCC seems to permit this but always gives the
3978   // nonsensical answer 0.
3979   //
3980   // We don't really need the layout here --- we could instead just
3981   // directly check for all the appropriate alignment-lowing
3982   // attributes --- but that would require duplicating a lot of
3983   // logic that just isn't worth duplicating for such a marginal
3984   // use-case.
3985   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3986     // Fast path this check, since we at least know the record has a
3987     // definition if we can find a member of it.
3988     if (!FD->getParent()->isCompleteDefinition()) {
3989       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3990         << E->getSourceRange();
3991       return true;
3992     }
3993 
3994     // Otherwise, if it's a field, and the field doesn't have
3995     // reference type, then it must have a complete type (or be a
3996     // flexible array member, which we explicitly want to
3997     // white-list anyway), which makes the following checks trivial.
3998     if (!FD->getType()->isReferenceType())
3999       return false;
4000   }
4001 
4002   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4003 }
4004 
4005 bool Sema::CheckVecStepExpr(Expr *E) {
4006   E = E->IgnoreParens();
4007 
4008   // Cannot know anything else if the expression is dependent.
4009   if (E->isTypeDependent())
4010     return false;
4011 
4012   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4013 }
4014 
4015 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4016                                         CapturingScopeInfo *CSI) {
4017   assert(T->isVariablyModifiedType());
4018   assert(CSI != nullptr);
4019 
4020   // We're going to walk down into the type and look for VLA expressions.
4021   do {
4022     const Type *Ty = T.getTypePtr();
4023     switch (Ty->getTypeClass()) {
4024 #define TYPE(Class, Base)
4025 #define ABSTRACT_TYPE(Class, Base)
4026 #define NON_CANONICAL_TYPE(Class, Base)
4027 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4028 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4029 #include "clang/AST/TypeNodes.def"
4030       T = QualType();
4031       break;
4032     // These types are never variably-modified.
4033     case Type::Builtin:
4034     case Type::Complex:
4035     case Type::Vector:
4036     case Type::ExtVector:
4037     case Type::Record:
4038     case Type::Enum:
4039     case Type::Elaborated:
4040     case Type::TemplateSpecialization:
4041     case Type::ObjCObject:
4042     case Type::ObjCInterface:
4043     case Type::ObjCObjectPointer:
4044     case Type::ObjCTypeParam:
4045     case Type::Pipe:
4046       llvm_unreachable("type class is never variably-modified!");
4047     case Type::Adjusted:
4048       T = cast<AdjustedType>(Ty)->getOriginalType();
4049       break;
4050     case Type::Decayed:
4051       T = cast<DecayedType>(Ty)->getPointeeType();
4052       break;
4053     case Type::Pointer:
4054       T = cast<PointerType>(Ty)->getPointeeType();
4055       break;
4056     case Type::BlockPointer:
4057       T = cast<BlockPointerType>(Ty)->getPointeeType();
4058       break;
4059     case Type::LValueReference:
4060     case Type::RValueReference:
4061       T = cast<ReferenceType>(Ty)->getPointeeType();
4062       break;
4063     case Type::MemberPointer:
4064       T = cast<MemberPointerType>(Ty)->getPointeeType();
4065       break;
4066     case Type::ConstantArray:
4067     case Type::IncompleteArray:
4068       // Losing element qualification here is fine.
4069       T = cast<ArrayType>(Ty)->getElementType();
4070       break;
4071     case Type::VariableArray: {
4072       // Losing element qualification here is fine.
4073       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4074 
4075       // Unknown size indication requires no size computation.
4076       // Otherwise, evaluate and record it.
4077       auto Size = VAT->getSizeExpr();
4078       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4079           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4080         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4081 
4082       T = VAT->getElementType();
4083       break;
4084     }
4085     case Type::FunctionProto:
4086     case Type::FunctionNoProto:
4087       T = cast<FunctionType>(Ty)->getReturnType();
4088       break;
4089     case Type::Paren:
4090     case Type::TypeOf:
4091     case Type::UnaryTransform:
4092     case Type::Attributed:
4093     case Type::SubstTemplateTypeParm:
4094     case Type::PackExpansion:
4095     case Type::MacroQualified:
4096       // Keep walking after single level desugaring.
4097       T = T.getSingleStepDesugaredType(Context);
4098       break;
4099     case Type::Typedef:
4100       T = cast<TypedefType>(Ty)->desugar();
4101       break;
4102     case Type::Decltype:
4103       T = cast<DecltypeType>(Ty)->desugar();
4104       break;
4105     case Type::Auto:
4106     case Type::DeducedTemplateSpecialization:
4107       T = cast<DeducedType>(Ty)->getDeducedType();
4108       break;
4109     case Type::TypeOfExpr:
4110       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4111       break;
4112     case Type::Atomic:
4113       T = cast<AtomicType>(Ty)->getValueType();
4114       break;
4115     }
4116   } while (!T.isNull() && T->isVariablyModifiedType());
4117 }
4118 
4119 /// Build a sizeof or alignof expression given a type operand.
4120 ExprResult
4121 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4122                                      SourceLocation OpLoc,
4123                                      UnaryExprOrTypeTrait ExprKind,
4124                                      SourceRange R) {
4125   if (!TInfo)
4126     return ExprError();
4127 
4128   QualType T = TInfo->getType();
4129 
4130   if (!T->isDependentType() &&
4131       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4132     return ExprError();
4133 
4134   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4135     if (auto *TT = T->getAs<TypedefType>()) {
4136       for (auto I = FunctionScopes.rbegin(),
4137                 E = std::prev(FunctionScopes.rend());
4138            I != E; ++I) {
4139         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4140         if (CSI == nullptr)
4141           break;
4142         DeclContext *DC = nullptr;
4143         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4144           DC = LSI->CallOperator;
4145         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4146           DC = CRSI->TheCapturedDecl;
4147         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4148           DC = BSI->TheDecl;
4149         if (DC) {
4150           if (DC->containsDecl(TT->getDecl()))
4151             break;
4152           captureVariablyModifiedType(Context, T, CSI);
4153         }
4154       }
4155     }
4156   }
4157 
4158   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4159   return new (Context) UnaryExprOrTypeTraitExpr(
4160       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4161 }
4162 
4163 /// Build a sizeof or alignof expression given an expression
4164 /// operand.
4165 ExprResult
4166 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4167                                      UnaryExprOrTypeTrait ExprKind) {
4168   ExprResult PE = CheckPlaceholderExpr(E);
4169   if (PE.isInvalid())
4170     return ExprError();
4171 
4172   E = PE.get();
4173 
4174   // Verify that the operand is valid.
4175   bool isInvalid = false;
4176   if (E->isTypeDependent()) {
4177     // Delay type-checking for type-dependent expressions.
4178   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4179     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4180   } else if (ExprKind == UETT_VecStep) {
4181     isInvalid = CheckVecStepExpr(E);
4182   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4183       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4184       isInvalid = true;
4185   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4186     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4187     isInvalid = true;
4188   } else {
4189     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4190   }
4191 
4192   if (isInvalid)
4193     return ExprError();
4194 
4195   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4196     PE = TransformToPotentiallyEvaluated(E);
4197     if (PE.isInvalid()) return ExprError();
4198     E = PE.get();
4199   }
4200 
4201   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4202   return new (Context) UnaryExprOrTypeTraitExpr(
4203       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4204 }
4205 
4206 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4207 /// expr and the same for @c alignof and @c __alignof
4208 /// Note that the ArgRange is invalid if isType is false.
4209 ExprResult
4210 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4211                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4212                                     void *TyOrEx, SourceRange ArgRange) {
4213   // If error parsing type, ignore.
4214   if (!TyOrEx) return ExprError();
4215 
4216   if (IsType) {
4217     TypeSourceInfo *TInfo;
4218     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4219     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4220   }
4221 
4222   Expr *ArgEx = (Expr *)TyOrEx;
4223   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4224   return Result;
4225 }
4226 
4227 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4228                                      bool IsReal) {
4229   if (V.get()->isTypeDependent())
4230     return S.Context.DependentTy;
4231 
4232   // _Real and _Imag are only l-values for normal l-values.
4233   if (V.get()->getObjectKind() != OK_Ordinary) {
4234     V = S.DefaultLvalueConversion(V.get());
4235     if (V.isInvalid())
4236       return QualType();
4237   }
4238 
4239   // These operators return the element type of a complex type.
4240   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4241     return CT->getElementType();
4242 
4243   // Otherwise they pass through real integer and floating point types here.
4244   if (V.get()->getType()->isArithmeticType())
4245     return V.get()->getType();
4246 
4247   // Test for placeholders.
4248   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4249   if (PR.isInvalid()) return QualType();
4250   if (PR.get() != V.get()) {
4251     V = PR;
4252     return CheckRealImagOperand(S, V, Loc, IsReal);
4253   }
4254 
4255   // Reject anything else.
4256   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4257     << (IsReal ? "__real" : "__imag");
4258   return QualType();
4259 }
4260 
4261 
4262 
4263 ExprResult
4264 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4265                           tok::TokenKind Kind, Expr *Input) {
4266   UnaryOperatorKind Opc;
4267   switch (Kind) {
4268   default: llvm_unreachable("Unknown unary op!");
4269   case tok::plusplus:   Opc = UO_PostInc; break;
4270   case tok::minusminus: Opc = UO_PostDec; break;
4271   }
4272 
4273   // Since this might is a postfix expression, get rid of ParenListExprs.
4274   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4275   if (Result.isInvalid()) return ExprError();
4276   Input = Result.get();
4277 
4278   return BuildUnaryOp(S, OpLoc, Opc, Input);
4279 }
4280 
4281 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4282 ///
4283 /// \return true on error
4284 static bool checkArithmeticOnObjCPointer(Sema &S,
4285                                          SourceLocation opLoc,
4286                                          Expr *op) {
4287   assert(op->getType()->isObjCObjectPointerType());
4288   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4289       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4290     return false;
4291 
4292   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4293     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4294     << op->getSourceRange();
4295   return true;
4296 }
4297 
4298 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4299   auto *BaseNoParens = Base->IgnoreParens();
4300   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4301     return MSProp->getPropertyDecl()->getType()->isArrayType();
4302   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4303 }
4304 
4305 ExprResult
4306 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4307                               Expr *idx, SourceLocation rbLoc) {
4308   if (base && !base->getType().isNull() &&
4309       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4310     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4311                                     /*Length=*/nullptr, rbLoc);
4312 
4313   // Since this might be a postfix expression, get rid of ParenListExprs.
4314   if (isa<ParenListExpr>(base)) {
4315     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4316     if (result.isInvalid()) return ExprError();
4317     base = result.get();
4318   }
4319 
4320   // Handle any non-overload placeholder types in the base and index
4321   // expressions.  We can't handle overloads here because the other
4322   // operand might be an overloadable type, in which case the overload
4323   // resolution for the operator overload should get the first crack
4324   // at the overload.
4325   bool IsMSPropertySubscript = false;
4326   if (base->getType()->isNonOverloadPlaceholderType()) {
4327     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4328     if (!IsMSPropertySubscript) {
4329       ExprResult result = CheckPlaceholderExpr(base);
4330       if (result.isInvalid())
4331         return ExprError();
4332       base = result.get();
4333     }
4334   }
4335   if (idx->getType()->isNonOverloadPlaceholderType()) {
4336     ExprResult result = CheckPlaceholderExpr(idx);
4337     if (result.isInvalid()) return ExprError();
4338     idx = result.get();
4339   }
4340 
4341   // Build an unanalyzed expression if either operand is type-dependent.
4342   if (getLangOpts().CPlusPlus &&
4343       (base->isTypeDependent() || idx->isTypeDependent())) {
4344     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4345                                             VK_LValue, OK_Ordinary, rbLoc);
4346   }
4347 
4348   // MSDN, property (C++)
4349   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4350   // This attribute can also be used in the declaration of an empty array in a
4351   // class or structure definition. For example:
4352   // __declspec(property(get=GetX, put=PutX)) int x[];
4353   // The above statement indicates that x[] can be used with one or more array
4354   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4355   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4356   if (IsMSPropertySubscript) {
4357     // Build MS property subscript expression if base is MS property reference
4358     // or MS property subscript.
4359     return new (Context) MSPropertySubscriptExpr(
4360         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4361   }
4362 
4363   // Use C++ overloaded-operator rules if either operand has record
4364   // type.  The spec says to do this if either type is *overloadable*,
4365   // but enum types can't declare subscript operators or conversion
4366   // operators, so there's nothing interesting for overload resolution
4367   // to do if there aren't any record types involved.
4368   //
4369   // ObjC pointers have their own subscripting logic that is not tied
4370   // to overload resolution and so should not take this path.
4371   if (getLangOpts().CPlusPlus &&
4372       (base->getType()->isRecordType() ||
4373        (!base->getType()->isObjCObjectPointerType() &&
4374         idx->getType()->isRecordType()))) {
4375     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4376   }
4377 
4378   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4379 
4380   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4381     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4382 
4383   return Res;
4384 }
4385 
4386 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4387   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4388   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4389 
4390   // For expressions like `&(*s).b`, the base is recorded and what should be
4391   // checked.
4392   const MemberExpr *Member = nullptr;
4393   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4394     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4395 
4396   LastRecord.PossibleDerefs.erase(StrippedExpr);
4397 }
4398 
4399 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4400   QualType ResultTy = E->getType();
4401   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4402 
4403   // Bail if the element is an array since it is not memory access.
4404   if (isa<ArrayType>(ResultTy))
4405     return;
4406 
4407   if (ResultTy->hasAttr(attr::NoDeref)) {
4408     LastRecord.PossibleDerefs.insert(E);
4409     return;
4410   }
4411 
4412   // Check if the base type is a pointer to a member access of a struct
4413   // marked with noderef.
4414   const Expr *Base = E->getBase();
4415   QualType BaseTy = Base->getType();
4416   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4417     // Not a pointer access
4418     return;
4419 
4420   const MemberExpr *Member = nullptr;
4421   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4422          Member->isArrow())
4423     Base = Member->getBase();
4424 
4425   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4426     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4427       LastRecord.PossibleDerefs.insert(E);
4428   }
4429 }
4430 
4431 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4432                                           Expr *LowerBound,
4433                                           SourceLocation ColonLoc, Expr *Length,
4434                                           SourceLocation RBLoc) {
4435   if (Base->getType()->isPlaceholderType() &&
4436       !Base->getType()->isSpecificPlaceholderType(
4437           BuiltinType::OMPArraySection)) {
4438     ExprResult Result = CheckPlaceholderExpr(Base);
4439     if (Result.isInvalid())
4440       return ExprError();
4441     Base = Result.get();
4442   }
4443   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4444     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4445     if (Result.isInvalid())
4446       return ExprError();
4447     Result = DefaultLvalueConversion(Result.get());
4448     if (Result.isInvalid())
4449       return ExprError();
4450     LowerBound = Result.get();
4451   }
4452   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4453     ExprResult Result = CheckPlaceholderExpr(Length);
4454     if (Result.isInvalid())
4455       return ExprError();
4456     Result = DefaultLvalueConversion(Result.get());
4457     if (Result.isInvalid())
4458       return ExprError();
4459     Length = Result.get();
4460   }
4461 
4462   // Build an unanalyzed expression if either operand is type-dependent.
4463   if (Base->isTypeDependent() ||
4464       (LowerBound &&
4465        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4466       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4467     return new (Context)
4468         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4469                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4470   }
4471 
4472   // Perform default conversions.
4473   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4474   QualType ResultTy;
4475   if (OriginalTy->isAnyPointerType()) {
4476     ResultTy = OriginalTy->getPointeeType();
4477   } else if (OriginalTy->isArrayType()) {
4478     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4479   } else {
4480     return ExprError(
4481         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4482         << Base->getSourceRange());
4483   }
4484   // C99 6.5.2.1p1
4485   if (LowerBound) {
4486     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4487                                                       LowerBound);
4488     if (Res.isInvalid())
4489       return ExprError(Diag(LowerBound->getExprLoc(),
4490                             diag::err_omp_typecheck_section_not_integer)
4491                        << 0 << LowerBound->getSourceRange());
4492     LowerBound = Res.get();
4493 
4494     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4495         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4496       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4497           << 0 << LowerBound->getSourceRange();
4498   }
4499   if (Length) {
4500     auto Res =
4501         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4502     if (Res.isInvalid())
4503       return ExprError(Diag(Length->getExprLoc(),
4504                             diag::err_omp_typecheck_section_not_integer)
4505                        << 1 << Length->getSourceRange());
4506     Length = Res.get();
4507 
4508     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4509         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4510       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4511           << 1 << Length->getSourceRange();
4512   }
4513 
4514   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4515   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4516   // type. Note that functions are not objects, and that (in C99 parlance)
4517   // incomplete types are not object types.
4518   if (ResultTy->isFunctionType()) {
4519     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4520         << ResultTy << Base->getSourceRange();
4521     return ExprError();
4522   }
4523 
4524   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4525                           diag::err_omp_section_incomplete_type, Base))
4526     return ExprError();
4527 
4528   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4529     Expr::EvalResult Result;
4530     if (LowerBound->EvaluateAsInt(Result, Context)) {
4531       // OpenMP 4.5, [2.4 Array Sections]
4532       // The array section must be a subset of the original array.
4533       llvm::APSInt LowerBoundValue = Result.Val.getInt();
4534       if (LowerBoundValue.isNegative()) {
4535         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4536             << LowerBound->getSourceRange();
4537         return ExprError();
4538       }
4539     }
4540   }
4541 
4542   if (Length) {
4543     Expr::EvalResult Result;
4544     if (Length->EvaluateAsInt(Result, Context)) {
4545       // OpenMP 4.5, [2.4 Array Sections]
4546       // The length must evaluate to non-negative integers.
4547       llvm::APSInt LengthValue = Result.Val.getInt();
4548       if (LengthValue.isNegative()) {
4549         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4550             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4551             << Length->getSourceRange();
4552         return ExprError();
4553       }
4554     }
4555   } else if (ColonLoc.isValid() &&
4556              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4557                                       !OriginalTy->isVariableArrayType()))) {
4558     // OpenMP 4.5, [2.4 Array Sections]
4559     // When the size of the array dimension is not known, the length must be
4560     // specified explicitly.
4561     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4562         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4563     return ExprError();
4564   }
4565 
4566   if (!Base->getType()->isSpecificPlaceholderType(
4567           BuiltinType::OMPArraySection)) {
4568     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4569     if (Result.isInvalid())
4570       return ExprError();
4571     Base = Result.get();
4572   }
4573   return new (Context)
4574       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4575                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4576 }
4577 
4578 ExprResult
4579 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4580                                       Expr *Idx, SourceLocation RLoc) {
4581   Expr *LHSExp = Base;
4582   Expr *RHSExp = Idx;
4583 
4584   ExprValueKind VK = VK_LValue;
4585   ExprObjectKind OK = OK_Ordinary;
4586 
4587   // Per C++ core issue 1213, the result is an xvalue if either operand is
4588   // a non-lvalue array, and an lvalue otherwise.
4589   if (getLangOpts().CPlusPlus11) {
4590     for (auto *Op : {LHSExp, RHSExp}) {
4591       Op = Op->IgnoreImplicit();
4592       if (Op->getType()->isArrayType() && !Op->isLValue())
4593         VK = VK_XValue;
4594     }
4595   }
4596 
4597   // Perform default conversions.
4598   if (!LHSExp->getType()->getAs<VectorType>()) {
4599     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4600     if (Result.isInvalid())
4601       return ExprError();
4602     LHSExp = Result.get();
4603   }
4604   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4605   if (Result.isInvalid())
4606     return ExprError();
4607   RHSExp = Result.get();
4608 
4609   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4610 
4611   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4612   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4613   // in the subscript position. As a result, we need to derive the array base
4614   // and index from the expression types.
4615   Expr *BaseExpr, *IndexExpr;
4616   QualType ResultType;
4617   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4618     BaseExpr = LHSExp;
4619     IndexExpr = RHSExp;
4620     ResultType = Context.DependentTy;
4621   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4622     BaseExpr = LHSExp;
4623     IndexExpr = RHSExp;
4624     ResultType = PTy->getPointeeType();
4625   } else if (const ObjCObjectPointerType *PTy =
4626                LHSTy->getAs<ObjCObjectPointerType>()) {
4627     BaseExpr = LHSExp;
4628     IndexExpr = RHSExp;
4629 
4630     // Use custom logic if this should be the pseudo-object subscript
4631     // expression.
4632     if (!LangOpts.isSubscriptPointerArithmetic())
4633       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4634                                           nullptr);
4635 
4636     ResultType = PTy->getPointeeType();
4637   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4638      // Handle the uncommon case of "123[Ptr]".
4639     BaseExpr = RHSExp;
4640     IndexExpr = LHSExp;
4641     ResultType = PTy->getPointeeType();
4642   } else if (const ObjCObjectPointerType *PTy =
4643                RHSTy->getAs<ObjCObjectPointerType>()) {
4644      // Handle the uncommon case of "123[Ptr]".
4645     BaseExpr = RHSExp;
4646     IndexExpr = LHSExp;
4647     ResultType = PTy->getPointeeType();
4648     if (!LangOpts.isSubscriptPointerArithmetic()) {
4649       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4650         << ResultType << BaseExpr->getSourceRange();
4651       return ExprError();
4652     }
4653   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4654     BaseExpr = LHSExp;    // vectors: V[123]
4655     IndexExpr = RHSExp;
4656     // We apply C++ DR1213 to vector subscripting too.
4657     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
4658       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
4659       if (Materialized.isInvalid())
4660         return ExprError();
4661       LHSExp = Materialized.get();
4662     }
4663     VK = LHSExp->getValueKind();
4664     if (VK != VK_RValue)
4665       OK = OK_VectorComponent;
4666 
4667     ResultType = VTy->getElementType();
4668     QualType BaseType = BaseExpr->getType();
4669     Qualifiers BaseQuals = BaseType.getQualifiers();
4670     Qualifiers MemberQuals = ResultType.getQualifiers();
4671     Qualifiers Combined = BaseQuals + MemberQuals;
4672     if (Combined != MemberQuals)
4673       ResultType = Context.getQualifiedType(ResultType, Combined);
4674   } else if (LHSTy->isArrayType()) {
4675     // If we see an array that wasn't promoted by
4676     // DefaultFunctionArrayLvalueConversion, it must be an array that
4677     // wasn't promoted because of the C90 rule that doesn't
4678     // allow promoting non-lvalue arrays.  Warn, then
4679     // force the promotion here.
4680     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4681         << LHSExp->getSourceRange();
4682     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4683                                CK_ArrayToPointerDecay).get();
4684     LHSTy = LHSExp->getType();
4685 
4686     BaseExpr = LHSExp;
4687     IndexExpr = RHSExp;
4688     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4689   } else if (RHSTy->isArrayType()) {
4690     // Same as previous, except for 123[f().a] case
4691     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4692         << RHSExp->getSourceRange();
4693     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4694                                CK_ArrayToPointerDecay).get();
4695     RHSTy = RHSExp->getType();
4696 
4697     BaseExpr = RHSExp;
4698     IndexExpr = LHSExp;
4699     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4700   } else {
4701     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4702        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4703   }
4704   // C99 6.5.2.1p1
4705   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4706     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4707                      << IndexExpr->getSourceRange());
4708 
4709   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4710        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4711          && !IndexExpr->isTypeDependent())
4712     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4713 
4714   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4715   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4716   // type. Note that Functions are not objects, and that (in C99 parlance)
4717   // incomplete types are not object types.
4718   if (ResultType->isFunctionType()) {
4719     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
4720         << ResultType << BaseExpr->getSourceRange();
4721     return ExprError();
4722   }
4723 
4724   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4725     // GNU extension: subscripting on pointer to void
4726     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4727       << BaseExpr->getSourceRange();
4728 
4729     // C forbids expressions of unqualified void type from being l-values.
4730     // See IsCForbiddenLValueType.
4731     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4732   } else if (!ResultType->isDependentType() &&
4733       RequireCompleteType(LLoc, ResultType,
4734                           diag::err_subscript_incomplete_type, BaseExpr))
4735     return ExprError();
4736 
4737   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4738          !ResultType.isCForbiddenLValueType());
4739 
4740   return new (Context)
4741       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4742 }
4743 
4744 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4745                                   ParmVarDecl *Param) {
4746   if (Param->hasUnparsedDefaultArg()) {
4747     Diag(CallLoc,
4748          diag::err_use_of_default_argument_to_function_declared_later) <<
4749       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4750     Diag(UnparsedDefaultArgLocs[Param],
4751          diag::note_default_argument_declared_here);
4752     return true;
4753   }
4754 
4755   if (Param->hasUninstantiatedDefaultArg()) {
4756     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4757 
4758     EnterExpressionEvaluationContext EvalContext(
4759         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4760 
4761     // Instantiate the expression.
4762     //
4763     // FIXME: Pass in a correct Pattern argument, otherwise
4764     // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4765     //
4766     // template<typename T>
4767     // struct A {
4768     //   static int FooImpl();
4769     //
4770     //   template<typename Tp>
4771     //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4772     //   // template argument list [[T], [Tp]], should be [[Tp]].
4773     //   friend A<Tp> Foo(int a);
4774     // };
4775     //
4776     // template<typename T>
4777     // A<T> Foo(int a = A<T>::FooImpl());
4778     MultiLevelTemplateArgumentList MutiLevelArgList
4779       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4780 
4781     InstantiatingTemplate Inst(*this, CallLoc, Param,
4782                                MutiLevelArgList.getInnermost());
4783     if (Inst.isInvalid())
4784       return true;
4785     if (Inst.isAlreadyInstantiating()) {
4786       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4787       Param->setInvalidDecl();
4788       return true;
4789     }
4790 
4791     ExprResult Result;
4792     {
4793       // C++ [dcl.fct.default]p5:
4794       //   The names in the [default argument] expression are bound, and
4795       //   the semantic constraints are checked, at the point where the
4796       //   default argument expression appears.
4797       ContextRAII SavedContext(*this, FD);
4798       LocalInstantiationScope Local(*this);
4799       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4800                                 /*DirectInit*/false);
4801     }
4802     if (Result.isInvalid())
4803       return true;
4804 
4805     // Check the expression as an initializer for the parameter.
4806     InitializedEntity Entity
4807       = InitializedEntity::InitializeParameter(Context, Param);
4808     InitializationKind Kind = InitializationKind::CreateCopy(
4809         Param->getLocation(),
4810         /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
4811     Expr *ResultE = Result.getAs<Expr>();
4812 
4813     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4814     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4815     if (Result.isInvalid())
4816       return true;
4817 
4818     Result =
4819         ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
4820                             /*DiscardedValue*/ false);
4821     if (Result.isInvalid())
4822       return true;
4823 
4824     // Remember the instantiated default argument.
4825     Param->setDefaultArg(Result.getAs<Expr>());
4826     if (ASTMutationListener *L = getASTMutationListener()) {
4827       L->DefaultArgumentInstantiated(Param);
4828     }
4829   }
4830 
4831   // If the default argument expression is not set yet, we are building it now.
4832   if (!Param->hasInit()) {
4833     Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4834     Param->setInvalidDecl();
4835     return true;
4836   }
4837 
4838   // If the default expression creates temporaries, we need to
4839   // push them to the current stack of expression temporaries so they'll
4840   // be properly destroyed.
4841   // FIXME: We should really be rebuilding the default argument with new
4842   // bound temporaries; see the comment in PR5810.
4843   // We don't need to do that with block decls, though, because
4844   // blocks in default argument expression can never capture anything.
4845   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4846     // Set the "needs cleanups" bit regardless of whether there are
4847     // any explicit objects.
4848     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4849 
4850     // Append all the objects to the cleanup list.  Right now, this
4851     // should always be a no-op, because blocks in default argument
4852     // expressions should never be able to capture anything.
4853     assert(!Init->getNumObjects() &&
4854            "default argument expression has capturing blocks?");
4855   }
4856 
4857   // We already type-checked the argument, so we know it works.
4858   // Just mark all of the declarations in this potentially-evaluated expression
4859   // as being "referenced".
4860   EnterExpressionEvaluationContext EvalContext(
4861       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4862   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4863                                    /*SkipLocalVariables=*/true);
4864   return false;
4865 }
4866 
4867 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4868                                         FunctionDecl *FD, ParmVarDecl *Param) {
4869   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4870     return ExprError();
4871   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
4872 }
4873 
4874 Sema::VariadicCallType
4875 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4876                           Expr *Fn) {
4877   if (Proto && Proto->isVariadic()) {
4878     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4879       return VariadicConstructor;
4880     else if (Fn && Fn->getType()->isBlockPointerType())
4881       return VariadicBlock;
4882     else if (FDecl) {
4883       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4884         if (Method->isInstance())
4885           return VariadicMethod;
4886     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4887       return VariadicMethod;
4888     return VariadicFunction;
4889   }
4890   return VariadicDoesNotApply;
4891 }
4892 
4893 namespace {
4894 class FunctionCallCCC final : public FunctionCallFilterCCC {
4895 public:
4896   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4897                   unsigned NumArgs, MemberExpr *ME)
4898       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4899         FunctionName(FuncName) {}
4900 
4901   bool ValidateCandidate(const TypoCorrection &candidate) override {
4902     if (!candidate.getCorrectionSpecifier() ||
4903         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4904       return false;
4905     }
4906 
4907     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4908   }
4909 
4910   std::unique_ptr<CorrectionCandidateCallback> clone() override {
4911     return llvm::make_unique<FunctionCallCCC>(*this);
4912   }
4913 
4914 private:
4915   const IdentifierInfo *const FunctionName;
4916 };
4917 }
4918 
4919 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4920                                                FunctionDecl *FDecl,
4921                                                ArrayRef<Expr *> Args) {
4922   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4923   DeclarationName FuncName = FDecl->getDeclName();
4924   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
4925 
4926   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
4927   if (TypoCorrection Corrected = S.CorrectTypo(
4928           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4929           S.getScopeForContext(S.CurContext), nullptr, CCC,
4930           Sema::CTK_ErrorRecovery)) {
4931     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4932       if (Corrected.isOverloaded()) {
4933         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4934         OverloadCandidateSet::iterator Best;
4935         for (NamedDecl *CD : Corrected) {
4936           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4937             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4938                                    OCS);
4939         }
4940         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4941         case OR_Success:
4942           ND = Best->FoundDecl;
4943           Corrected.setCorrectionDecl(ND);
4944           break;
4945         default:
4946           break;
4947         }
4948       }
4949       ND = ND->getUnderlyingDecl();
4950       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4951         return Corrected;
4952     }
4953   }
4954   return TypoCorrection();
4955 }
4956 
4957 /// ConvertArgumentsForCall - Converts the arguments specified in
4958 /// Args/NumArgs to the parameter types of the function FDecl with
4959 /// function prototype Proto. Call is the call expression itself, and
4960 /// Fn is the function expression. For a C++ member function, this
4961 /// routine does not attempt to convert the object argument. Returns
4962 /// true if the call is ill-formed.
4963 bool
4964 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4965                               FunctionDecl *FDecl,
4966                               const FunctionProtoType *Proto,
4967                               ArrayRef<Expr *> Args,
4968                               SourceLocation RParenLoc,
4969                               bool IsExecConfig) {
4970   // Bail out early if calling a builtin with custom typechecking.
4971   if (FDecl)
4972     if (unsigned ID = FDecl->getBuiltinID())
4973       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4974         return false;
4975 
4976   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4977   // assignment, to the types of the corresponding parameter, ...
4978   unsigned NumParams = Proto->getNumParams();
4979   bool Invalid = false;
4980   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4981   unsigned FnKind = Fn->getType()->isBlockPointerType()
4982                        ? 1 /* block */
4983                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4984                                        : 0 /* function */);
4985 
4986   // If too few arguments are available (and we don't have default
4987   // arguments for the remaining parameters), don't make the call.
4988   if (Args.size() < NumParams) {
4989     if (Args.size() < MinArgs) {
4990       TypoCorrection TC;
4991       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4992         unsigned diag_id =
4993             MinArgs == NumParams && !Proto->isVariadic()
4994                 ? diag::err_typecheck_call_too_few_args_suggest
4995                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4996         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4997                                         << static_cast<unsigned>(Args.size())
4998                                         << TC.getCorrectionRange());
4999       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5000         Diag(RParenLoc,
5001              MinArgs == NumParams && !Proto->isVariadic()
5002                  ? diag::err_typecheck_call_too_few_args_one
5003                  : diag::err_typecheck_call_too_few_args_at_least_one)
5004             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5005       else
5006         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5007                             ? diag::err_typecheck_call_too_few_args
5008                             : diag::err_typecheck_call_too_few_args_at_least)
5009             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5010             << Fn->getSourceRange();
5011 
5012       // Emit the location of the prototype.
5013       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5014         Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5015 
5016       return true;
5017     }
5018     // We reserve space for the default arguments when we create
5019     // the call expression, before calling ConvertArgumentsForCall.
5020     assert((Call->getNumArgs() == NumParams) &&
5021            "We should have reserved space for the default arguments before!");
5022   }
5023 
5024   // If too many are passed and not variadic, error on the extras and drop
5025   // them.
5026   if (Args.size() > NumParams) {
5027     if (!Proto->isVariadic()) {
5028       TypoCorrection TC;
5029       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5030         unsigned diag_id =
5031             MinArgs == NumParams && !Proto->isVariadic()
5032                 ? diag::err_typecheck_call_too_many_args_suggest
5033                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5034         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5035                                         << static_cast<unsigned>(Args.size())
5036                                         << TC.getCorrectionRange());
5037       } else if (NumParams == 1 && FDecl &&
5038                  FDecl->getParamDecl(0)->getDeclName())
5039         Diag(Args[NumParams]->getBeginLoc(),
5040              MinArgs == NumParams
5041                  ? diag::err_typecheck_call_too_many_args_one
5042                  : diag::err_typecheck_call_too_many_args_at_most_one)
5043             << FnKind << FDecl->getParamDecl(0)
5044             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5045             << SourceRange(Args[NumParams]->getBeginLoc(),
5046                            Args.back()->getEndLoc());
5047       else
5048         Diag(Args[NumParams]->getBeginLoc(),
5049              MinArgs == NumParams
5050                  ? diag::err_typecheck_call_too_many_args
5051                  : diag::err_typecheck_call_too_many_args_at_most)
5052             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5053             << Fn->getSourceRange()
5054             << SourceRange(Args[NumParams]->getBeginLoc(),
5055                            Args.back()->getEndLoc());
5056 
5057       // Emit the location of the prototype.
5058       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5059         Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5060 
5061       // This deletes the extra arguments.
5062       Call->shrinkNumArgs(NumParams);
5063       return true;
5064     }
5065   }
5066   SmallVector<Expr *, 8> AllArgs;
5067   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5068 
5069   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5070                                    AllArgs, CallType);
5071   if (Invalid)
5072     return true;
5073   unsigned TotalNumArgs = AllArgs.size();
5074   for (unsigned i = 0; i < TotalNumArgs; ++i)
5075     Call->setArg(i, AllArgs[i]);
5076 
5077   return false;
5078 }
5079 
5080 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5081                                   const FunctionProtoType *Proto,
5082                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5083                                   SmallVectorImpl<Expr *> &AllArgs,
5084                                   VariadicCallType CallType, bool AllowExplicit,
5085                                   bool IsListInitialization) {
5086   unsigned NumParams = Proto->getNumParams();
5087   bool Invalid = false;
5088   size_t ArgIx = 0;
5089   // Continue to check argument types (even if we have too few/many args).
5090   for (unsigned i = FirstParam; i < NumParams; i++) {
5091     QualType ProtoArgType = Proto->getParamType(i);
5092 
5093     Expr *Arg;
5094     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5095     if (ArgIx < Args.size()) {
5096       Arg = Args[ArgIx++];
5097 
5098       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5099                               diag::err_call_incomplete_argument, Arg))
5100         return true;
5101 
5102       // Strip the unbridged-cast placeholder expression off, if applicable.
5103       bool CFAudited = false;
5104       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5105           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5106           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5107         Arg = stripARCUnbridgedCast(Arg);
5108       else if (getLangOpts().ObjCAutoRefCount &&
5109                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5110                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5111         CFAudited = true;
5112 
5113       if (Proto->getExtParameterInfo(i).isNoEscape())
5114         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5115           BE->getBlockDecl()->setDoesNotEscape();
5116 
5117       InitializedEntity Entity =
5118           Param ? InitializedEntity::InitializeParameter(Context, Param,
5119                                                          ProtoArgType)
5120                 : InitializedEntity::InitializeParameter(
5121                       Context, ProtoArgType, Proto->isParamConsumed(i));
5122 
5123       // Remember that parameter belongs to a CF audited API.
5124       if (CFAudited)
5125         Entity.setParameterCFAudited();
5126 
5127       ExprResult ArgE = PerformCopyInitialization(
5128           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5129       if (ArgE.isInvalid())
5130         return true;
5131 
5132       Arg = ArgE.getAs<Expr>();
5133     } else {
5134       assert(Param && "can't use default arguments without a known callee");
5135 
5136       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5137       if (ArgExpr.isInvalid())
5138         return true;
5139 
5140       Arg = ArgExpr.getAs<Expr>();
5141     }
5142 
5143     // Check for array bounds violations for each argument to the call. This
5144     // check only triggers warnings when the argument isn't a more complex Expr
5145     // with its own checking, such as a BinaryOperator.
5146     CheckArrayAccess(Arg);
5147 
5148     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5149     CheckStaticArrayArgument(CallLoc, Param, Arg);
5150 
5151     AllArgs.push_back(Arg);
5152   }
5153 
5154   // If this is a variadic call, handle args passed through "...".
5155   if (CallType != VariadicDoesNotApply) {
5156     // Assume that extern "C" functions with variadic arguments that
5157     // return __unknown_anytype aren't *really* variadic.
5158     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5159         FDecl->isExternC()) {
5160       for (Expr *A : Args.slice(ArgIx)) {
5161         QualType paramType; // ignored
5162         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5163         Invalid |= arg.isInvalid();
5164         AllArgs.push_back(arg.get());
5165       }
5166 
5167     // Otherwise do argument promotion, (C99 6.5.2.2p7).
5168     } else {
5169       for (Expr *A : Args.slice(ArgIx)) {
5170         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5171         Invalid |= Arg.isInvalid();
5172         AllArgs.push_back(Arg.get());
5173       }
5174     }
5175 
5176     // Check for array bounds violations.
5177     for (Expr *A : Args.slice(ArgIx))
5178       CheckArrayAccess(A);
5179   }
5180   return Invalid;
5181 }
5182 
5183 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5184   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5185   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5186     TL = DTL.getOriginalLoc();
5187   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5188     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5189       << ATL.getLocalSourceRange();
5190 }
5191 
5192 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5193 /// array parameter, check that it is non-null, and that if it is formed by
5194 /// array-to-pointer decay, the underlying array is sufficiently large.
5195 ///
5196 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5197 /// array type derivation, then for each call to the function, the value of the
5198 /// corresponding actual argument shall provide access to the first element of
5199 /// an array with at least as many elements as specified by the size expression.
5200 void
5201 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5202                                ParmVarDecl *Param,
5203                                const Expr *ArgExpr) {
5204   // Static array parameters are not supported in C++.
5205   if (!Param || getLangOpts().CPlusPlus)
5206     return;
5207 
5208   QualType OrigTy = Param->getOriginalType();
5209 
5210   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5211   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5212     return;
5213 
5214   if (ArgExpr->isNullPointerConstant(Context,
5215                                      Expr::NPC_NeverValueDependent)) {
5216     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5217     DiagnoseCalleeStaticArrayParam(*this, Param);
5218     return;
5219   }
5220 
5221   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5222   if (!CAT)
5223     return;
5224 
5225   const ConstantArrayType *ArgCAT =
5226     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5227   if (!ArgCAT)
5228     return;
5229 
5230   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5231                                              ArgCAT->getElementType())) {
5232     if (ArgCAT->getSize().ult(CAT->getSize())) {
5233       Diag(CallLoc, diag::warn_static_array_too_small)
5234           << ArgExpr->getSourceRange()
5235           << (unsigned)ArgCAT->getSize().getZExtValue()
5236           << (unsigned)CAT->getSize().getZExtValue() << 0;
5237       DiagnoseCalleeStaticArrayParam(*this, Param);
5238     }
5239     return;
5240   }
5241 
5242   Optional<CharUnits> ArgSize =
5243       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
5244   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
5245   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
5246     Diag(CallLoc, diag::warn_static_array_too_small)
5247         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
5248         << (unsigned)ParmSize->getQuantity() << 1;
5249     DiagnoseCalleeStaticArrayParam(*this, Param);
5250   }
5251 }
5252 
5253 /// Given a function expression of unknown-any type, try to rebuild it
5254 /// to have a function type.
5255 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5256 
5257 /// Is the given type a placeholder that we need to lower out
5258 /// immediately during argument processing?
5259 static bool isPlaceholderToRemoveAsArg(QualType type) {
5260   // Placeholders are never sugared.
5261   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5262   if (!placeholder) return false;
5263 
5264   switch (placeholder->getKind()) {
5265   // Ignore all the non-placeholder types.
5266 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5267   case BuiltinType::Id:
5268 #include "clang/Basic/OpenCLImageTypes.def"
5269 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
5270   case BuiltinType::Id:
5271 #include "clang/Basic/OpenCLExtensionTypes.def"
5272 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5273 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5274 #include "clang/AST/BuiltinTypes.def"
5275     return false;
5276 
5277   // We cannot lower out overload sets; they might validly be resolved
5278   // by the call machinery.
5279   case BuiltinType::Overload:
5280     return false;
5281 
5282   // Unbridged casts in ARC can be handled in some call positions and
5283   // should be left in place.
5284   case BuiltinType::ARCUnbridgedCast:
5285     return false;
5286 
5287   // Pseudo-objects should be converted as soon as possible.
5288   case BuiltinType::PseudoObject:
5289     return true;
5290 
5291   // The debugger mode could theoretically but currently does not try
5292   // to resolve unknown-typed arguments based on known parameter types.
5293   case BuiltinType::UnknownAny:
5294     return true;
5295 
5296   // These are always invalid as call arguments and should be reported.
5297   case BuiltinType::BoundMember:
5298   case BuiltinType::BuiltinFn:
5299   case BuiltinType::OMPArraySection:
5300     return true;
5301 
5302   }
5303   llvm_unreachable("bad builtin type kind");
5304 }
5305 
5306 /// Check an argument list for placeholders that we won't try to
5307 /// handle later.
5308 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5309   // Apply this processing to all the arguments at once instead of
5310   // dying at the first failure.
5311   bool hasInvalid = false;
5312   for (size_t i = 0, e = args.size(); i != e; i++) {
5313     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5314       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5315       if (result.isInvalid()) hasInvalid = true;
5316       else args[i] = result.get();
5317     } else if (hasInvalid) {
5318       (void)S.CorrectDelayedTyposInExpr(args[i]);
5319     }
5320   }
5321   return hasInvalid;
5322 }
5323 
5324 /// If a builtin function has a pointer argument with no explicit address
5325 /// space, then it should be able to accept a pointer to any address
5326 /// space as input.  In order to do this, we need to replace the
5327 /// standard builtin declaration with one that uses the same address space
5328 /// as the call.
5329 ///
5330 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5331 ///                  it does not contain any pointer arguments without
5332 ///                  an address space qualifer.  Otherwise the rewritten
5333 ///                  FunctionDecl is returned.
5334 /// TODO: Handle pointer return types.
5335 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5336                                                 const FunctionDecl *FDecl,
5337                                                 MultiExprArg ArgExprs) {
5338 
5339   QualType DeclType = FDecl->getType();
5340   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5341 
5342   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5343       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5344     return nullptr;
5345 
5346   bool NeedsNewDecl = false;
5347   unsigned i = 0;
5348   SmallVector<QualType, 8> OverloadParams;
5349 
5350   for (QualType ParamType : FT->param_types()) {
5351 
5352     // Convert array arguments to pointer to simplify type lookup.
5353     ExprResult ArgRes =
5354         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5355     if (ArgRes.isInvalid())
5356       return nullptr;
5357     Expr *Arg = ArgRes.get();
5358     QualType ArgType = Arg->getType();
5359     if (!ParamType->isPointerType() ||
5360         ParamType.getQualifiers().hasAddressSpace() ||
5361         !ArgType->isPointerType() ||
5362         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5363       OverloadParams.push_back(ParamType);
5364       continue;
5365     }
5366 
5367     QualType PointeeType = ParamType->getPointeeType();
5368     if (PointeeType.getQualifiers().hasAddressSpace())
5369       continue;
5370 
5371     NeedsNewDecl = true;
5372     LangAS AS = ArgType->getPointeeType().getAddressSpace();
5373 
5374     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5375     OverloadParams.push_back(Context.getPointerType(PointeeType));
5376   }
5377 
5378   if (!NeedsNewDecl)
5379     return nullptr;
5380 
5381   FunctionProtoType::ExtProtoInfo EPI;
5382   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5383                                                 OverloadParams, EPI);
5384   DeclContext *Parent = Context.getTranslationUnitDecl();
5385   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5386                                                     FDecl->getLocation(),
5387                                                     FDecl->getLocation(),
5388                                                     FDecl->getIdentifier(),
5389                                                     OverloadTy,
5390                                                     /*TInfo=*/nullptr,
5391                                                     SC_Extern, false,
5392                                                     /*hasPrototype=*/true);
5393   SmallVector<ParmVarDecl*, 16> Params;
5394   FT = cast<FunctionProtoType>(OverloadTy);
5395   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5396     QualType ParamType = FT->getParamType(i);
5397     ParmVarDecl *Parm =
5398         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5399                                 SourceLocation(), nullptr, ParamType,
5400                                 /*TInfo=*/nullptr, SC_None, nullptr);
5401     Parm->setScopeInfo(0, i);
5402     Params.push_back(Parm);
5403   }
5404   OverloadDecl->setParams(Params);
5405   return OverloadDecl;
5406 }
5407 
5408 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5409                                     FunctionDecl *Callee,
5410                                     MultiExprArg ArgExprs) {
5411   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5412   // similar attributes) really don't like it when functions are called with an
5413   // invalid number of args.
5414   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5415                          /*PartialOverloading=*/false) &&
5416       !Callee->isVariadic())
5417     return;
5418   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5419     return;
5420 
5421   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5422     S.Diag(Fn->getBeginLoc(),
5423            isa<CXXMethodDecl>(Callee)
5424                ? diag::err_ovl_no_viable_member_function_in_call
5425                : diag::err_ovl_no_viable_function_in_call)
5426         << Callee << Callee->getSourceRange();
5427     S.Diag(Callee->getLocation(),
5428            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5429         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5430     return;
5431   }
5432 }
5433 
5434 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
5435     const UnresolvedMemberExpr *const UME, Sema &S) {
5436 
5437   const auto GetFunctionLevelDCIfCXXClass =
5438       [](Sema &S) -> const CXXRecordDecl * {
5439     const DeclContext *const DC = S.getFunctionLevelDeclContext();
5440     if (!DC || !DC->getParent())
5441       return nullptr;
5442 
5443     // If the call to some member function was made from within a member
5444     // function body 'M' return return 'M's parent.
5445     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5446       return MD->getParent()->getCanonicalDecl();
5447     // else the call was made from within a default member initializer of a
5448     // class, so return the class.
5449     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5450       return RD->getCanonicalDecl();
5451     return nullptr;
5452   };
5453   // If our DeclContext is neither a member function nor a class (in the
5454   // case of a lambda in a default member initializer), we can't have an
5455   // enclosing 'this'.
5456 
5457   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5458   if (!CurParentClass)
5459     return false;
5460 
5461   // The naming class for implicit member functions call is the class in which
5462   // name lookup starts.
5463   const CXXRecordDecl *const NamingClass =
5464       UME->getNamingClass()->getCanonicalDecl();
5465   assert(NamingClass && "Must have naming class even for implicit access");
5466 
5467   // If the unresolved member functions were found in a 'naming class' that is
5468   // related (either the same or derived from) to the class that contains the
5469   // member function that itself contained the implicit member access.
5470 
5471   return CurParentClass == NamingClass ||
5472          CurParentClass->isDerivedFrom(NamingClass);
5473 }
5474 
5475 static void
5476 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5477     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5478 
5479   if (!UME)
5480     return;
5481 
5482   LambdaScopeInfo *const CurLSI = S.getCurLambda();
5483   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5484   // already been captured, or if this is an implicit member function call (if
5485   // it isn't, an attempt to capture 'this' should already have been made).
5486   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5487       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5488     return;
5489 
5490   // Check if the naming class in which the unresolved members were found is
5491   // related (same as or is a base of) to the enclosing class.
5492 
5493   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
5494     return;
5495 
5496 
5497   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5498   // If the enclosing function is not dependent, then this lambda is
5499   // capture ready, so if we can capture this, do so.
5500   if (!EnclosingFunctionCtx->isDependentContext()) {
5501     // If the current lambda and all enclosing lambdas can capture 'this' -
5502     // then go ahead and capture 'this' (since our unresolved overload set
5503     // contains at least one non-static member function).
5504     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5505       S.CheckCXXThisCapture(CallLoc);
5506   } else if (S.CurContext->isDependentContext()) {
5507     // ... since this is an implicit member reference, that might potentially
5508     // involve a 'this' capture, mark 'this' for potential capture in
5509     // enclosing lambdas.
5510     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5511       CurLSI->addPotentialThisCapture(CallLoc);
5512   }
5513 }
5514 
5515 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5516                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5517                                Expr *ExecConfig) {
5518   ExprResult Call =
5519       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
5520   if (Call.isInvalid())
5521     return Call;
5522 
5523   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
5524   // language modes.
5525   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
5526     if (ULE->hasExplicitTemplateArgs() &&
5527         ULE->decls_begin() == ULE->decls_end()) {
5528       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a
5529                                  ? diag::warn_cxx17_compat_adl_only_template_id
5530                                  : diag::ext_adl_only_template_id)
5531           << ULE->getName();
5532     }
5533   }
5534 
5535   return Call;
5536 }
5537 
5538 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
5539 /// This provides the location of the left/right parens and a list of comma
5540 /// locations.
5541 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5542                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5543                                Expr *ExecConfig, bool IsExecConfig) {
5544   // Since this might be a postfix expression, get rid of ParenListExprs.
5545   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5546   if (Result.isInvalid()) return ExprError();
5547   Fn = Result.get();
5548 
5549   if (checkArgsForPlaceholders(*this, ArgExprs))
5550     return ExprError();
5551 
5552   if (getLangOpts().CPlusPlus) {
5553     // If this is a pseudo-destructor expression, build the call immediately.
5554     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5555       if (!ArgExprs.empty()) {
5556         // Pseudo-destructor calls should not have any arguments.
5557         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
5558             << FixItHint::CreateRemoval(
5559                    SourceRange(ArgExprs.front()->getBeginLoc(),
5560                                ArgExprs.back()->getEndLoc()));
5561       }
5562 
5563       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
5564                               VK_RValue, RParenLoc);
5565     }
5566     if (Fn->getType() == Context.PseudoObjectTy) {
5567       ExprResult result = CheckPlaceholderExpr(Fn);
5568       if (result.isInvalid()) return ExprError();
5569       Fn = result.get();
5570     }
5571 
5572     // Determine whether this is a dependent call inside a C++ template,
5573     // in which case we won't do any semantic analysis now.
5574     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
5575       if (ExecConfig) {
5576         return CUDAKernelCallExpr::Create(
5577             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5578             Context.DependentTy, VK_RValue, RParenLoc);
5579       } else {
5580 
5581         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5582             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
5583             Fn->getBeginLoc());
5584 
5585         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5586                                 VK_RValue, RParenLoc);
5587       }
5588     }
5589 
5590     // Determine whether this is a call to an object (C++ [over.call.object]).
5591     if (Fn->getType()->isRecordType())
5592       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5593                                           RParenLoc);
5594 
5595     if (Fn->getType() == Context.UnknownAnyTy) {
5596       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5597       if (result.isInvalid()) return ExprError();
5598       Fn = result.get();
5599     }
5600 
5601     if (Fn->getType() == Context.BoundMemberTy) {
5602       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5603                                        RParenLoc);
5604     }
5605   }
5606 
5607   // Check for overloaded calls.  This can happen even in C due to extensions.
5608   if (Fn->getType() == Context.OverloadTy) {
5609     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5610 
5611     // We aren't supposed to apply this logic if there's an '&' involved.
5612     if (!find.HasFormOfMemberPointer) {
5613       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5614         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5615                                 VK_RValue, RParenLoc);
5616       OverloadExpr *ovl = find.Expression;
5617       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5618         return BuildOverloadedCallExpr(
5619             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5620             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5621       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5622                                        RParenLoc);
5623     }
5624   }
5625 
5626   // If we're directly calling a function, get the appropriate declaration.
5627   if (Fn->getType() == Context.UnknownAnyTy) {
5628     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5629     if (result.isInvalid()) return ExprError();
5630     Fn = result.get();
5631   }
5632 
5633   Expr *NakedFn = Fn->IgnoreParens();
5634 
5635   bool CallingNDeclIndirectly = false;
5636   NamedDecl *NDecl = nullptr;
5637   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5638     if (UnOp->getOpcode() == UO_AddrOf) {
5639       CallingNDeclIndirectly = true;
5640       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5641     }
5642   }
5643 
5644   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
5645     NDecl = DRE->getDecl();
5646 
5647     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5648     if (FDecl && FDecl->getBuiltinID()) {
5649       // Rewrite the function decl for this builtin by replacing parameters
5650       // with no explicit address space with the address space of the arguments
5651       // in ArgExprs.
5652       if ((FDecl =
5653                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5654         NDecl = FDecl;
5655         Fn = DeclRefExpr::Create(
5656             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5657             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
5658             nullptr, DRE->isNonOdrUse());
5659       }
5660     }
5661   } else if (isa<MemberExpr>(NakedFn))
5662     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5663 
5664   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5665     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
5666                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
5667       return ExprError();
5668 
5669     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5670       return ExprError();
5671 
5672     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5673   }
5674 
5675   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5676                                ExecConfig, IsExecConfig);
5677 }
5678 
5679 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5680 ///
5681 /// __builtin_astype( value, dst type )
5682 ///
5683 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5684                                  SourceLocation BuiltinLoc,
5685                                  SourceLocation RParenLoc) {
5686   ExprValueKind VK = VK_RValue;
5687   ExprObjectKind OK = OK_Ordinary;
5688   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5689   QualType SrcTy = E->getType();
5690   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5691     return ExprError(Diag(BuiltinLoc,
5692                           diag::err_invalid_astype_of_different_size)
5693                      << DstTy
5694                      << SrcTy
5695                      << E->getSourceRange());
5696   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5697 }
5698 
5699 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5700 /// provided arguments.
5701 ///
5702 /// __builtin_convertvector( value, dst type )
5703 ///
5704 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5705                                         SourceLocation BuiltinLoc,
5706                                         SourceLocation RParenLoc) {
5707   TypeSourceInfo *TInfo;
5708   GetTypeFromParser(ParsedDestTy, &TInfo);
5709   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5710 }
5711 
5712 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5713 /// i.e. an expression not of \p OverloadTy.  The expression should
5714 /// unary-convert to an expression of function-pointer or
5715 /// block-pointer type.
5716 ///
5717 /// \param NDecl the declaration being called, if available
5718 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5719                                        SourceLocation LParenLoc,
5720                                        ArrayRef<Expr *> Args,
5721                                        SourceLocation RParenLoc, Expr *Config,
5722                                        bool IsExecConfig, ADLCallKind UsesADL) {
5723   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5724   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5725 
5726   // Functions with 'interrupt' attribute cannot be called directly.
5727   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5728     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5729     return ExprError();
5730   }
5731 
5732   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5733   // so there's some risk when calling out to non-interrupt handler functions
5734   // that the callee might not preserve them. This is easy to diagnose here,
5735   // but can be very challenging to debug.
5736   if (auto *Caller = getCurFunctionDecl())
5737     if (Caller->hasAttr<ARMInterruptAttr>()) {
5738       bool VFP = Context.getTargetInfo().hasFeature("vfp");
5739       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5740         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5741     }
5742 
5743   // Promote the function operand.
5744   // We special-case function promotion here because we only allow promoting
5745   // builtin functions to function pointers in the callee of a call.
5746   ExprResult Result;
5747   QualType ResultTy;
5748   if (BuiltinID &&
5749       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5750     // Extract the return type from the (builtin) function pointer type.
5751     // FIXME Several builtins still have setType in
5752     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
5753     // Builtins.def to ensure they are correct before removing setType calls.
5754     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
5755     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
5756     ResultTy = FDecl->getCallResultType();
5757   } else {
5758     Result = CallExprUnaryConversions(Fn);
5759     ResultTy = Context.BoolTy;
5760   }
5761   if (Result.isInvalid())
5762     return ExprError();
5763   Fn = Result.get();
5764 
5765   // Check for a valid function type, but only if it is not a builtin which
5766   // requires custom type checking. These will be handled by
5767   // CheckBuiltinFunctionCall below just after creation of the call expression.
5768   const FunctionType *FuncT = nullptr;
5769   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
5770    retry:
5771     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5772       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5773       // have type pointer to function".
5774       FuncT = PT->getPointeeType()->getAs<FunctionType>();
5775       if (!FuncT)
5776         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5777                            << Fn->getType() << Fn->getSourceRange());
5778     } else if (const BlockPointerType *BPT =
5779                  Fn->getType()->getAs<BlockPointerType>()) {
5780       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5781     } else {
5782       // Handle calls to expressions of unknown-any type.
5783       if (Fn->getType() == Context.UnknownAnyTy) {
5784         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5785         if (rewrite.isInvalid()) return ExprError();
5786         Fn = rewrite.get();
5787         goto retry;
5788       }
5789 
5790     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5791       << Fn->getType() << Fn->getSourceRange());
5792     }
5793   }
5794 
5795   // Get the number of parameters in the function prototype, if any.
5796   // We will allocate space for max(Args.size(), NumParams) arguments
5797   // in the call expression.
5798   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
5799   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
5800 
5801   CallExpr *TheCall;
5802   if (Config) {
5803     assert(UsesADL == ADLCallKind::NotADL &&
5804            "CUDAKernelCallExpr should not use ADL");
5805     TheCall =
5806         CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
5807                                    ResultTy, VK_RValue, RParenLoc, NumParams);
5808   } else {
5809     TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
5810                                RParenLoc, NumParams, UsesADL);
5811   }
5812 
5813   if (!getLangOpts().CPlusPlus) {
5814     // Forget about the nulled arguments since typo correction
5815     // do not handle them well.
5816     TheCall->shrinkNumArgs(Args.size());
5817     // C cannot always handle TypoExpr nodes in builtin calls and direct
5818     // function calls as their argument checking don't necessarily handle
5819     // dependent types properly, so make sure any TypoExprs have been
5820     // dealt with.
5821     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5822     if (!Result.isUsable()) return ExprError();
5823     CallExpr *TheOldCall = TheCall;
5824     TheCall = dyn_cast<CallExpr>(Result.get());
5825     bool CorrectedTypos = TheCall != TheOldCall;
5826     if (!TheCall) return Result;
5827     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5828 
5829     // A new call expression node was created if some typos were corrected.
5830     // However it may not have been constructed with enough storage. In this
5831     // case, rebuild the node with enough storage. The waste of space is
5832     // immaterial since this only happens when some typos were corrected.
5833     if (CorrectedTypos && Args.size() < NumParams) {
5834       if (Config)
5835         TheCall = CUDAKernelCallExpr::Create(
5836             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
5837             RParenLoc, NumParams);
5838       else
5839         TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
5840                                    RParenLoc, NumParams, UsesADL);
5841     }
5842     // We can now handle the nulled arguments for the default arguments.
5843     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
5844   }
5845 
5846   // Bail out early if calling a builtin with custom type checking.
5847   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5848     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5849 
5850   if (getLangOpts().CUDA) {
5851     if (Config) {
5852       // CUDA: Kernel calls must be to global functions
5853       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5854         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5855             << FDecl << Fn->getSourceRange());
5856 
5857       // CUDA: Kernel function must have 'void' return type
5858       if (!FuncT->getReturnType()->isVoidType())
5859         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5860             << Fn->getType() << Fn->getSourceRange());
5861     } else {
5862       // CUDA: Calls to global functions must be configured
5863       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5864         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5865             << FDecl << Fn->getSourceRange());
5866     }
5867   }
5868 
5869   // Check for a valid return type
5870   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
5871                           FDecl))
5872     return ExprError();
5873 
5874   // We know the result type of the call, set it.
5875   TheCall->setType(FuncT->getCallResultType(Context));
5876   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5877 
5878   if (Proto) {
5879     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5880                                 IsExecConfig))
5881       return ExprError();
5882   } else {
5883     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5884 
5885     if (FDecl) {
5886       // Check if we have too few/too many template arguments, based
5887       // on our knowledge of the function definition.
5888       const FunctionDecl *Def = nullptr;
5889       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5890         Proto = Def->getType()->getAs<FunctionProtoType>();
5891        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5892           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5893           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5894       }
5895 
5896       // If the function we're calling isn't a function prototype, but we have
5897       // a function prototype from a prior declaratiom, use that prototype.
5898       if (!FDecl->hasPrototype())
5899         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5900     }
5901 
5902     // Promote the arguments (C99 6.5.2.2p6).
5903     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5904       Expr *Arg = Args[i];
5905 
5906       if (Proto && i < Proto->getNumParams()) {
5907         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5908             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5909         ExprResult ArgE =
5910             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5911         if (ArgE.isInvalid())
5912           return true;
5913 
5914         Arg = ArgE.getAs<Expr>();
5915 
5916       } else {
5917         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5918 
5919         if (ArgE.isInvalid())
5920           return true;
5921 
5922         Arg = ArgE.getAs<Expr>();
5923       }
5924 
5925       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
5926                               diag::err_call_incomplete_argument, Arg))
5927         return ExprError();
5928 
5929       TheCall->setArg(i, Arg);
5930     }
5931   }
5932 
5933   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5934     if (!Method->isStatic())
5935       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5936         << Fn->getSourceRange());
5937 
5938   // Check for sentinels
5939   if (NDecl)
5940     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5941 
5942   // Do special checking on direct calls to functions.
5943   if (FDecl) {
5944     if (CheckFunctionCall(FDecl, TheCall, Proto))
5945       return ExprError();
5946 
5947     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
5948 
5949     if (BuiltinID)
5950       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5951   } else if (NDecl) {
5952     if (CheckPointerCall(NDecl, TheCall, Proto))
5953       return ExprError();
5954   } else {
5955     if (CheckOtherCall(TheCall, Proto))
5956       return ExprError();
5957   }
5958 
5959   return MaybeBindToTemporary(TheCall);
5960 }
5961 
5962 ExprResult
5963 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5964                            SourceLocation RParenLoc, Expr *InitExpr) {
5965   assert(Ty && "ActOnCompoundLiteral(): missing type");
5966   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5967 
5968   TypeSourceInfo *TInfo;
5969   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5970   if (!TInfo)
5971     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5972 
5973   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5974 }
5975 
5976 ExprResult
5977 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5978                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5979   QualType literalType = TInfo->getType();
5980 
5981   if (literalType->isArrayType()) {
5982     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5983           diag::err_illegal_decl_array_incomplete_type,
5984           SourceRange(LParenLoc,
5985                       LiteralExpr->getSourceRange().getEnd())))
5986       return ExprError();
5987     if (literalType->isVariableArrayType())
5988       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5989         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5990   } else if (!literalType->isDependentType() &&
5991              RequireCompleteType(LParenLoc, literalType,
5992                diag::err_typecheck_decl_incomplete_type,
5993                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5994     return ExprError();
5995 
5996   InitializedEntity Entity
5997     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5998   InitializationKind Kind
5999     = InitializationKind::CreateCStyleCast(LParenLoc,
6000                                            SourceRange(LParenLoc, RParenLoc),
6001                                            /*InitList=*/true);
6002   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6003   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6004                                       &literalType);
6005   if (Result.isInvalid())
6006     return ExprError();
6007   LiteralExpr = Result.get();
6008 
6009   bool isFileScope = !CurContext->isFunctionOrMethod();
6010 
6011   // In C, compound literals are l-values for some reason.
6012   // For GCC compatibility, in C++, file-scope array compound literals with
6013   // constant initializers are also l-values, and compound literals are
6014   // otherwise prvalues.
6015   //
6016   // (GCC also treats C++ list-initialized file-scope array prvalues with
6017   // constant initializers as l-values, but that's non-conforming, so we don't
6018   // follow it there.)
6019   //
6020   // FIXME: It would be better to handle the lvalue cases as materializing and
6021   // lifetime-extending a temporary object, but our materialized temporaries
6022   // representation only supports lifetime extension from a variable, not "out
6023   // of thin air".
6024   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6025   // is bound to the result of applying array-to-pointer decay to the compound
6026   // literal.
6027   // FIXME: GCC supports compound literals of reference type, which should
6028   // obviously have a value kind derived from the kind of reference involved.
6029   ExprValueKind VK =
6030       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6031           ? VK_RValue
6032           : VK_LValue;
6033 
6034   if (isFileScope)
6035     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6036       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6037         Expr *Init = ILE->getInit(i);
6038         ILE->setInit(i, ConstantExpr::Create(Context, Init));
6039       }
6040 
6041   Expr *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6042                                               VK, LiteralExpr, isFileScope);
6043   if (isFileScope) {
6044     if (!LiteralExpr->isTypeDependent() &&
6045         !LiteralExpr->isValueDependent() &&
6046         !literalType->isDependentType()) // C99 6.5.2.5p3
6047       if (CheckForConstantInitializer(LiteralExpr, literalType))
6048         return ExprError();
6049   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6050              literalType.getAddressSpace() != LangAS::Default) {
6051     // Embedded-C extensions to C99 6.5.2.5:
6052     //   "If the compound literal occurs inside the body of a function, the
6053     //   type name shall not be qualified by an address-space qualifier."
6054     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6055       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6056     return ExprError();
6057   }
6058 
6059   return MaybeBindToTemporary(E);
6060 }
6061 
6062 ExprResult
6063 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6064                     SourceLocation RBraceLoc) {
6065   // Immediately handle non-overload placeholders.  Overloads can be
6066   // resolved contextually, but everything else here can't.
6067   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6068     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6069       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6070 
6071       // Ignore failures; dropping the entire initializer list because
6072       // of one failure would be terrible for indexing/etc.
6073       if (result.isInvalid()) continue;
6074 
6075       InitArgList[I] = result.get();
6076     }
6077   }
6078 
6079   // Semantic analysis for initializers is done by ActOnDeclarator() and
6080   // CheckInitializer() - it requires knowledge of the object being initialized.
6081 
6082   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6083                                                RBraceLoc);
6084   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6085   return E;
6086 }
6087 
6088 /// Do an explicit extend of the given block pointer if we're in ARC.
6089 void Sema::maybeExtendBlockObject(ExprResult &E) {
6090   assert(E.get()->getType()->isBlockPointerType());
6091   assert(E.get()->isRValue());
6092 
6093   // Only do this in an r-value context.
6094   if (!getLangOpts().ObjCAutoRefCount) return;
6095 
6096   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
6097                                CK_ARCExtendBlockObject, E.get(),
6098                                /*base path*/ nullptr, VK_RValue);
6099   Cleanup.setExprNeedsCleanups(true);
6100 }
6101 
6102 /// Prepare a conversion of the given expression to an ObjC object
6103 /// pointer type.
6104 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
6105   QualType type = E.get()->getType();
6106   if (type->isObjCObjectPointerType()) {
6107     return CK_BitCast;
6108   } else if (type->isBlockPointerType()) {
6109     maybeExtendBlockObject(E);
6110     return CK_BlockPointerToObjCPointerCast;
6111   } else {
6112     assert(type->isPointerType());
6113     return CK_CPointerToObjCPointerCast;
6114   }
6115 }
6116 
6117 /// Prepares for a scalar cast, performing all the necessary stages
6118 /// except the final cast and returning the kind required.
6119 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
6120   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
6121   // Also, callers should have filtered out the invalid cases with
6122   // pointers.  Everything else should be possible.
6123 
6124   QualType SrcTy = Src.get()->getType();
6125   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
6126     return CK_NoOp;
6127 
6128   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
6129   case Type::STK_MemberPointer:
6130     llvm_unreachable("member pointer type in C");
6131 
6132   case Type::STK_CPointer:
6133   case Type::STK_BlockPointer:
6134   case Type::STK_ObjCObjectPointer:
6135     switch (DestTy->getScalarTypeKind()) {
6136     case Type::STK_CPointer: {
6137       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
6138       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
6139       if (SrcAS != DestAS)
6140         return CK_AddressSpaceConversion;
6141       if (Context.hasCvrSimilarType(SrcTy, DestTy))
6142         return CK_NoOp;
6143       return CK_BitCast;
6144     }
6145     case Type::STK_BlockPointer:
6146       return (SrcKind == Type::STK_BlockPointer
6147                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
6148     case Type::STK_ObjCObjectPointer:
6149       if (SrcKind == Type::STK_ObjCObjectPointer)
6150         return CK_BitCast;
6151       if (SrcKind == Type::STK_CPointer)
6152         return CK_CPointerToObjCPointerCast;
6153       maybeExtendBlockObject(Src);
6154       return CK_BlockPointerToObjCPointerCast;
6155     case Type::STK_Bool:
6156       return CK_PointerToBoolean;
6157     case Type::STK_Integral:
6158       return CK_PointerToIntegral;
6159     case Type::STK_Floating:
6160     case Type::STK_FloatingComplex:
6161     case Type::STK_IntegralComplex:
6162     case Type::STK_MemberPointer:
6163     case Type::STK_FixedPoint:
6164       llvm_unreachable("illegal cast from pointer");
6165     }
6166     llvm_unreachable("Should have returned before this");
6167 
6168   case Type::STK_FixedPoint:
6169     switch (DestTy->getScalarTypeKind()) {
6170     case Type::STK_FixedPoint:
6171       return CK_FixedPointCast;
6172     case Type::STK_Bool:
6173       return CK_FixedPointToBoolean;
6174     case Type::STK_Integral:
6175       return CK_FixedPointToIntegral;
6176     case Type::STK_Floating:
6177     case Type::STK_IntegralComplex:
6178     case Type::STK_FloatingComplex:
6179       Diag(Src.get()->getExprLoc(),
6180            diag::err_unimplemented_conversion_with_fixed_point_type)
6181           << DestTy;
6182       return CK_IntegralCast;
6183     case Type::STK_CPointer:
6184     case Type::STK_ObjCObjectPointer:
6185     case Type::STK_BlockPointer:
6186     case Type::STK_MemberPointer:
6187       llvm_unreachable("illegal cast to pointer type");
6188     }
6189     llvm_unreachable("Should have returned before this");
6190 
6191   case Type::STK_Bool: // casting from bool is like casting from an integer
6192   case Type::STK_Integral:
6193     switch (DestTy->getScalarTypeKind()) {
6194     case Type::STK_CPointer:
6195     case Type::STK_ObjCObjectPointer:
6196     case Type::STK_BlockPointer:
6197       if (Src.get()->isNullPointerConstant(Context,
6198                                            Expr::NPC_ValueDependentIsNull))
6199         return CK_NullToPointer;
6200       return CK_IntegralToPointer;
6201     case Type::STK_Bool:
6202       return CK_IntegralToBoolean;
6203     case Type::STK_Integral:
6204       return CK_IntegralCast;
6205     case Type::STK_Floating:
6206       return CK_IntegralToFloating;
6207     case Type::STK_IntegralComplex:
6208       Src = ImpCastExprToType(Src.get(),
6209                       DestTy->castAs<ComplexType>()->getElementType(),
6210                       CK_IntegralCast);
6211       return CK_IntegralRealToComplex;
6212     case Type::STK_FloatingComplex:
6213       Src = ImpCastExprToType(Src.get(),
6214                       DestTy->castAs<ComplexType>()->getElementType(),
6215                       CK_IntegralToFloating);
6216       return CK_FloatingRealToComplex;
6217     case Type::STK_MemberPointer:
6218       llvm_unreachable("member pointer type in C");
6219     case Type::STK_FixedPoint:
6220       return CK_IntegralToFixedPoint;
6221     }
6222     llvm_unreachable("Should have returned before this");
6223 
6224   case Type::STK_Floating:
6225     switch (DestTy->getScalarTypeKind()) {
6226     case Type::STK_Floating:
6227       return CK_FloatingCast;
6228     case Type::STK_Bool:
6229       return CK_FloatingToBoolean;
6230     case Type::STK_Integral:
6231       return CK_FloatingToIntegral;
6232     case Type::STK_FloatingComplex:
6233       Src = ImpCastExprToType(Src.get(),
6234                               DestTy->castAs<ComplexType>()->getElementType(),
6235                               CK_FloatingCast);
6236       return CK_FloatingRealToComplex;
6237     case Type::STK_IntegralComplex:
6238       Src = ImpCastExprToType(Src.get(),
6239                               DestTy->castAs<ComplexType>()->getElementType(),
6240                               CK_FloatingToIntegral);
6241       return CK_IntegralRealToComplex;
6242     case Type::STK_CPointer:
6243     case Type::STK_ObjCObjectPointer:
6244     case Type::STK_BlockPointer:
6245       llvm_unreachable("valid float->pointer cast?");
6246     case Type::STK_MemberPointer:
6247       llvm_unreachable("member pointer type in C");
6248     case Type::STK_FixedPoint:
6249       Diag(Src.get()->getExprLoc(),
6250            diag::err_unimplemented_conversion_with_fixed_point_type)
6251           << SrcTy;
6252       return CK_IntegralCast;
6253     }
6254     llvm_unreachable("Should have returned before this");
6255 
6256   case Type::STK_FloatingComplex:
6257     switch (DestTy->getScalarTypeKind()) {
6258     case Type::STK_FloatingComplex:
6259       return CK_FloatingComplexCast;
6260     case Type::STK_IntegralComplex:
6261       return CK_FloatingComplexToIntegralComplex;
6262     case Type::STK_Floating: {
6263       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6264       if (Context.hasSameType(ET, DestTy))
6265         return CK_FloatingComplexToReal;
6266       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
6267       return CK_FloatingCast;
6268     }
6269     case Type::STK_Bool:
6270       return CK_FloatingComplexToBoolean;
6271     case Type::STK_Integral:
6272       Src = ImpCastExprToType(Src.get(),
6273                               SrcTy->castAs<ComplexType>()->getElementType(),
6274                               CK_FloatingComplexToReal);
6275       return CK_FloatingToIntegral;
6276     case Type::STK_CPointer:
6277     case Type::STK_ObjCObjectPointer:
6278     case Type::STK_BlockPointer:
6279       llvm_unreachable("valid complex float->pointer cast?");
6280     case Type::STK_MemberPointer:
6281       llvm_unreachable("member pointer type in C");
6282     case Type::STK_FixedPoint:
6283       Diag(Src.get()->getExprLoc(),
6284            diag::err_unimplemented_conversion_with_fixed_point_type)
6285           << SrcTy;
6286       return CK_IntegralCast;
6287     }
6288     llvm_unreachable("Should have returned before this");
6289 
6290   case Type::STK_IntegralComplex:
6291     switch (DestTy->getScalarTypeKind()) {
6292     case Type::STK_FloatingComplex:
6293       return CK_IntegralComplexToFloatingComplex;
6294     case Type::STK_IntegralComplex:
6295       return CK_IntegralComplexCast;
6296     case Type::STK_Integral: {
6297       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6298       if (Context.hasSameType(ET, DestTy))
6299         return CK_IntegralComplexToReal;
6300       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
6301       return CK_IntegralCast;
6302     }
6303     case Type::STK_Bool:
6304       return CK_IntegralComplexToBoolean;
6305     case Type::STK_Floating:
6306       Src = ImpCastExprToType(Src.get(),
6307                               SrcTy->castAs<ComplexType>()->getElementType(),
6308                               CK_IntegralComplexToReal);
6309       return CK_IntegralToFloating;
6310     case Type::STK_CPointer:
6311     case Type::STK_ObjCObjectPointer:
6312     case Type::STK_BlockPointer:
6313       llvm_unreachable("valid complex int->pointer cast?");
6314     case Type::STK_MemberPointer:
6315       llvm_unreachable("member pointer type in C");
6316     case Type::STK_FixedPoint:
6317       Diag(Src.get()->getExprLoc(),
6318            diag::err_unimplemented_conversion_with_fixed_point_type)
6319           << SrcTy;
6320       return CK_IntegralCast;
6321     }
6322     llvm_unreachable("Should have returned before this");
6323   }
6324 
6325   llvm_unreachable("Unhandled scalar cast");
6326 }
6327 
6328 static bool breakDownVectorType(QualType type, uint64_t &len,
6329                                 QualType &eltType) {
6330   // Vectors are simple.
6331   if (const VectorType *vecType = type->getAs<VectorType>()) {
6332     len = vecType->getNumElements();
6333     eltType = vecType->getElementType();
6334     assert(eltType->isScalarType());
6335     return true;
6336   }
6337 
6338   // We allow lax conversion to and from non-vector types, but only if
6339   // they're real types (i.e. non-complex, non-pointer scalar types).
6340   if (!type->isRealType()) return false;
6341 
6342   len = 1;
6343   eltType = type;
6344   return true;
6345 }
6346 
6347 /// Are the two types lax-compatible vector types?  That is, given
6348 /// that one of them is a vector, do they have equal storage sizes,
6349 /// where the storage size is the number of elements times the element
6350 /// size?
6351 ///
6352 /// This will also return false if either of the types is neither a
6353 /// vector nor a real type.
6354 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
6355   assert(destTy->isVectorType() || srcTy->isVectorType());
6356 
6357   // Disallow lax conversions between scalars and ExtVectors (these
6358   // conversions are allowed for other vector types because common headers
6359   // depend on them).  Most scalar OP ExtVector cases are handled by the
6360   // splat path anyway, which does what we want (convert, not bitcast).
6361   // What this rules out for ExtVectors is crazy things like char4*float.
6362   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
6363   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
6364 
6365   uint64_t srcLen, destLen;
6366   QualType srcEltTy, destEltTy;
6367   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
6368   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
6369 
6370   // ASTContext::getTypeSize will return the size rounded up to a
6371   // power of 2, so instead of using that, we need to use the raw
6372   // element size multiplied by the element count.
6373   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
6374   uint64_t destEltSize = Context.getTypeSize(destEltTy);
6375 
6376   return (srcLen * srcEltSize == destLen * destEltSize);
6377 }
6378 
6379 /// Is this a legal conversion between two types, one of which is
6380 /// known to be a vector type?
6381 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
6382   assert(destTy->isVectorType() || srcTy->isVectorType());
6383 
6384   if (!Context.getLangOpts().LaxVectorConversions)
6385     return false;
6386   return areLaxCompatibleVectorTypes(srcTy, destTy);
6387 }
6388 
6389 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
6390                            CastKind &Kind) {
6391   assert(VectorTy->isVectorType() && "Not a vector type!");
6392 
6393   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
6394     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
6395       return Diag(R.getBegin(),
6396                   Ty->isVectorType() ?
6397                   diag::err_invalid_conversion_between_vectors :
6398                   diag::err_invalid_conversion_between_vector_and_integer)
6399         << VectorTy << Ty << R;
6400   } else
6401     return Diag(R.getBegin(),
6402                 diag::err_invalid_conversion_between_vector_and_scalar)
6403       << VectorTy << Ty << R;
6404 
6405   Kind = CK_BitCast;
6406   return false;
6407 }
6408 
6409 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
6410   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
6411 
6412   if (DestElemTy == SplattedExpr->getType())
6413     return SplattedExpr;
6414 
6415   assert(DestElemTy->isFloatingType() ||
6416          DestElemTy->isIntegralOrEnumerationType());
6417 
6418   CastKind CK;
6419   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6420     // OpenCL requires that we convert `true` boolean expressions to -1, but
6421     // only when splatting vectors.
6422     if (DestElemTy->isFloatingType()) {
6423       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6424       // in two steps: boolean to signed integral, then to floating.
6425       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6426                                                  CK_BooleanToSignedIntegral);
6427       SplattedExpr = CastExprRes.get();
6428       CK = CK_IntegralToFloating;
6429     } else {
6430       CK = CK_BooleanToSignedIntegral;
6431     }
6432   } else {
6433     ExprResult CastExprRes = SplattedExpr;
6434     CK = PrepareScalarCast(CastExprRes, DestElemTy);
6435     if (CastExprRes.isInvalid())
6436       return ExprError();
6437     SplattedExpr = CastExprRes.get();
6438   }
6439   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6440 }
6441 
6442 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6443                                     Expr *CastExpr, CastKind &Kind) {
6444   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6445 
6446   QualType SrcTy = CastExpr->getType();
6447 
6448   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6449   // an ExtVectorType.
6450   // In OpenCL, casts between vectors of different types are not allowed.
6451   // (See OpenCL 6.2).
6452   if (SrcTy->isVectorType()) {
6453     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
6454         (getLangOpts().OpenCL &&
6455          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
6456       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6457         << DestTy << SrcTy << R;
6458       return ExprError();
6459     }
6460     Kind = CK_BitCast;
6461     return CastExpr;
6462   }
6463 
6464   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6465   // conversion will take place first from scalar to elt type, and then
6466   // splat from elt type to vector.
6467   if (SrcTy->isPointerType())
6468     return Diag(R.getBegin(),
6469                 diag::err_invalid_conversion_between_vector_and_scalar)
6470       << DestTy << SrcTy << R;
6471 
6472   Kind = CK_VectorSplat;
6473   return prepareVectorSplat(DestTy, CastExpr);
6474 }
6475 
6476 ExprResult
6477 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6478                     Declarator &D, ParsedType &Ty,
6479                     SourceLocation RParenLoc, Expr *CastExpr) {
6480   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6481          "ActOnCastExpr(): missing type or expr");
6482 
6483   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6484   if (D.isInvalidType())
6485     return ExprError();
6486 
6487   if (getLangOpts().CPlusPlus) {
6488     // Check that there are no default arguments (C++ only).
6489     CheckExtraCXXDefaultArguments(D);
6490   } else {
6491     // Make sure any TypoExprs have been dealt with.
6492     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6493     if (!Res.isUsable())
6494       return ExprError();
6495     CastExpr = Res.get();
6496   }
6497 
6498   checkUnusedDeclAttributes(D);
6499 
6500   QualType castType = castTInfo->getType();
6501   Ty = CreateParsedType(castType, castTInfo);
6502 
6503   bool isVectorLiteral = false;
6504 
6505   // Check for an altivec or OpenCL literal,
6506   // i.e. all the elements are integer constants.
6507   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6508   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6509   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6510        && castType->isVectorType() && (PE || PLE)) {
6511     if (PLE && PLE->getNumExprs() == 0) {
6512       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6513       return ExprError();
6514     }
6515     if (PE || PLE->getNumExprs() == 1) {
6516       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6517       if (!E->getType()->isVectorType())
6518         isVectorLiteral = true;
6519     }
6520     else
6521       isVectorLiteral = true;
6522   }
6523 
6524   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6525   // then handle it as such.
6526   if (isVectorLiteral)
6527     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6528 
6529   // If the Expr being casted is a ParenListExpr, handle it specially.
6530   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6531   // sequence of BinOp comma operators.
6532   if (isa<ParenListExpr>(CastExpr)) {
6533     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6534     if (Result.isInvalid()) return ExprError();
6535     CastExpr = Result.get();
6536   }
6537 
6538   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6539       !getSourceManager().isInSystemMacro(LParenLoc))
6540     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6541 
6542   CheckTollFreeBridgeCast(castType, CastExpr);
6543 
6544   CheckObjCBridgeRelatedCast(castType, CastExpr);
6545 
6546   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6547 
6548   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6549 }
6550 
6551 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6552                                     SourceLocation RParenLoc, Expr *E,
6553                                     TypeSourceInfo *TInfo) {
6554   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6555          "Expected paren or paren list expression");
6556 
6557   Expr **exprs;
6558   unsigned numExprs;
6559   Expr *subExpr;
6560   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6561   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6562     LiteralLParenLoc = PE->getLParenLoc();
6563     LiteralRParenLoc = PE->getRParenLoc();
6564     exprs = PE->getExprs();
6565     numExprs = PE->getNumExprs();
6566   } else { // isa<ParenExpr> by assertion at function entrance
6567     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6568     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6569     subExpr = cast<ParenExpr>(E)->getSubExpr();
6570     exprs = &subExpr;
6571     numExprs = 1;
6572   }
6573 
6574   QualType Ty = TInfo->getType();
6575   assert(Ty->isVectorType() && "Expected vector type");
6576 
6577   SmallVector<Expr *, 8> initExprs;
6578   const VectorType *VTy = Ty->getAs<VectorType>();
6579   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6580 
6581   // '(...)' form of vector initialization in AltiVec: the number of
6582   // initializers must be one or must match the size of the vector.
6583   // If a single value is specified in the initializer then it will be
6584   // replicated to all the components of the vector
6585   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6586     // The number of initializers must be one or must match the size of the
6587     // vector. If a single value is specified in the initializer then it will
6588     // be replicated to all the components of the vector
6589     if (numExprs == 1) {
6590       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6591       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6592       if (Literal.isInvalid())
6593         return ExprError();
6594       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6595                                   PrepareScalarCast(Literal, ElemTy));
6596       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6597     }
6598     else if (numExprs < numElems) {
6599       Diag(E->getExprLoc(),
6600            diag::err_incorrect_number_of_vector_initializers);
6601       return ExprError();
6602     }
6603     else
6604       initExprs.append(exprs, exprs + numExprs);
6605   }
6606   else {
6607     // For OpenCL, when the number of initializers is a single value,
6608     // it will be replicated to all components of the vector.
6609     if (getLangOpts().OpenCL &&
6610         VTy->getVectorKind() == VectorType::GenericVector &&
6611         numExprs == 1) {
6612         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6613         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6614         if (Literal.isInvalid())
6615           return ExprError();
6616         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6617                                     PrepareScalarCast(Literal, ElemTy));
6618         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6619     }
6620 
6621     initExprs.append(exprs, exprs + numExprs);
6622   }
6623   // FIXME: This means that pretty-printing the final AST will produce curly
6624   // braces instead of the original commas.
6625   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6626                                                    initExprs, LiteralRParenLoc);
6627   initE->setType(Ty);
6628   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6629 }
6630 
6631 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6632 /// the ParenListExpr into a sequence of comma binary operators.
6633 ExprResult
6634 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6635   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6636   if (!E)
6637     return OrigExpr;
6638 
6639   ExprResult Result(E->getExpr(0));
6640 
6641   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6642     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6643                         E->getExpr(i));
6644 
6645   if (Result.isInvalid()) return ExprError();
6646 
6647   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6648 }
6649 
6650 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6651                                     SourceLocation R,
6652                                     MultiExprArg Val) {
6653   return ParenListExpr::Create(Context, L, Val, R);
6654 }
6655 
6656 /// Emit a specialized diagnostic when one expression is a null pointer
6657 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6658 /// emitted.
6659 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6660                                       SourceLocation QuestionLoc) {
6661   Expr *NullExpr = LHSExpr;
6662   Expr *NonPointerExpr = RHSExpr;
6663   Expr::NullPointerConstantKind NullKind =
6664       NullExpr->isNullPointerConstant(Context,
6665                                       Expr::NPC_ValueDependentIsNotNull);
6666 
6667   if (NullKind == Expr::NPCK_NotNull) {
6668     NullExpr = RHSExpr;
6669     NonPointerExpr = LHSExpr;
6670     NullKind =
6671         NullExpr->isNullPointerConstant(Context,
6672                                         Expr::NPC_ValueDependentIsNotNull);
6673   }
6674 
6675   if (NullKind == Expr::NPCK_NotNull)
6676     return false;
6677 
6678   if (NullKind == Expr::NPCK_ZeroExpression)
6679     return false;
6680 
6681   if (NullKind == Expr::NPCK_ZeroLiteral) {
6682     // In this case, check to make sure that we got here from a "NULL"
6683     // string in the source code.
6684     NullExpr = NullExpr->IgnoreParenImpCasts();
6685     SourceLocation loc = NullExpr->getExprLoc();
6686     if (!findMacroSpelling(loc, "NULL"))
6687       return false;
6688   }
6689 
6690   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6691   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6692       << NonPointerExpr->getType() << DiagType
6693       << NonPointerExpr->getSourceRange();
6694   return true;
6695 }
6696 
6697 /// Return false if the condition expression is valid, true otherwise.
6698 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6699   QualType CondTy = Cond->getType();
6700 
6701   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6702   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6703     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6704       << CondTy << Cond->getSourceRange();
6705     return true;
6706   }
6707 
6708   // C99 6.5.15p2
6709   if (CondTy->isScalarType()) return false;
6710 
6711   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6712     << CondTy << Cond->getSourceRange();
6713   return true;
6714 }
6715 
6716 /// Handle when one or both operands are void type.
6717 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6718                                          ExprResult &RHS) {
6719     Expr *LHSExpr = LHS.get();
6720     Expr *RHSExpr = RHS.get();
6721 
6722     if (!LHSExpr->getType()->isVoidType())
6723       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6724           << RHSExpr->getSourceRange();
6725     if (!RHSExpr->getType()->isVoidType())
6726       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6727           << LHSExpr->getSourceRange();
6728     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6729     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6730     return S.Context.VoidTy;
6731 }
6732 
6733 /// Return false if the NullExpr can be promoted to PointerTy,
6734 /// true otherwise.
6735 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6736                                         QualType PointerTy) {
6737   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6738       !NullExpr.get()->isNullPointerConstant(S.Context,
6739                                             Expr::NPC_ValueDependentIsNull))
6740     return true;
6741 
6742   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6743   return false;
6744 }
6745 
6746 /// Checks compatibility between two pointers and return the resulting
6747 /// type.
6748 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6749                                                      ExprResult &RHS,
6750                                                      SourceLocation Loc) {
6751   QualType LHSTy = LHS.get()->getType();
6752   QualType RHSTy = RHS.get()->getType();
6753 
6754   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6755     // Two identical pointers types are always compatible.
6756     return LHSTy;
6757   }
6758 
6759   QualType lhptee, rhptee;
6760 
6761   // Get the pointee types.
6762   bool IsBlockPointer = false;
6763   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6764     lhptee = LHSBTy->getPointeeType();
6765     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6766     IsBlockPointer = true;
6767   } else {
6768     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6769     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6770   }
6771 
6772   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6773   // differently qualified versions of compatible types, the result type is
6774   // a pointer to an appropriately qualified version of the composite
6775   // type.
6776 
6777   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6778   // clause doesn't make sense for our extensions. E.g. address space 2 should
6779   // be incompatible with address space 3: they may live on different devices or
6780   // anything.
6781   Qualifiers lhQual = lhptee.getQualifiers();
6782   Qualifiers rhQual = rhptee.getQualifiers();
6783 
6784   LangAS ResultAddrSpace = LangAS::Default;
6785   LangAS LAddrSpace = lhQual.getAddressSpace();
6786   LangAS RAddrSpace = rhQual.getAddressSpace();
6787 
6788   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6789   // spaces is disallowed.
6790   if (lhQual.isAddressSpaceSupersetOf(rhQual))
6791     ResultAddrSpace = LAddrSpace;
6792   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6793     ResultAddrSpace = RAddrSpace;
6794   else {
6795     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6796         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6797         << RHS.get()->getSourceRange();
6798     return QualType();
6799   }
6800 
6801   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6802   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6803   lhQual.removeCVRQualifiers();
6804   rhQual.removeCVRQualifiers();
6805 
6806   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6807   // (C99 6.7.3) for address spaces. We assume that the check should behave in
6808   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6809   // qual types are compatible iff
6810   //  * corresponded types are compatible
6811   //  * CVR qualifiers are equal
6812   //  * address spaces are equal
6813   // Thus for conditional operator we merge CVR and address space unqualified
6814   // pointees and if there is a composite type we return a pointer to it with
6815   // merged qualifiers.
6816   LHSCastKind =
6817       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6818   RHSCastKind =
6819       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6820   lhQual.removeAddressSpace();
6821   rhQual.removeAddressSpace();
6822 
6823   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6824   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6825 
6826   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6827 
6828   if (CompositeTy.isNull()) {
6829     // In this situation, we assume void* type. No especially good
6830     // reason, but this is what gcc does, and we do have to pick
6831     // to get a consistent AST.
6832     QualType incompatTy;
6833     incompatTy = S.Context.getPointerType(
6834         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6835     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6836     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6837 
6838     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6839     // for casts between types with incompatible address space qualifiers.
6840     // For the following code the compiler produces casts between global and
6841     // local address spaces of the corresponded innermost pointees:
6842     // local int *global *a;
6843     // global int *global *b;
6844     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6845     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6846         << LHSTy << RHSTy << LHS.get()->getSourceRange()
6847         << RHS.get()->getSourceRange();
6848 
6849     return incompatTy;
6850   }
6851 
6852   // The pointer types are compatible.
6853   // In case of OpenCL ResultTy should have the address space qualifier
6854   // which is a superset of address spaces of both the 2nd and the 3rd
6855   // operands of the conditional operator.
6856   QualType ResultTy = [&, ResultAddrSpace]() {
6857     if (S.getLangOpts().OpenCL) {
6858       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6859       CompositeQuals.setAddressSpace(ResultAddrSpace);
6860       return S.Context
6861           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6862           .withCVRQualifiers(MergedCVRQual);
6863     }
6864     return CompositeTy.withCVRQualifiers(MergedCVRQual);
6865   }();
6866   if (IsBlockPointer)
6867     ResultTy = S.Context.getBlockPointerType(ResultTy);
6868   else
6869     ResultTy = S.Context.getPointerType(ResultTy);
6870 
6871   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6872   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6873   return ResultTy;
6874 }
6875 
6876 /// Return the resulting type when the operands are both block pointers.
6877 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6878                                                           ExprResult &LHS,
6879                                                           ExprResult &RHS,
6880                                                           SourceLocation Loc) {
6881   QualType LHSTy = LHS.get()->getType();
6882   QualType RHSTy = RHS.get()->getType();
6883 
6884   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6885     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6886       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6887       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6888       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6889       return destType;
6890     }
6891     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6892       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6893       << RHS.get()->getSourceRange();
6894     return QualType();
6895   }
6896 
6897   // We have 2 block pointer types.
6898   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6899 }
6900 
6901 /// Return the resulting type when the operands are both pointers.
6902 static QualType
6903 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6904                                             ExprResult &RHS,
6905                                             SourceLocation Loc) {
6906   // get the pointer types
6907   QualType LHSTy = LHS.get()->getType();
6908   QualType RHSTy = RHS.get()->getType();
6909 
6910   // get the "pointed to" types
6911   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6912   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6913 
6914   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6915   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6916     // Figure out necessary qualifiers (C99 6.5.15p6)
6917     QualType destPointee
6918       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6919     QualType destType = S.Context.getPointerType(destPointee);
6920     // Add qualifiers if necessary.
6921     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6922     // Promote to void*.
6923     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6924     return destType;
6925   }
6926   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6927     QualType destPointee
6928       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6929     QualType destType = S.Context.getPointerType(destPointee);
6930     // Add qualifiers if necessary.
6931     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6932     // Promote to void*.
6933     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6934     return destType;
6935   }
6936 
6937   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6938 }
6939 
6940 /// Return false if the first expression is not an integer and the second
6941 /// expression is not a pointer, true otherwise.
6942 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6943                                         Expr* PointerExpr, SourceLocation Loc,
6944                                         bool IsIntFirstExpr) {
6945   if (!PointerExpr->getType()->isPointerType() ||
6946       !Int.get()->getType()->isIntegerType())
6947     return false;
6948 
6949   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6950   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6951 
6952   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6953     << Expr1->getType() << Expr2->getType()
6954     << Expr1->getSourceRange() << Expr2->getSourceRange();
6955   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6956                             CK_IntegralToPointer);
6957   return true;
6958 }
6959 
6960 /// Simple conversion between integer and floating point types.
6961 ///
6962 /// Used when handling the OpenCL conditional operator where the
6963 /// condition is a vector while the other operands are scalar.
6964 ///
6965 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6966 /// types are either integer or floating type. Between the two
6967 /// operands, the type with the higher rank is defined as the "result
6968 /// type". The other operand needs to be promoted to the same type. No
6969 /// other type promotion is allowed. We cannot use
6970 /// UsualArithmeticConversions() for this purpose, since it always
6971 /// promotes promotable types.
6972 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6973                                             ExprResult &RHS,
6974                                             SourceLocation QuestionLoc) {
6975   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6976   if (LHS.isInvalid())
6977     return QualType();
6978   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6979   if (RHS.isInvalid())
6980     return QualType();
6981 
6982   // For conversion purposes, we ignore any qualifiers.
6983   // For example, "const float" and "float" are equivalent.
6984   QualType LHSType =
6985     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6986   QualType RHSType =
6987     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6988 
6989   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6990     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6991       << LHSType << LHS.get()->getSourceRange();
6992     return QualType();
6993   }
6994 
6995   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6996     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6997       << RHSType << RHS.get()->getSourceRange();
6998     return QualType();
6999   }
7000 
7001   // If both types are identical, no conversion is needed.
7002   if (LHSType == RHSType)
7003     return LHSType;
7004 
7005   // Now handle "real" floating types (i.e. float, double, long double).
7006   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
7007     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
7008                                  /*IsCompAssign = */ false);
7009 
7010   // Finally, we have two differing integer types.
7011   return handleIntegerConversion<doIntegralCast, doIntegralCast>
7012   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
7013 }
7014 
7015 /// Convert scalar operands to a vector that matches the
7016 ///        condition in length.
7017 ///
7018 /// Used when handling the OpenCL conditional operator where the
7019 /// condition is a vector while the other operands are scalar.
7020 ///
7021 /// We first compute the "result type" for the scalar operands
7022 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7023 /// into a vector of that type where the length matches the condition
7024 /// vector type. s6.11.6 requires that the element types of the result
7025 /// and the condition must have the same number of bits.
7026 static QualType
7027 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7028                               QualType CondTy, SourceLocation QuestionLoc) {
7029   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7030   if (ResTy.isNull()) return QualType();
7031 
7032   const VectorType *CV = CondTy->getAs<VectorType>();
7033   assert(CV);
7034 
7035   // Determine the vector result type
7036   unsigned NumElements = CV->getNumElements();
7037   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7038 
7039   // Ensure that all types have the same number of bits
7040   if (S.Context.getTypeSize(CV->getElementType())
7041       != S.Context.getTypeSize(ResTy)) {
7042     // Since VectorTy is created internally, it does not pretty print
7043     // with an OpenCL name. Instead, we just print a description.
7044     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7045     SmallString<64> Str;
7046     llvm::raw_svector_ostream OS(Str);
7047     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7048     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7049       << CondTy << OS.str();
7050     return QualType();
7051   }
7052 
7053   // Convert operands to the vector result type
7054   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7055   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7056 
7057   return VectorTy;
7058 }
7059 
7060 /// Return false if this is a valid OpenCL condition vector
7061 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
7062                                        SourceLocation QuestionLoc) {
7063   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
7064   // integral type.
7065   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
7066   assert(CondTy);
7067   QualType EleTy = CondTy->getElementType();
7068   if (EleTy->isIntegerType()) return false;
7069 
7070   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7071     << Cond->getType() << Cond->getSourceRange();
7072   return true;
7073 }
7074 
7075 /// Return false if the vector condition type and the vector
7076 ///        result type are compatible.
7077 ///
7078 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
7079 /// number of elements, and their element types have the same number
7080 /// of bits.
7081 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
7082                               SourceLocation QuestionLoc) {
7083   const VectorType *CV = CondTy->getAs<VectorType>();
7084   const VectorType *RV = VecResTy->getAs<VectorType>();
7085   assert(CV && RV);
7086 
7087   if (CV->getNumElements() != RV->getNumElements()) {
7088     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
7089       << CondTy << VecResTy;
7090     return true;
7091   }
7092 
7093   QualType CVE = CV->getElementType();
7094   QualType RVE = RV->getElementType();
7095 
7096   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
7097     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7098       << CondTy << VecResTy;
7099     return true;
7100   }
7101 
7102   return false;
7103 }
7104 
7105 /// Return the resulting type for the conditional operator in
7106 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
7107 ///        s6.3.i) when the condition is a vector type.
7108 static QualType
7109 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
7110                              ExprResult &LHS, ExprResult &RHS,
7111                              SourceLocation QuestionLoc) {
7112   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
7113   if (Cond.isInvalid())
7114     return QualType();
7115   QualType CondTy = Cond.get()->getType();
7116 
7117   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
7118     return QualType();
7119 
7120   // If either operand is a vector then find the vector type of the
7121   // result as specified in OpenCL v1.1 s6.3.i.
7122   if (LHS.get()->getType()->isVectorType() ||
7123       RHS.get()->getType()->isVectorType()) {
7124     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
7125                                               /*isCompAssign*/false,
7126                                               /*AllowBothBool*/true,
7127                                               /*AllowBoolConversions*/false);
7128     if (VecResTy.isNull()) return QualType();
7129     // The result type must match the condition type as specified in
7130     // OpenCL v1.1 s6.11.6.
7131     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
7132       return QualType();
7133     return VecResTy;
7134   }
7135 
7136   // Both operands are scalar.
7137   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
7138 }
7139 
7140 /// Return true if the Expr is block type
7141 static bool checkBlockType(Sema &S, const Expr *E) {
7142   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7143     QualType Ty = CE->getCallee()->getType();
7144     if (Ty->isBlockPointerType()) {
7145       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
7146       return true;
7147     }
7148   }
7149   return false;
7150 }
7151 
7152 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
7153 /// In that case, LHS = cond.
7154 /// C99 6.5.15
7155 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
7156                                         ExprResult &RHS, ExprValueKind &VK,
7157                                         ExprObjectKind &OK,
7158                                         SourceLocation QuestionLoc) {
7159 
7160   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
7161   if (!LHSResult.isUsable()) return QualType();
7162   LHS = LHSResult;
7163 
7164   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
7165   if (!RHSResult.isUsable()) return QualType();
7166   RHS = RHSResult;
7167 
7168   // C++ is sufficiently different to merit its own checker.
7169   if (getLangOpts().CPlusPlus)
7170     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
7171 
7172   VK = VK_RValue;
7173   OK = OK_Ordinary;
7174 
7175   // The OpenCL operator with a vector condition is sufficiently
7176   // different to merit its own checker.
7177   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
7178     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
7179 
7180   // First, check the condition.
7181   Cond = UsualUnaryConversions(Cond.get());
7182   if (Cond.isInvalid())
7183     return QualType();
7184   if (checkCondition(*this, Cond.get(), QuestionLoc))
7185     return QualType();
7186 
7187   // Now check the two expressions.
7188   if (LHS.get()->getType()->isVectorType() ||
7189       RHS.get()->getType()->isVectorType())
7190     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
7191                                /*AllowBothBool*/true,
7192                                /*AllowBoolConversions*/false);
7193 
7194   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
7195   if (LHS.isInvalid() || RHS.isInvalid())
7196     return QualType();
7197 
7198   QualType LHSTy = LHS.get()->getType();
7199   QualType RHSTy = RHS.get()->getType();
7200 
7201   // Diagnose attempts to convert between __float128 and long double where
7202   // such conversions currently can't be handled.
7203   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
7204     Diag(QuestionLoc,
7205          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
7206       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7207     return QualType();
7208   }
7209 
7210   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
7211   // selection operator (?:).
7212   if (getLangOpts().OpenCL &&
7213       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
7214     return QualType();
7215   }
7216 
7217   // If both operands have arithmetic type, do the usual arithmetic conversions
7218   // to find a common type: C99 6.5.15p3,5.
7219   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
7220     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
7221     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
7222 
7223     return ResTy;
7224   }
7225 
7226   // If both operands are the same structure or union type, the result is that
7227   // type.
7228   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
7229     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
7230       if (LHSRT->getDecl() == RHSRT->getDecl())
7231         // "If both the operands have structure or union type, the result has
7232         // that type."  This implies that CV qualifiers are dropped.
7233         return LHSTy.getUnqualifiedType();
7234     // FIXME: Type of conditional expression must be complete in C mode.
7235   }
7236 
7237   // C99 6.5.15p5: "If both operands have void type, the result has void type."
7238   // The following || allows only one side to be void (a GCC-ism).
7239   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
7240     return checkConditionalVoidType(*this, LHS, RHS);
7241   }
7242 
7243   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
7244   // the type of the other operand."
7245   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
7246   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
7247 
7248   // All objective-c pointer type analysis is done here.
7249   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
7250                                                         QuestionLoc);
7251   if (LHS.isInvalid() || RHS.isInvalid())
7252     return QualType();
7253   if (!compositeType.isNull())
7254     return compositeType;
7255 
7256 
7257   // Handle block pointer types.
7258   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
7259     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
7260                                                      QuestionLoc);
7261 
7262   // Check constraints for C object pointers types (C99 6.5.15p3,6).
7263   if (LHSTy->isPointerType() && RHSTy->isPointerType())
7264     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
7265                                                        QuestionLoc);
7266 
7267   // GCC compatibility: soften pointer/integer mismatch.  Note that
7268   // null pointers have been filtered out by this point.
7269   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
7270       /*isIntFirstExpr=*/true))
7271     return RHSTy;
7272   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
7273       /*isIntFirstExpr=*/false))
7274     return LHSTy;
7275 
7276   // Emit a better diagnostic if one of the expressions is a null pointer
7277   // constant and the other is not a pointer type. In this case, the user most
7278   // likely forgot to take the address of the other expression.
7279   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
7280     return QualType();
7281 
7282   // Otherwise, the operands are not compatible.
7283   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
7284     << LHSTy << RHSTy << LHS.get()->getSourceRange()
7285     << RHS.get()->getSourceRange();
7286   return QualType();
7287 }
7288 
7289 /// FindCompositeObjCPointerType - Helper method to find composite type of
7290 /// two objective-c pointer types of the two input expressions.
7291 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
7292                                             SourceLocation QuestionLoc) {
7293   QualType LHSTy = LHS.get()->getType();
7294   QualType RHSTy = RHS.get()->getType();
7295 
7296   // Handle things like Class and struct objc_class*.  Here we case the result
7297   // to the pseudo-builtin, because that will be implicitly cast back to the
7298   // redefinition type if an attempt is made to access its fields.
7299   if (LHSTy->isObjCClassType() &&
7300       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
7301     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7302     return LHSTy;
7303   }
7304   if (RHSTy->isObjCClassType() &&
7305       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
7306     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7307     return RHSTy;
7308   }
7309   // And the same for struct objc_object* / id
7310   if (LHSTy->isObjCIdType() &&
7311       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
7312     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7313     return LHSTy;
7314   }
7315   if (RHSTy->isObjCIdType() &&
7316       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
7317     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7318     return RHSTy;
7319   }
7320   // And the same for struct objc_selector* / SEL
7321   if (Context.isObjCSelType(LHSTy) &&
7322       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
7323     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
7324     return LHSTy;
7325   }
7326   if (Context.isObjCSelType(RHSTy) &&
7327       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
7328     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
7329     return RHSTy;
7330   }
7331   // Check constraints for Objective-C object pointers types.
7332   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
7333 
7334     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
7335       // Two identical object pointer types are always compatible.
7336       return LHSTy;
7337     }
7338     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
7339     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
7340     QualType compositeType = LHSTy;
7341 
7342     // If both operands are interfaces and either operand can be
7343     // assigned to the other, use that type as the composite
7344     // type. This allows
7345     //   xxx ? (A*) a : (B*) b
7346     // where B is a subclass of A.
7347     //
7348     // Additionally, as for assignment, if either type is 'id'
7349     // allow silent coercion. Finally, if the types are
7350     // incompatible then make sure to use 'id' as the composite
7351     // type so the result is acceptable for sending messages to.
7352 
7353     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
7354     // It could return the composite type.
7355     if (!(compositeType =
7356           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
7357       // Nothing more to do.
7358     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
7359       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
7360     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
7361       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
7362     } else if ((LHSTy->isObjCQualifiedIdType() ||
7363                 RHSTy->isObjCQualifiedIdType()) &&
7364                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
7365       // Need to handle "id<xx>" explicitly.
7366       // GCC allows qualified id and any Objective-C type to devolve to
7367       // id. Currently localizing to here until clear this should be
7368       // part of ObjCQualifiedIdTypesAreCompatible.
7369       compositeType = Context.getObjCIdType();
7370     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
7371       compositeType = Context.getObjCIdType();
7372     } else {
7373       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
7374       << LHSTy << RHSTy
7375       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7376       QualType incompatTy = Context.getObjCIdType();
7377       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
7378       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
7379       return incompatTy;
7380     }
7381     // The object pointer types are compatible.
7382     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
7383     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
7384     return compositeType;
7385   }
7386   // Check Objective-C object pointer types and 'void *'
7387   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
7388     if (getLangOpts().ObjCAutoRefCount) {
7389       // ARC forbids the implicit conversion of object pointers to 'void *',
7390       // so these types are not compatible.
7391       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7392           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7393       LHS = RHS = true;
7394       return QualType();
7395     }
7396     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
7397     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7398     QualType destPointee
7399     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7400     QualType destType = Context.getPointerType(destPointee);
7401     // Add qualifiers if necessary.
7402     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7403     // Promote to void*.
7404     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7405     return destType;
7406   }
7407   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
7408     if (getLangOpts().ObjCAutoRefCount) {
7409       // ARC forbids the implicit conversion of object pointers to 'void *',
7410       // so these types are not compatible.
7411       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7412           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7413       LHS = RHS = true;
7414       return QualType();
7415     }
7416     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7417     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
7418     QualType destPointee
7419     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7420     QualType destType = Context.getPointerType(destPointee);
7421     // Add qualifiers if necessary.
7422     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7423     // Promote to void*.
7424     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7425     return destType;
7426   }
7427   return QualType();
7428 }
7429 
7430 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7431 /// ParenRange in parentheses.
7432 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7433                                const PartialDiagnostic &Note,
7434                                SourceRange ParenRange) {
7435   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7436   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7437       EndLoc.isValid()) {
7438     Self.Diag(Loc, Note)
7439       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7440       << FixItHint::CreateInsertion(EndLoc, ")");
7441   } else {
7442     // We can't display the parentheses, so just show the bare note.
7443     Self.Diag(Loc, Note) << ParenRange;
7444   }
7445 }
7446 
7447 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7448   return BinaryOperator::isAdditiveOp(Opc) ||
7449          BinaryOperator::isMultiplicativeOp(Opc) ||
7450          BinaryOperator::isShiftOp(Opc);
7451 }
7452 
7453 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7454 /// expression, either using a built-in or overloaded operator,
7455 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7456 /// expression.
7457 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7458                                    Expr **RHSExprs) {
7459   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7460   E = E->IgnoreImpCasts();
7461   E = E->IgnoreConversionOperator();
7462   E = E->IgnoreImpCasts();
7463   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
7464     E = MTE->GetTemporaryExpr();
7465     E = E->IgnoreImpCasts();
7466   }
7467 
7468   // Built-in binary operator.
7469   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7470     if (IsArithmeticOp(OP->getOpcode())) {
7471       *Opcode = OP->getOpcode();
7472       *RHSExprs = OP->getRHS();
7473       return true;
7474     }
7475   }
7476 
7477   // Overloaded operator.
7478   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7479     if (Call->getNumArgs() != 2)
7480       return false;
7481 
7482     // Make sure this is really a binary operator that is safe to pass into
7483     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7484     OverloadedOperatorKind OO = Call->getOperator();
7485     if (OO < OO_Plus || OO > OO_Arrow ||
7486         OO == OO_PlusPlus || OO == OO_MinusMinus)
7487       return false;
7488 
7489     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7490     if (IsArithmeticOp(OpKind)) {
7491       *Opcode = OpKind;
7492       *RHSExprs = Call->getArg(1);
7493       return true;
7494     }
7495   }
7496 
7497   return false;
7498 }
7499 
7500 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7501 /// or is a logical expression such as (x==y) which has int type, but is
7502 /// commonly interpreted as boolean.
7503 static bool ExprLooksBoolean(Expr *E) {
7504   E = E->IgnoreParenImpCasts();
7505 
7506   if (E->getType()->isBooleanType())
7507     return true;
7508   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7509     return OP->isComparisonOp() || OP->isLogicalOp();
7510   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7511     return OP->getOpcode() == UO_LNot;
7512   if (E->getType()->isPointerType())
7513     return true;
7514   // FIXME: What about overloaded operator calls returning "unspecified boolean
7515   // type"s (commonly pointer-to-members)?
7516 
7517   return false;
7518 }
7519 
7520 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7521 /// and binary operator are mixed in a way that suggests the programmer assumed
7522 /// the conditional operator has higher precedence, for example:
7523 /// "int x = a + someBinaryCondition ? 1 : 2".
7524 static void DiagnoseConditionalPrecedence(Sema &Self,
7525                                           SourceLocation OpLoc,
7526                                           Expr *Condition,
7527                                           Expr *LHSExpr,
7528                                           Expr *RHSExpr) {
7529   BinaryOperatorKind CondOpcode;
7530   Expr *CondRHS;
7531 
7532   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7533     return;
7534   if (!ExprLooksBoolean(CondRHS))
7535     return;
7536 
7537   // The condition is an arithmetic binary expression, with a right-
7538   // hand side that looks boolean, so warn.
7539 
7540   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7541       << Condition->getSourceRange()
7542       << BinaryOperator::getOpcodeStr(CondOpcode);
7543 
7544   SuggestParentheses(
7545       Self, OpLoc,
7546       Self.PDiag(diag::note_precedence_silence)
7547           << BinaryOperator::getOpcodeStr(CondOpcode),
7548       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
7549 
7550   SuggestParentheses(Self, OpLoc,
7551                      Self.PDiag(diag::note_precedence_conditional_first),
7552                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
7553 }
7554 
7555 /// Compute the nullability of a conditional expression.
7556 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7557                                               QualType LHSTy, QualType RHSTy,
7558                                               ASTContext &Ctx) {
7559   if (!ResTy->isAnyPointerType())
7560     return ResTy;
7561 
7562   auto GetNullability = [&Ctx](QualType Ty) {
7563     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7564     if (Kind)
7565       return *Kind;
7566     return NullabilityKind::Unspecified;
7567   };
7568 
7569   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7570   NullabilityKind MergedKind;
7571 
7572   // Compute nullability of a binary conditional expression.
7573   if (IsBin) {
7574     if (LHSKind == NullabilityKind::NonNull)
7575       MergedKind = NullabilityKind::NonNull;
7576     else
7577       MergedKind = RHSKind;
7578   // Compute nullability of a normal conditional expression.
7579   } else {
7580     if (LHSKind == NullabilityKind::Nullable ||
7581         RHSKind == NullabilityKind::Nullable)
7582       MergedKind = NullabilityKind::Nullable;
7583     else if (LHSKind == NullabilityKind::NonNull)
7584       MergedKind = RHSKind;
7585     else if (RHSKind == NullabilityKind::NonNull)
7586       MergedKind = LHSKind;
7587     else
7588       MergedKind = NullabilityKind::Unspecified;
7589   }
7590 
7591   // Return if ResTy already has the correct nullability.
7592   if (GetNullability(ResTy) == MergedKind)
7593     return ResTy;
7594 
7595   // Strip all nullability from ResTy.
7596   while (ResTy->getNullability(Ctx))
7597     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7598 
7599   // Create a new AttributedType with the new nullability kind.
7600   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7601   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7602 }
7603 
7604 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7605 /// in the case of a the GNU conditional expr extension.
7606 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7607                                     SourceLocation ColonLoc,
7608                                     Expr *CondExpr, Expr *LHSExpr,
7609                                     Expr *RHSExpr) {
7610   if (!getLangOpts().CPlusPlus) {
7611     // C cannot handle TypoExpr nodes in the condition because it
7612     // doesn't handle dependent types properly, so make sure any TypoExprs have
7613     // been dealt with before checking the operands.
7614     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7615     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7616     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7617 
7618     if (!CondResult.isUsable())
7619       return ExprError();
7620 
7621     if (LHSExpr) {
7622       if (!LHSResult.isUsable())
7623         return ExprError();
7624     }
7625 
7626     if (!RHSResult.isUsable())
7627       return ExprError();
7628 
7629     CondExpr = CondResult.get();
7630     LHSExpr = LHSResult.get();
7631     RHSExpr = RHSResult.get();
7632   }
7633 
7634   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7635   // was the condition.
7636   OpaqueValueExpr *opaqueValue = nullptr;
7637   Expr *commonExpr = nullptr;
7638   if (!LHSExpr) {
7639     commonExpr = CondExpr;
7640     // Lower out placeholder types first.  This is important so that we don't
7641     // try to capture a placeholder. This happens in few cases in C++; such
7642     // as Objective-C++'s dictionary subscripting syntax.
7643     if (commonExpr->hasPlaceholderType()) {
7644       ExprResult result = CheckPlaceholderExpr(commonExpr);
7645       if (!result.isUsable()) return ExprError();
7646       commonExpr = result.get();
7647     }
7648     // We usually want to apply unary conversions *before* saving, except
7649     // in the special case of a C++ l-value conditional.
7650     if (!(getLangOpts().CPlusPlus
7651           && !commonExpr->isTypeDependent()
7652           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7653           && commonExpr->isGLValue()
7654           && commonExpr->isOrdinaryOrBitFieldObject()
7655           && RHSExpr->isOrdinaryOrBitFieldObject()
7656           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7657       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7658       if (commonRes.isInvalid())
7659         return ExprError();
7660       commonExpr = commonRes.get();
7661     }
7662 
7663     // If the common expression is a class or array prvalue, materialize it
7664     // so that we can safely refer to it multiple times.
7665     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
7666                                    commonExpr->getType()->isArrayType())) {
7667       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
7668       if (MatExpr.isInvalid())
7669         return ExprError();
7670       commonExpr = MatExpr.get();
7671     }
7672 
7673     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7674                                                 commonExpr->getType(),
7675                                                 commonExpr->getValueKind(),
7676                                                 commonExpr->getObjectKind(),
7677                                                 commonExpr);
7678     LHSExpr = CondExpr = opaqueValue;
7679   }
7680 
7681   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7682   ExprValueKind VK = VK_RValue;
7683   ExprObjectKind OK = OK_Ordinary;
7684   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7685   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7686                                              VK, OK, QuestionLoc);
7687   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7688       RHS.isInvalid())
7689     return ExprError();
7690 
7691   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7692                                 RHS.get());
7693 
7694   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7695 
7696   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7697                                          Context);
7698 
7699   if (!commonExpr)
7700     return new (Context)
7701         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7702                             RHS.get(), result, VK, OK);
7703 
7704   return new (Context) BinaryConditionalOperator(
7705       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7706       ColonLoc, result, VK, OK);
7707 }
7708 
7709 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7710 // being closely modeled after the C99 spec:-). The odd characteristic of this
7711 // routine is it effectively iqnores the qualifiers on the top level pointee.
7712 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7713 // FIXME: add a couple examples in this comment.
7714 static Sema::AssignConvertType
7715 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7716   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7717   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7718 
7719   // get the "pointed to" type (ignoring qualifiers at the top level)
7720   const Type *lhptee, *rhptee;
7721   Qualifiers lhq, rhq;
7722   std::tie(lhptee, lhq) =
7723       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7724   std::tie(rhptee, rhq) =
7725       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7726 
7727   Sema::AssignConvertType ConvTy = Sema::Compatible;
7728 
7729   // C99 6.5.16.1p1: This following citation is common to constraints
7730   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7731   // qualifiers of the type *pointed to* by the right;
7732 
7733   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7734   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7735       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7736     // Ignore lifetime for further calculation.
7737     lhq.removeObjCLifetime();
7738     rhq.removeObjCLifetime();
7739   }
7740 
7741   if (!lhq.compatiblyIncludes(rhq)) {
7742     // Treat address-space mismatches as fatal.
7743     if (!lhq.isAddressSpaceSupersetOf(rhq))
7744       return Sema::IncompatiblePointerDiscardsQualifiers;
7745 
7746     // It's okay to add or remove GC or lifetime qualifiers when converting to
7747     // and from void*.
7748     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7749                         .compatiblyIncludes(
7750                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7751              && (lhptee->isVoidType() || rhptee->isVoidType()))
7752       ; // keep old
7753 
7754     // Treat lifetime mismatches as fatal.
7755     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7756       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7757 
7758     // For GCC/MS compatibility, other qualifier mismatches are treated
7759     // as still compatible in C.
7760     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7761   }
7762 
7763   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7764   // incomplete type and the other is a pointer to a qualified or unqualified
7765   // version of void...
7766   if (lhptee->isVoidType()) {
7767     if (rhptee->isIncompleteOrObjectType())
7768       return ConvTy;
7769 
7770     // As an extension, we allow cast to/from void* to function pointer.
7771     assert(rhptee->isFunctionType());
7772     return Sema::FunctionVoidPointer;
7773   }
7774 
7775   if (rhptee->isVoidType()) {
7776     if (lhptee->isIncompleteOrObjectType())
7777       return ConvTy;
7778 
7779     // As an extension, we allow cast to/from void* to function pointer.
7780     assert(lhptee->isFunctionType());
7781     return Sema::FunctionVoidPointer;
7782   }
7783 
7784   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7785   // unqualified versions of compatible types, ...
7786   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7787   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7788     // Check if the pointee types are compatible ignoring the sign.
7789     // We explicitly check for char so that we catch "char" vs
7790     // "unsigned char" on systems where "char" is unsigned.
7791     if (lhptee->isCharType())
7792       ltrans = S.Context.UnsignedCharTy;
7793     else if (lhptee->hasSignedIntegerRepresentation())
7794       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7795 
7796     if (rhptee->isCharType())
7797       rtrans = S.Context.UnsignedCharTy;
7798     else if (rhptee->hasSignedIntegerRepresentation())
7799       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7800 
7801     if (ltrans == rtrans) {
7802       // Types are compatible ignoring the sign. Qualifier incompatibility
7803       // takes priority over sign incompatibility because the sign
7804       // warning can be disabled.
7805       if (ConvTy != Sema::Compatible)
7806         return ConvTy;
7807 
7808       return Sema::IncompatiblePointerSign;
7809     }
7810 
7811     // If we are a multi-level pointer, it's possible that our issue is simply
7812     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7813     // the eventual target type is the same and the pointers have the same
7814     // level of indirection, this must be the issue.
7815     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7816       do {
7817         std::tie(lhptee, lhq) =
7818           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
7819         std::tie(rhptee, rhq) =
7820           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
7821 
7822         // Inconsistent address spaces at this point is invalid, even if the
7823         // address spaces would be compatible.
7824         // FIXME: This doesn't catch address space mismatches for pointers of
7825         // different nesting levels, like:
7826         //   __local int *** a;
7827         //   int ** b = a;
7828         // It's not clear how to actually determine when such pointers are
7829         // invalidly incompatible.
7830         if (lhq.getAddressSpace() != rhq.getAddressSpace())
7831           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
7832 
7833       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7834 
7835       if (lhptee == rhptee)
7836         return Sema::IncompatibleNestedPointerQualifiers;
7837     }
7838 
7839     // General pointer incompatibility takes priority over qualifiers.
7840     return Sema::IncompatiblePointer;
7841   }
7842   if (!S.getLangOpts().CPlusPlus &&
7843       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7844     return Sema::IncompatiblePointer;
7845   return ConvTy;
7846 }
7847 
7848 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7849 /// block pointer types are compatible or whether a block and normal pointer
7850 /// are compatible. It is more restrict than comparing two function pointer
7851 // types.
7852 static Sema::AssignConvertType
7853 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7854                                     QualType RHSType) {
7855   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7856   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7857 
7858   QualType lhptee, rhptee;
7859 
7860   // get the "pointed to" type (ignoring qualifiers at the top level)
7861   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7862   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7863 
7864   // In C++, the types have to match exactly.
7865   if (S.getLangOpts().CPlusPlus)
7866     return Sema::IncompatibleBlockPointer;
7867 
7868   Sema::AssignConvertType ConvTy = Sema::Compatible;
7869 
7870   // For blocks we enforce that qualifiers are identical.
7871   Qualifiers LQuals = lhptee.getLocalQualifiers();
7872   Qualifiers RQuals = rhptee.getLocalQualifiers();
7873   if (S.getLangOpts().OpenCL) {
7874     LQuals.removeAddressSpace();
7875     RQuals.removeAddressSpace();
7876   }
7877   if (LQuals != RQuals)
7878     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7879 
7880   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7881   // assignment.
7882   // The current behavior is similar to C++ lambdas. A block might be
7883   // assigned to a variable iff its return type and parameters are compatible
7884   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7885   // an assignment. Presumably it should behave in way that a function pointer
7886   // assignment does in C, so for each parameter and return type:
7887   //  * CVR and address space of LHS should be a superset of CVR and address
7888   //  space of RHS.
7889   //  * unqualified types should be compatible.
7890   if (S.getLangOpts().OpenCL) {
7891     if (!S.Context.typesAreBlockPointerCompatible(
7892             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7893             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7894       return Sema::IncompatibleBlockPointer;
7895   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7896     return Sema::IncompatibleBlockPointer;
7897 
7898   return ConvTy;
7899 }
7900 
7901 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7902 /// for assignment compatibility.
7903 static Sema::AssignConvertType
7904 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7905                                    QualType RHSType) {
7906   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7907   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7908 
7909   if (LHSType->isObjCBuiltinType()) {
7910     // Class is not compatible with ObjC object pointers.
7911     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7912         !RHSType->isObjCQualifiedClassType())
7913       return Sema::IncompatiblePointer;
7914     return Sema::Compatible;
7915   }
7916   if (RHSType->isObjCBuiltinType()) {
7917     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7918         !LHSType->isObjCQualifiedClassType())
7919       return Sema::IncompatiblePointer;
7920     return Sema::Compatible;
7921   }
7922   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7923   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7924 
7925   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7926       // make an exception for id<P>
7927       !LHSType->isObjCQualifiedIdType())
7928     return Sema::CompatiblePointerDiscardsQualifiers;
7929 
7930   if (S.Context.typesAreCompatible(LHSType, RHSType))
7931     return Sema::Compatible;
7932   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7933     return Sema::IncompatibleObjCQualifiedId;
7934   return Sema::IncompatiblePointer;
7935 }
7936 
7937 Sema::AssignConvertType
7938 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7939                                  QualType LHSType, QualType RHSType) {
7940   // Fake up an opaque expression.  We don't actually care about what
7941   // cast operations are required, so if CheckAssignmentConstraints
7942   // adds casts to this they'll be wasted, but fortunately that doesn't
7943   // usually happen on valid code.
7944   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7945   ExprResult RHSPtr = &RHSExpr;
7946   CastKind K;
7947 
7948   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7949 }
7950 
7951 /// This helper function returns true if QT is a vector type that has element
7952 /// type ElementType.
7953 static bool isVector(QualType QT, QualType ElementType) {
7954   if (const VectorType *VT = QT->getAs<VectorType>())
7955     return VT->getElementType() == ElementType;
7956   return false;
7957 }
7958 
7959 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7960 /// has code to accommodate several GCC extensions when type checking
7961 /// pointers. Here are some objectionable examples that GCC considers warnings:
7962 ///
7963 ///  int a, *pint;
7964 ///  short *pshort;
7965 ///  struct foo *pfoo;
7966 ///
7967 ///  pint = pshort; // warning: assignment from incompatible pointer type
7968 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7969 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7970 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7971 ///
7972 /// As a result, the code for dealing with pointers is more complex than the
7973 /// C99 spec dictates.
7974 ///
7975 /// Sets 'Kind' for any result kind except Incompatible.
7976 Sema::AssignConvertType
7977 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7978                                  CastKind &Kind, bool ConvertRHS) {
7979   QualType RHSType = RHS.get()->getType();
7980   QualType OrigLHSType = LHSType;
7981 
7982   // Get canonical types.  We're not formatting these types, just comparing
7983   // them.
7984   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7985   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7986 
7987   // Common case: no conversion required.
7988   if (LHSType == RHSType) {
7989     Kind = CK_NoOp;
7990     return Compatible;
7991   }
7992 
7993   // If we have an atomic type, try a non-atomic assignment, then just add an
7994   // atomic qualification step.
7995   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7996     Sema::AssignConvertType result =
7997       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7998     if (result != Compatible)
7999       return result;
8000     if (Kind != CK_NoOp && ConvertRHS)
8001       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
8002     Kind = CK_NonAtomicToAtomic;
8003     return Compatible;
8004   }
8005 
8006   // If the left-hand side is a reference type, then we are in a
8007   // (rare!) case where we've allowed the use of references in C,
8008   // e.g., as a parameter type in a built-in function. In this case,
8009   // just make sure that the type referenced is compatible with the
8010   // right-hand side type. The caller is responsible for adjusting
8011   // LHSType so that the resulting expression does not have reference
8012   // type.
8013   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
8014     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
8015       Kind = CK_LValueBitCast;
8016       return Compatible;
8017     }
8018     return Incompatible;
8019   }
8020 
8021   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
8022   // to the same ExtVector type.
8023   if (LHSType->isExtVectorType()) {
8024     if (RHSType->isExtVectorType())
8025       return Incompatible;
8026     if (RHSType->isArithmeticType()) {
8027       // CK_VectorSplat does T -> vector T, so first cast to the element type.
8028       if (ConvertRHS)
8029         RHS = prepareVectorSplat(LHSType, RHS.get());
8030       Kind = CK_VectorSplat;
8031       return Compatible;
8032     }
8033   }
8034 
8035   // Conversions to or from vector type.
8036   if (LHSType->isVectorType() || RHSType->isVectorType()) {
8037     if (LHSType->isVectorType() && RHSType->isVectorType()) {
8038       // Allow assignments of an AltiVec vector type to an equivalent GCC
8039       // vector type and vice versa
8040       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8041         Kind = CK_BitCast;
8042         return Compatible;
8043       }
8044 
8045       // If we are allowing lax vector conversions, and LHS and RHS are both
8046       // vectors, the total size only needs to be the same. This is a bitcast;
8047       // no bits are changed but the result type is different.
8048       if (isLaxVectorConversion(RHSType, LHSType)) {
8049         Kind = CK_BitCast;
8050         return IncompatibleVectors;
8051       }
8052     }
8053 
8054     // When the RHS comes from another lax conversion (e.g. binops between
8055     // scalars and vectors) the result is canonicalized as a vector. When the
8056     // LHS is also a vector, the lax is allowed by the condition above. Handle
8057     // the case where LHS is a scalar.
8058     if (LHSType->isScalarType()) {
8059       const VectorType *VecType = RHSType->getAs<VectorType>();
8060       if (VecType && VecType->getNumElements() == 1 &&
8061           isLaxVectorConversion(RHSType, LHSType)) {
8062         ExprResult *VecExpr = &RHS;
8063         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
8064         Kind = CK_BitCast;
8065         return Compatible;
8066       }
8067     }
8068 
8069     return Incompatible;
8070   }
8071 
8072   // Diagnose attempts to convert between __float128 and long double where
8073   // such conversions currently can't be handled.
8074   if (unsupportedTypeConversion(*this, LHSType, RHSType))
8075     return Incompatible;
8076 
8077   // Disallow assigning a _Complex to a real type in C++ mode since it simply
8078   // discards the imaginary part.
8079   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
8080       !LHSType->getAs<ComplexType>())
8081     return Incompatible;
8082 
8083   // Arithmetic conversions.
8084   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
8085       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
8086     if (ConvertRHS)
8087       Kind = PrepareScalarCast(RHS, LHSType);
8088     return Compatible;
8089   }
8090 
8091   // Conversions to normal pointers.
8092   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
8093     // U* -> T*
8094     if (isa<PointerType>(RHSType)) {
8095       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8096       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
8097       if (AddrSpaceL != AddrSpaceR)
8098         Kind = CK_AddressSpaceConversion;
8099       else if (Context.hasCvrSimilarType(RHSType, LHSType))
8100         Kind = CK_NoOp;
8101       else
8102         Kind = CK_BitCast;
8103       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
8104     }
8105 
8106     // int -> T*
8107     if (RHSType->isIntegerType()) {
8108       Kind = CK_IntegralToPointer; // FIXME: null?
8109       return IntToPointer;
8110     }
8111 
8112     // C pointers are not compatible with ObjC object pointers,
8113     // with two exceptions:
8114     if (isa<ObjCObjectPointerType>(RHSType)) {
8115       //  - conversions to void*
8116       if (LHSPointer->getPointeeType()->isVoidType()) {
8117         Kind = CK_BitCast;
8118         return Compatible;
8119       }
8120 
8121       //  - conversions from 'Class' to the redefinition type
8122       if (RHSType->isObjCClassType() &&
8123           Context.hasSameType(LHSType,
8124                               Context.getObjCClassRedefinitionType())) {
8125         Kind = CK_BitCast;
8126         return Compatible;
8127       }
8128 
8129       Kind = CK_BitCast;
8130       return IncompatiblePointer;
8131     }
8132 
8133     // U^ -> void*
8134     if (RHSType->getAs<BlockPointerType>()) {
8135       if (LHSPointer->getPointeeType()->isVoidType()) {
8136         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8137         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8138                                 ->getPointeeType()
8139                                 .getAddressSpace();
8140         Kind =
8141             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8142         return Compatible;
8143       }
8144     }
8145 
8146     return Incompatible;
8147   }
8148 
8149   // Conversions to block pointers.
8150   if (isa<BlockPointerType>(LHSType)) {
8151     // U^ -> T^
8152     if (RHSType->isBlockPointerType()) {
8153       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
8154                               ->getPointeeType()
8155                               .getAddressSpace();
8156       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8157                               ->getPointeeType()
8158                               .getAddressSpace();
8159       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8160       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
8161     }
8162 
8163     // int or null -> T^
8164     if (RHSType->isIntegerType()) {
8165       Kind = CK_IntegralToPointer; // FIXME: null
8166       return IntToBlockPointer;
8167     }
8168 
8169     // id -> T^
8170     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
8171       Kind = CK_AnyPointerToBlockPointerCast;
8172       return Compatible;
8173     }
8174 
8175     // void* -> T^
8176     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
8177       if (RHSPT->getPointeeType()->isVoidType()) {
8178         Kind = CK_AnyPointerToBlockPointerCast;
8179         return Compatible;
8180       }
8181 
8182     return Incompatible;
8183   }
8184 
8185   // Conversions to Objective-C pointers.
8186   if (isa<ObjCObjectPointerType>(LHSType)) {
8187     // A* -> B*
8188     if (RHSType->isObjCObjectPointerType()) {
8189       Kind = CK_BitCast;
8190       Sema::AssignConvertType result =
8191         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
8192       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8193           result == Compatible &&
8194           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
8195         result = IncompatibleObjCWeakRef;
8196       return result;
8197     }
8198 
8199     // int or null -> A*
8200     if (RHSType->isIntegerType()) {
8201       Kind = CK_IntegralToPointer; // FIXME: null
8202       return IntToPointer;
8203     }
8204 
8205     // In general, C pointers are not compatible with ObjC object pointers,
8206     // with two exceptions:
8207     if (isa<PointerType>(RHSType)) {
8208       Kind = CK_CPointerToObjCPointerCast;
8209 
8210       //  - conversions from 'void*'
8211       if (RHSType->isVoidPointerType()) {
8212         return Compatible;
8213       }
8214 
8215       //  - conversions to 'Class' from its redefinition type
8216       if (LHSType->isObjCClassType() &&
8217           Context.hasSameType(RHSType,
8218                               Context.getObjCClassRedefinitionType())) {
8219         return Compatible;
8220       }
8221 
8222       return IncompatiblePointer;
8223     }
8224 
8225     // Only under strict condition T^ is compatible with an Objective-C pointer.
8226     if (RHSType->isBlockPointerType() &&
8227         LHSType->isBlockCompatibleObjCPointerType(Context)) {
8228       if (ConvertRHS)
8229         maybeExtendBlockObject(RHS);
8230       Kind = CK_BlockPointerToObjCPointerCast;
8231       return Compatible;
8232     }
8233 
8234     return Incompatible;
8235   }
8236 
8237   // Conversions from pointers that are not covered by the above.
8238   if (isa<PointerType>(RHSType)) {
8239     // T* -> _Bool
8240     if (LHSType == Context.BoolTy) {
8241       Kind = CK_PointerToBoolean;
8242       return Compatible;
8243     }
8244 
8245     // T* -> int
8246     if (LHSType->isIntegerType()) {
8247       Kind = CK_PointerToIntegral;
8248       return PointerToInt;
8249     }
8250 
8251     return Incompatible;
8252   }
8253 
8254   // Conversions from Objective-C pointers that are not covered by the above.
8255   if (isa<ObjCObjectPointerType>(RHSType)) {
8256     // T* -> _Bool
8257     if (LHSType == Context.BoolTy) {
8258       Kind = CK_PointerToBoolean;
8259       return Compatible;
8260     }
8261 
8262     // T* -> int
8263     if (LHSType->isIntegerType()) {
8264       Kind = CK_PointerToIntegral;
8265       return PointerToInt;
8266     }
8267 
8268     return Incompatible;
8269   }
8270 
8271   // struct A -> struct B
8272   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
8273     if (Context.typesAreCompatible(LHSType, RHSType)) {
8274       Kind = CK_NoOp;
8275       return Compatible;
8276     }
8277   }
8278 
8279   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
8280     Kind = CK_IntToOCLSampler;
8281     return Compatible;
8282   }
8283 
8284   return Incompatible;
8285 }
8286 
8287 /// Constructs a transparent union from an expression that is
8288 /// used to initialize the transparent union.
8289 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
8290                                       ExprResult &EResult, QualType UnionType,
8291                                       FieldDecl *Field) {
8292   // Build an initializer list that designates the appropriate member
8293   // of the transparent union.
8294   Expr *E = EResult.get();
8295   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
8296                                                    E, SourceLocation());
8297   Initializer->setType(UnionType);
8298   Initializer->setInitializedFieldInUnion(Field);
8299 
8300   // Build a compound literal constructing a value of the transparent
8301   // union type from this initializer list.
8302   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
8303   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
8304                                         VK_RValue, Initializer, false);
8305 }
8306 
8307 Sema::AssignConvertType
8308 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
8309                                                ExprResult &RHS) {
8310   QualType RHSType = RHS.get()->getType();
8311 
8312   // If the ArgType is a Union type, we want to handle a potential
8313   // transparent_union GCC extension.
8314   const RecordType *UT = ArgType->getAsUnionType();
8315   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
8316     return Incompatible;
8317 
8318   // The field to initialize within the transparent union.
8319   RecordDecl *UD = UT->getDecl();
8320   FieldDecl *InitField = nullptr;
8321   // It's compatible if the expression matches any of the fields.
8322   for (auto *it : UD->fields()) {
8323     if (it->getType()->isPointerType()) {
8324       // If the transparent union contains a pointer type, we allow:
8325       // 1) void pointer
8326       // 2) null pointer constant
8327       if (RHSType->isPointerType())
8328         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
8329           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
8330           InitField = it;
8331           break;
8332         }
8333 
8334       if (RHS.get()->isNullPointerConstant(Context,
8335                                            Expr::NPC_ValueDependentIsNull)) {
8336         RHS = ImpCastExprToType(RHS.get(), it->getType(),
8337                                 CK_NullToPointer);
8338         InitField = it;
8339         break;
8340       }
8341     }
8342 
8343     CastKind Kind;
8344     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
8345           == Compatible) {
8346       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
8347       InitField = it;
8348       break;
8349     }
8350   }
8351 
8352   if (!InitField)
8353     return Incompatible;
8354 
8355   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
8356   return Compatible;
8357 }
8358 
8359 Sema::AssignConvertType
8360 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
8361                                        bool Diagnose,
8362                                        bool DiagnoseCFAudited,
8363                                        bool ConvertRHS) {
8364   // We need to be able to tell the caller whether we diagnosed a problem, if
8365   // they ask us to issue diagnostics.
8366   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
8367 
8368   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
8369   // we can't avoid *all* modifications at the moment, so we need some somewhere
8370   // to put the updated value.
8371   ExprResult LocalRHS = CallerRHS;
8372   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
8373 
8374   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
8375     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
8376       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8377           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8378         Diag(RHS.get()->getExprLoc(),
8379              diag::warn_noderef_to_dereferenceable_pointer)
8380             << RHS.get()->getSourceRange();
8381       }
8382     }
8383   }
8384 
8385   if (getLangOpts().CPlusPlus) {
8386     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
8387       // C++ 5.17p3: If the left operand is not of class type, the
8388       // expression is implicitly converted (C++ 4) to the
8389       // cv-unqualified type of the left operand.
8390       QualType RHSType = RHS.get()->getType();
8391       if (Diagnose) {
8392         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8393                                         AA_Assigning);
8394       } else {
8395         ImplicitConversionSequence ICS =
8396             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8397                                   /*SuppressUserConversions=*/false,
8398                                   /*AllowExplicit=*/false,
8399                                   /*InOverloadResolution=*/false,
8400                                   /*CStyle=*/false,
8401                                   /*AllowObjCWritebackConversion=*/false);
8402         if (ICS.isFailure())
8403           return Incompatible;
8404         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8405                                         ICS, AA_Assigning);
8406       }
8407       if (RHS.isInvalid())
8408         return Incompatible;
8409       Sema::AssignConvertType result = Compatible;
8410       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8411           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
8412         result = IncompatibleObjCWeakRef;
8413       return result;
8414     }
8415 
8416     // FIXME: Currently, we fall through and treat C++ classes like C
8417     // structures.
8418     // FIXME: We also fall through for atomics; not sure what should
8419     // happen there, though.
8420   } else if (RHS.get()->getType() == Context.OverloadTy) {
8421     // As a set of extensions to C, we support overloading on functions. These
8422     // functions need to be resolved here.
8423     DeclAccessPair DAP;
8424     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
8425             RHS.get(), LHSType, /*Complain=*/false, DAP))
8426       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
8427     else
8428       return Incompatible;
8429   }
8430 
8431   // C99 6.5.16.1p1: the left operand is a pointer and the right is
8432   // a null pointer constant.
8433   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
8434        LHSType->isBlockPointerType()) &&
8435       RHS.get()->isNullPointerConstant(Context,
8436                                        Expr::NPC_ValueDependentIsNull)) {
8437     if (Diagnose || ConvertRHS) {
8438       CastKind Kind;
8439       CXXCastPath Path;
8440       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
8441                              /*IgnoreBaseAccess=*/false, Diagnose);
8442       if (ConvertRHS)
8443         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
8444     }
8445     return Compatible;
8446   }
8447 
8448   // OpenCL queue_t type assignment.
8449   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
8450                                  Context, Expr::NPC_ValueDependentIsNull)) {
8451     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8452     return Compatible;
8453   }
8454 
8455   // This check seems unnatural, however it is necessary to ensure the proper
8456   // conversion of functions/arrays. If the conversion were done for all
8457   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
8458   // expressions that suppress this implicit conversion (&, sizeof).
8459   //
8460   // Suppress this for references: C++ 8.5.3p5.
8461   if (!LHSType->isReferenceType()) {
8462     // FIXME: We potentially allocate here even if ConvertRHS is false.
8463     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
8464     if (RHS.isInvalid())
8465       return Incompatible;
8466   }
8467   CastKind Kind;
8468   Sema::AssignConvertType result =
8469     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
8470 
8471   // C99 6.5.16.1p2: The value of the right operand is converted to the
8472   // type of the assignment expression.
8473   // CheckAssignmentConstraints allows the left-hand side to be a reference,
8474   // so that we can use references in built-in functions even in C.
8475   // The getNonReferenceType() call makes sure that the resulting expression
8476   // does not have reference type.
8477   if (result != Incompatible && RHS.get()->getType() != LHSType) {
8478     QualType Ty = LHSType.getNonLValueExprType(Context);
8479     Expr *E = RHS.get();
8480 
8481     // Check for various Objective-C errors. If we are not reporting
8482     // diagnostics and just checking for errors, e.g., during overload
8483     // resolution, return Incompatible to indicate the failure.
8484     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8485         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8486                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
8487       if (!Diagnose)
8488         return Incompatible;
8489     }
8490     if (getLangOpts().ObjC &&
8491         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
8492                                            E->getType(), E, Diagnose) ||
8493          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8494       if (!Diagnose)
8495         return Incompatible;
8496       // Replace the expression with a corrected version and continue so we
8497       // can find further errors.
8498       RHS = E;
8499       return Compatible;
8500     }
8501 
8502     if (ConvertRHS)
8503       RHS = ImpCastExprToType(E, Ty, Kind);
8504   }
8505 
8506   return result;
8507 }
8508 
8509 namespace {
8510 /// The original operand to an operator, prior to the application of the usual
8511 /// arithmetic conversions and converting the arguments of a builtin operator
8512 /// candidate.
8513 struct OriginalOperand {
8514   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
8515     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
8516       Op = MTE->GetTemporaryExpr();
8517     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
8518       Op = BTE->getSubExpr();
8519     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
8520       Orig = ICE->getSubExprAsWritten();
8521       Conversion = ICE->getConversionFunction();
8522     }
8523   }
8524 
8525   QualType getType() const { return Orig->getType(); }
8526 
8527   Expr *Orig;
8528   NamedDecl *Conversion;
8529 };
8530 }
8531 
8532 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8533                                ExprResult &RHS) {
8534   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
8535 
8536   Diag(Loc, diag::err_typecheck_invalid_operands)
8537     << OrigLHS.getType() << OrigRHS.getType()
8538     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8539 
8540   // If a user-defined conversion was applied to either of the operands prior
8541   // to applying the built-in operator rules, tell the user about it.
8542   if (OrigLHS.Conversion) {
8543     Diag(OrigLHS.Conversion->getLocation(),
8544          diag::note_typecheck_invalid_operands_converted)
8545       << 0 << LHS.get()->getType();
8546   }
8547   if (OrigRHS.Conversion) {
8548     Diag(OrigRHS.Conversion->getLocation(),
8549          diag::note_typecheck_invalid_operands_converted)
8550       << 1 << RHS.get()->getType();
8551   }
8552 
8553   return QualType();
8554 }
8555 
8556 // Diagnose cases where a scalar was implicitly converted to a vector and
8557 // diagnose the underlying types. Otherwise, diagnose the error
8558 // as invalid vector logical operands for non-C++ cases.
8559 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8560                                             ExprResult &RHS) {
8561   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8562   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8563 
8564   bool LHSNatVec = LHSType->isVectorType();
8565   bool RHSNatVec = RHSType->isVectorType();
8566 
8567   if (!(LHSNatVec && RHSNatVec)) {
8568     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8569     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8570     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8571         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8572         << Vector->getSourceRange();
8573     return QualType();
8574   }
8575 
8576   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8577       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8578       << RHS.get()->getSourceRange();
8579 
8580   return QualType();
8581 }
8582 
8583 /// Try to convert a value of non-vector type to a vector type by converting
8584 /// the type to the element type of the vector and then performing a splat.
8585 /// If the language is OpenCL, we only use conversions that promote scalar
8586 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8587 /// for float->int.
8588 ///
8589 /// OpenCL V2.0 6.2.6.p2:
8590 /// An error shall occur if any scalar operand type has greater rank
8591 /// than the type of the vector element.
8592 ///
8593 /// \param scalar - if non-null, actually perform the conversions
8594 /// \return true if the operation fails (but without diagnosing the failure)
8595 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8596                                      QualType scalarTy,
8597                                      QualType vectorEltTy,
8598                                      QualType vectorTy,
8599                                      unsigned &DiagID) {
8600   // The conversion to apply to the scalar before splatting it,
8601   // if necessary.
8602   CastKind scalarCast = CK_NoOp;
8603 
8604   if (vectorEltTy->isIntegralType(S.Context)) {
8605     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8606         (scalarTy->isIntegerType() &&
8607          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8608       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8609       return true;
8610     }
8611     if (!scalarTy->isIntegralType(S.Context))
8612       return true;
8613     scalarCast = CK_IntegralCast;
8614   } else if (vectorEltTy->isRealFloatingType()) {
8615     if (scalarTy->isRealFloatingType()) {
8616       if (S.getLangOpts().OpenCL &&
8617           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8618         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8619         return true;
8620       }
8621       scalarCast = CK_FloatingCast;
8622     }
8623     else if (scalarTy->isIntegralType(S.Context))
8624       scalarCast = CK_IntegralToFloating;
8625     else
8626       return true;
8627   } else {
8628     return true;
8629   }
8630 
8631   // Adjust scalar if desired.
8632   if (scalar) {
8633     if (scalarCast != CK_NoOp)
8634       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8635     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8636   }
8637   return false;
8638 }
8639 
8640 /// Convert vector E to a vector with the same number of elements but different
8641 /// element type.
8642 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
8643   const auto *VecTy = E->getType()->getAs<VectorType>();
8644   assert(VecTy && "Expression E must be a vector");
8645   QualType NewVecTy = S.Context.getVectorType(ElementType,
8646                                               VecTy->getNumElements(),
8647                                               VecTy->getVectorKind());
8648 
8649   // Look through the implicit cast. Return the subexpression if its type is
8650   // NewVecTy.
8651   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
8652     if (ICE->getSubExpr()->getType() == NewVecTy)
8653       return ICE->getSubExpr();
8654 
8655   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
8656   return S.ImpCastExprToType(E, NewVecTy, Cast);
8657 }
8658 
8659 /// Test if a (constant) integer Int can be casted to another integer type
8660 /// IntTy without losing precision.
8661 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8662                                       QualType OtherIntTy) {
8663   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8664 
8665   // Reject cases where the value of the Int is unknown as that would
8666   // possibly cause truncation, but accept cases where the scalar can be
8667   // demoted without loss of precision.
8668   Expr::EvalResult EVResult;
8669   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8670   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8671   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8672   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8673 
8674   if (CstInt) {
8675     // If the scalar is constant and is of a higher order and has more active
8676     // bits that the vector element type, reject it.
8677     llvm::APSInt Result = EVResult.Val.getInt();
8678     unsigned NumBits = IntSigned
8679                            ? (Result.isNegative() ? Result.getMinSignedBits()
8680                                                   : Result.getActiveBits())
8681                            : Result.getActiveBits();
8682     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8683       return true;
8684 
8685     // If the signedness of the scalar type and the vector element type
8686     // differs and the number of bits is greater than that of the vector
8687     // element reject it.
8688     return (IntSigned != OtherIntSigned &&
8689             NumBits > S.Context.getIntWidth(OtherIntTy));
8690   }
8691 
8692   // Reject cases where the value of the scalar is not constant and it's
8693   // order is greater than that of the vector element type.
8694   return (Order < 0);
8695 }
8696 
8697 /// Test if a (constant) integer Int can be casted to floating point type
8698 /// FloatTy without losing precision.
8699 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
8700                                      QualType FloatTy) {
8701   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8702 
8703   // Determine if the integer constant can be expressed as a floating point
8704   // number of the appropriate type.
8705   Expr::EvalResult EVResult;
8706   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8707 
8708   uint64_t Bits = 0;
8709   if (CstInt) {
8710     // Reject constants that would be truncated if they were converted to
8711     // the floating point type. Test by simple to/from conversion.
8712     // FIXME: Ideally the conversion to an APFloat and from an APFloat
8713     //        could be avoided if there was a convertFromAPInt method
8714     //        which could signal back if implicit truncation occurred.
8715     llvm::APSInt Result = EVResult.Val.getInt();
8716     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8717     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8718                            llvm::APFloat::rmTowardZero);
8719     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8720                              !IntTy->hasSignedIntegerRepresentation());
8721     bool Ignored = false;
8722     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8723                            &Ignored);
8724     if (Result != ConvertBack)
8725       return true;
8726   } else {
8727     // Reject types that cannot be fully encoded into the mantissa of
8728     // the float.
8729     Bits = S.Context.getTypeSize(IntTy);
8730     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8731         S.Context.getFloatTypeSemantics(FloatTy));
8732     if (Bits > FloatPrec)
8733       return true;
8734   }
8735 
8736   return false;
8737 }
8738 
8739 /// Attempt to convert and splat Scalar into a vector whose types matches
8740 /// Vector following GCC conversion rules. The rule is that implicit
8741 /// conversion can occur when Scalar can be casted to match Vector's element
8742 /// type without causing truncation of Scalar.
8743 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
8744                                         ExprResult *Vector) {
8745   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8746   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8747   const VectorType *VT = VectorTy->getAs<VectorType>();
8748 
8749   assert(!isa<ExtVectorType>(VT) &&
8750          "ExtVectorTypes should not be handled here!");
8751 
8752   QualType VectorEltTy = VT->getElementType();
8753 
8754   // Reject cases where the vector element type or the scalar element type are
8755   // not integral or floating point types.
8756   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8757     return true;
8758 
8759   // The conversion to apply to the scalar before splatting it,
8760   // if necessary.
8761   CastKind ScalarCast = CK_NoOp;
8762 
8763   // Accept cases where the vector elements are integers and the scalar is
8764   // an integer.
8765   // FIXME: Notionally if the scalar was a floating point value with a precise
8766   //        integral representation, we could cast it to an appropriate integer
8767   //        type and then perform the rest of the checks here. GCC will perform
8768   //        this conversion in some cases as determined by the input language.
8769   //        We should accept it on a language independent basis.
8770   if (VectorEltTy->isIntegralType(S.Context) &&
8771       ScalarTy->isIntegralType(S.Context) &&
8772       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8773 
8774     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8775       return true;
8776 
8777     ScalarCast = CK_IntegralCast;
8778   } else if (VectorEltTy->isRealFloatingType()) {
8779     if (ScalarTy->isRealFloatingType()) {
8780 
8781       // Reject cases where the scalar type is not a constant and has a higher
8782       // Order than the vector element type.
8783       llvm::APFloat Result(0.0);
8784       bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8785       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8786       if (!CstScalar && Order < 0)
8787         return true;
8788 
8789       // If the scalar cannot be safely casted to the vector element type,
8790       // reject it.
8791       if (CstScalar) {
8792         bool Truncated = false;
8793         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8794                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
8795         if (Truncated)
8796           return true;
8797       }
8798 
8799       ScalarCast = CK_FloatingCast;
8800     } else if (ScalarTy->isIntegralType(S.Context)) {
8801       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8802         return true;
8803 
8804       ScalarCast = CK_IntegralToFloating;
8805     } else
8806       return true;
8807   }
8808 
8809   // Adjust scalar if desired.
8810   if (Scalar) {
8811     if (ScalarCast != CK_NoOp)
8812       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8813     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8814   }
8815   return false;
8816 }
8817 
8818 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8819                                    SourceLocation Loc, bool IsCompAssign,
8820                                    bool AllowBothBool,
8821                                    bool AllowBoolConversions) {
8822   if (!IsCompAssign) {
8823     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8824     if (LHS.isInvalid())
8825       return QualType();
8826   }
8827   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8828   if (RHS.isInvalid())
8829     return QualType();
8830 
8831   // For conversion purposes, we ignore any qualifiers.
8832   // For example, "const float" and "float" are equivalent.
8833   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8834   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8835 
8836   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8837   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8838   assert(LHSVecType || RHSVecType);
8839 
8840   // AltiVec-style "vector bool op vector bool" combinations are allowed
8841   // for some operators but not others.
8842   if (!AllowBothBool &&
8843       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8844       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8845     return InvalidOperands(Loc, LHS, RHS);
8846 
8847   // If the vector types are identical, return.
8848   if (Context.hasSameType(LHSType, RHSType))
8849     return LHSType;
8850 
8851   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8852   if (LHSVecType && RHSVecType &&
8853       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8854     if (isa<ExtVectorType>(LHSVecType)) {
8855       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8856       return LHSType;
8857     }
8858 
8859     if (!IsCompAssign)
8860       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8861     return RHSType;
8862   }
8863 
8864   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8865   // can be mixed, with the result being the non-bool type.  The non-bool
8866   // operand must have integer element type.
8867   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8868       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8869       (Context.getTypeSize(LHSVecType->getElementType()) ==
8870        Context.getTypeSize(RHSVecType->getElementType()))) {
8871     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8872         LHSVecType->getElementType()->isIntegerType() &&
8873         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8874       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8875       return LHSType;
8876     }
8877     if (!IsCompAssign &&
8878         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8879         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8880         RHSVecType->getElementType()->isIntegerType()) {
8881       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8882       return RHSType;
8883     }
8884   }
8885 
8886   // If there's a vector type and a scalar, try to convert the scalar to
8887   // the vector element type and splat.
8888   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
8889   if (!RHSVecType) {
8890     if (isa<ExtVectorType>(LHSVecType)) {
8891       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8892                                     LHSVecType->getElementType(), LHSType,
8893                                     DiagID))
8894         return LHSType;
8895     } else {
8896       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
8897         return LHSType;
8898     }
8899   }
8900   if (!LHSVecType) {
8901     if (isa<ExtVectorType>(RHSVecType)) {
8902       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8903                                     LHSType, RHSVecType->getElementType(),
8904                                     RHSType, DiagID))
8905         return RHSType;
8906     } else {
8907       if (LHS.get()->getValueKind() == VK_LValue ||
8908           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
8909         return RHSType;
8910     }
8911   }
8912 
8913   // FIXME: The code below also handles conversion between vectors and
8914   // non-scalars, we should break this down into fine grained specific checks
8915   // and emit proper diagnostics.
8916   QualType VecType = LHSVecType ? LHSType : RHSType;
8917   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8918   QualType OtherType = LHSVecType ? RHSType : LHSType;
8919   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8920   if (isLaxVectorConversion(OtherType, VecType)) {
8921     // If we're allowing lax vector conversions, only the total (data) size
8922     // needs to be the same. For non compound assignment, if one of the types is
8923     // scalar, the result is always the vector type.
8924     if (!IsCompAssign) {
8925       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8926       return VecType;
8927     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8928     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8929     // type. Note that this is already done by non-compound assignments in
8930     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8931     // <1 x T> -> T. The result is also a vector type.
8932     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
8933                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8934       ExprResult *RHSExpr = &RHS;
8935       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8936       return VecType;
8937     }
8938   }
8939 
8940   // Okay, the expression is invalid.
8941 
8942   // If there's a non-vector, non-real operand, diagnose that.
8943   if ((!RHSVecType && !RHSType->isRealType()) ||
8944       (!LHSVecType && !LHSType->isRealType())) {
8945     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8946       << LHSType << RHSType
8947       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8948     return QualType();
8949   }
8950 
8951   // OpenCL V1.1 6.2.6.p1:
8952   // If the operands are of more than one vector type, then an error shall
8953   // occur. Implicit conversions between vector types are not permitted, per
8954   // section 6.2.1.
8955   if (getLangOpts().OpenCL &&
8956       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8957       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8958     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8959                                                            << RHSType;
8960     return QualType();
8961   }
8962 
8963 
8964   // If there is a vector type that is not a ExtVector and a scalar, we reach
8965   // this point if scalar could not be converted to the vector's element type
8966   // without truncation.
8967   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
8968       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
8969     QualType Scalar = LHSVecType ? RHSType : LHSType;
8970     QualType Vector = LHSVecType ? LHSType : RHSType;
8971     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
8972     Diag(Loc,
8973          diag::err_typecheck_vector_not_convertable_implict_truncation)
8974         << ScalarOrVector << Scalar << Vector;
8975 
8976     return QualType();
8977   }
8978 
8979   // Otherwise, use the generic diagnostic.
8980   Diag(Loc, DiagID)
8981     << LHSType << RHSType
8982     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8983   return QualType();
8984 }
8985 
8986 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8987 // expression.  These are mainly cases where the null pointer is used as an
8988 // integer instead of a pointer.
8989 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8990                                 SourceLocation Loc, bool IsCompare) {
8991   // The canonical way to check for a GNU null is with isNullPointerConstant,
8992   // but we use a bit of a hack here for speed; this is a relatively
8993   // hot path, and isNullPointerConstant is slow.
8994   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8995   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8996 
8997   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8998 
8999   // Avoid analyzing cases where the result will either be invalid (and
9000   // diagnosed as such) or entirely valid and not something to warn about.
9001   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
9002       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
9003     return;
9004 
9005   // Comparison operations would not make sense with a null pointer no matter
9006   // what the other expression is.
9007   if (!IsCompare) {
9008     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
9009         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
9010         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
9011     return;
9012   }
9013 
9014   // The rest of the operations only make sense with a null pointer
9015   // if the other expression is a pointer.
9016   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
9017       NonNullType->canDecayToPointerType())
9018     return;
9019 
9020   S.Diag(Loc, diag::warn_null_in_comparison_operation)
9021       << LHSNull /* LHS is NULL */ << NonNullType
9022       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9023 }
9024 
9025 static void DiagnoseDivisionSizeofPointer(Sema &S, Expr *LHS, Expr *RHS,
9026                                           SourceLocation Loc) {
9027   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
9028   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
9029   if (!LUE || !RUE)
9030     return;
9031   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
9032       RUE->getKind() != UETT_SizeOf)
9033     return;
9034 
9035   QualType LHSTy = LUE->getArgumentExpr()->IgnoreParens()->getType();
9036   QualType RHSTy;
9037 
9038   if (RUE->isArgumentType())
9039     RHSTy = RUE->getArgumentType();
9040   else
9041     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
9042 
9043   if (!LHSTy->isPointerType() || RHSTy->isPointerType())
9044     return;
9045   if (LHSTy->getPointeeType() != RHSTy)
9046     return;
9047 
9048   S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
9049 }
9050 
9051 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
9052                                                ExprResult &RHS,
9053                                                SourceLocation Loc, bool IsDiv) {
9054   // Check for division/remainder by zero.
9055   Expr::EvalResult RHSValue;
9056   if (!RHS.get()->isValueDependent() &&
9057       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
9058       RHSValue.Val.getInt() == 0)
9059     S.DiagRuntimeBehavior(Loc, RHS.get(),
9060                           S.PDiag(diag::warn_remainder_division_by_zero)
9061                             << IsDiv << RHS.get()->getSourceRange());
9062 }
9063 
9064 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
9065                                            SourceLocation Loc,
9066                                            bool IsCompAssign, bool IsDiv) {
9067   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9068 
9069   if (LHS.get()->getType()->isVectorType() ||
9070       RHS.get()->getType()->isVectorType())
9071     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9072                                /*AllowBothBool*/getLangOpts().AltiVec,
9073                                /*AllowBoolConversions*/false);
9074 
9075   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
9076   if (LHS.isInvalid() || RHS.isInvalid())
9077     return QualType();
9078 
9079 
9080   if (compType.isNull() || !compType->isArithmeticType())
9081     return InvalidOperands(Loc, LHS, RHS);
9082   if (IsDiv) {
9083     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
9084     DiagnoseDivisionSizeofPointer(*this, LHS.get(), RHS.get(), Loc);
9085   }
9086   return compType;
9087 }
9088 
9089 QualType Sema::CheckRemainderOperands(
9090   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
9091   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9092 
9093   if (LHS.get()->getType()->isVectorType() ||
9094       RHS.get()->getType()->isVectorType()) {
9095     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9096         RHS.get()->getType()->hasIntegerRepresentation())
9097       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9098                                  /*AllowBothBool*/getLangOpts().AltiVec,
9099                                  /*AllowBoolConversions*/false);
9100     return InvalidOperands(Loc, LHS, RHS);
9101   }
9102 
9103   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
9104   if (LHS.isInvalid() || RHS.isInvalid())
9105     return QualType();
9106 
9107   if (compType.isNull() || !compType->isIntegerType())
9108     return InvalidOperands(Loc, LHS, RHS);
9109   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
9110   return compType;
9111 }
9112 
9113 /// Diagnose invalid arithmetic on two void pointers.
9114 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
9115                                                 Expr *LHSExpr, Expr *RHSExpr) {
9116   S.Diag(Loc, S.getLangOpts().CPlusPlus
9117                 ? diag::err_typecheck_pointer_arith_void_type
9118                 : diag::ext_gnu_void_ptr)
9119     << 1 /* two pointers */ << LHSExpr->getSourceRange()
9120                             << RHSExpr->getSourceRange();
9121 }
9122 
9123 /// Diagnose invalid arithmetic on a void pointer.
9124 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
9125                                             Expr *Pointer) {
9126   S.Diag(Loc, S.getLangOpts().CPlusPlus
9127                 ? diag::err_typecheck_pointer_arith_void_type
9128                 : diag::ext_gnu_void_ptr)
9129     << 0 /* one pointer */ << Pointer->getSourceRange();
9130 }
9131 
9132 /// Diagnose invalid arithmetic on a null pointer.
9133 ///
9134 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
9135 /// idiom, which we recognize as a GNU extension.
9136 ///
9137 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
9138                                             Expr *Pointer, bool IsGNUIdiom) {
9139   if (IsGNUIdiom)
9140     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
9141       << Pointer->getSourceRange();
9142   else
9143     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
9144       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
9145 }
9146 
9147 /// Diagnose invalid arithmetic on two function pointers.
9148 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
9149                                                     Expr *LHS, Expr *RHS) {
9150   assert(LHS->getType()->isAnyPointerType());
9151   assert(RHS->getType()->isAnyPointerType());
9152   S.Diag(Loc, S.getLangOpts().CPlusPlus
9153                 ? diag::err_typecheck_pointer_arith_function_type
9154                 : diag::ext_gnu_ptr_func_arith)
9155     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
9156     // We only show the second type if it differs from the first.
9157     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
9158                                                    RHS->getType())
9159     << RHS->getType()->getPointeeType()
9160     << LHS->getSourceRange() << RHS->getSourceRange();
9161 }
9162 
9163 /// Diagnose invalid arithmetic on a function pointer.
9164 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
9165                                                 Expr *Pointer) {
9166   assert(Pointer->getType()->isAnyPointerType());
9167   S.Diag(Loc, S.getLangOpts().CPlusPlus
9168                 ? diag::err_typecheck_pointer_arith_function_type
9169                 : diag::ext_gnu_ptr_func_arith)
9170     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
9171     << 0 /* one pointer, so only one type */
9172     << Pointer->getSourceRange();
9173 }
9174 
9175 /// Emit error if Operand is incomplete pointer type
9176 ///
9177 /// \returns True if pointer has incomplete type
9178 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
9179                                                  Expr *Operand) {
9180   QualType ResType = Operand->getType();
9181   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9182     ResType = ResAtomicType->getValueType();
9183 
9184   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
9185   QualType PointeeTy = ResType->getPointeeType();
9186   return S.RequireCompleteType(Loc, PointeeTy,
9187                                diag::err_typecheck_arithmetic_incomplete_type,
9188                                PointeeTy, Operand->getSourceRange());
9189 }
9190 
9191 /// Check the validity of an arithmetic pointer operand.
9192 ///
9193 /// If the operand has pointer type, this code will check for pointer types
9194 /// which are invalid in arithmetic operations. These will be diagnosed
9195 /// appropriately, including whether or not the use is supported as an
9196 /// extension.
9197 ///
9198 /// \returns True when the operand is valid to use (even if as an extension).
9199 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
9200                                             Expr *Operand) {
9201   QualType ResType = Operand->getType();
9202   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9203     ResType = ResAtomicType->getValueType();
9204 
9205   if (!ResType->isAnyPointerType()) return true;
9206 
9207   QualType PointeeTy = ResType->getPointeeType();
9208   if (PointeeTy->isVoidType()) {
9209     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
9210     return !S.getLangOpts().CPlusPlus;
9211   }
9212   if (PointeeTy->isFunctionType()) {
9213     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
9214     return !S.getLangOpts().CPlusPlus;
9215   }
9216 
9217   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
9218 
9219   return true;
9220 }
9221 
9222 /// Check the validity of a binary arithmetic operation w.r.t. pointer
9223 /// operands.
9224 ///
9225 /// This routine will diagnose any invalid arithmetic on pointer operands much
9226 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
9227 /// for emitting a single diagnostic even for operations where both LHS and RHS
9228 /// are (potentially problematic) pointers.
9229 ///
9230 /// \returns True when the operand is valid to use (even if as an extension).
9231 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
9232                                                 Expr *LHSExpr, Expr *RHSExpr) {
9233   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
9234   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
9235   if (!isLHSPointer && !isRHSPointer) return true;
9236 
9237   QualType LHSPointeeTy, RHSPointeeTy;
9238   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
9239   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
9240 
9241   // if both are pointers check if operation is valid wrt address spaces
9242   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
9243     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
9244     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
9245     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
9246       S.Diag(Loc,
9247              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9248           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
9249           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9250       return false;
9251     }
9252   }
9253 
9254   // Check for arithmetic on pointers to incomplete types.
9255   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
9256   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
9257   if (isLHSVoidPtr || isRHSVoidPtr) {
9258     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
9259     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
9260     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
9261 
9262     return !S.getLangOpts().CPlusPlus;
9263   }
9264 
9265   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
9266   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
9267   if (isLHSFuncPtr || isRHSFuncPtr) {
9268     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
9269     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
9270                                                                 RHSExpr);
9271     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
9272 
9273     return !S.getLangOpts().CPlusPlus;
9274   }
9275 
9276   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
9277     return false;
9278   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
9279     return false;
9280 
9281   return true;
9282 }
9283 
9284 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
9285 /// literal.
9286 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
9287                                   Expr *LHSExpr, Expr *RHSExpr) {
9288   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
9289   Expr* IndexExpr = RHSExpr;
9290   if (!StrExpr) {
9291     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
9292     IndexExpr = LHSExpr;
9293   }
9294 
9295   bool IsStringPlusInt = StrExpr &&
9296       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
9297   if (!IsStringPlusInt || IndexExpr->isValueDependent())
9298     return;
9299 
9300   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9301   Self.Diag(OpLoc, diag::warn_string_plus_int)
9302       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
9303 
9304   // Only print a fixit for "str" + int, not for int + "str".
9305   if (IndexExpr == RHSExpr) {
9306     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9307     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9308         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9309         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9310         << FixItHint::CreateInsertion(EndLoc, "]");
9311   } else
9312     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9313 }
9314 
9315 /// Emit a warning when adding a char literal to a string.
9316 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
9317                                    Expr *LHSExpr, Expr *RHSExpr) {
9318   const Expr *StringRefExpr = LHSExpr;
9319   const CharacterLiteral *CharExpr =
9320       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
9321 
9322   if (!CharExpr) {
9323     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
9324     StringRefExpr = RHSExpr;
9325   }
9326 
9327   if (!CharExpr || !StringRefExpr)
9328     return;
9329 
9330   const QualType StringType = StringRefExpr->getType();
9331 
9332   // Return if not a PointerType.
9333   if (!StringType->isAnyPointerType())
9334     return;
9335 
9336   // Return if not a CharacterType.
9337   if (!StringType->getPointeeType()->isAnyCharacterType())
9338     return;
9339 
9340   ASTContext &Ctx = Self.getASTContext();
9341   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9342 
9343   const QualType CharType = CharExpr->getType();
9344   if (!CharType->isAnyCharacterType() &&
9345       CharType->isIntegerType() &&
9346       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
9347     Self.Diag(OpLoc, diag::warn_string_plus_char)
9348         << DiagRange << Ctx.CharTy;
9349   } else {
9350     Self.Diag(OpLoc, diag::warn_string_plus_char)
9351         << DiagRange << CharExpr->getType();
9352   }
9353 
9354   // Only print a fixit for str + char, not for char + str.
9355   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
9356     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9357     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9358         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9359         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9360         << FixItHint::CreateInsertion(EndLoc, "]");
9361   } else {
9362     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9363   }
9364 }
9365 
9366 /// Emit error when two pointers are incompatible.
9367 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
9368                                            Expr *LHSExpr, Expr *RHSExpr) {
9369   assert(LHSExpr->getType()->isAnyPointerType());
9370   assert(RHSExpr->getType()->isAnyPointerType());
9371   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
9372     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
9373     << RHSExpr->getSourceRange();
9374 }
9375 
9376 // C99 6.5.6
9377 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
9378                                      SourceLocation Loc, BinaryOperatorKind Opc,
9379                                      QualType* CompLHSTy) {
9380   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9381 
9382   if (LHS.get()->getType()->isVectorType() ||
9383       RHS.get()->getType()->isVectorType()) {
9384     QualType compType = CheckVectorOperands(
9385         LHS, RHS, Loc, CompLHSTy,
9386         /*AllowBothBool*/getLangOpts().AltiVec,
9387         /*AllowBoolConversions*/getLangOpts().ZVector);
9388     if (CompLHSTy) *CompLHSTy = compType;
9389     return compType;
9390   }
9391 
9392   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9393   if (LHS.isInvalid() || RHS.isInvalid())
9394     return QualType();
9395 
9396   // Diagnose "string literal" '+' int and string '+' "char literal".
9397   if (Opc == BO_Add) {
9398     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
9399     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
9400   }
9401 
9402   // handle the common case first (both operands are arithmetic).
9403   if (!compType.isNull() && compType->isArithmeticType()) {
9404     if (CompLHSTy) *CompLHSTy = compType;
9405     return compType;
9406   }
9407 
9408   // Type-checking.  Ultimately the pointer's going to be in PExp;
9409   // note that we bias towards the LHS being the pointer.
9410   Expr *PExp = LHS.get(), *IExp = RHS.get();
9411 
9412   bool isObjCPointer;
9413   if (PExp->getType()->isPointerType()) {
9414     isObjCPointer = false;
9415   } else if (PExp->getType()->isObjCObjectPointerType()) {
9416     isObjCPointer = true;
9417   } else {
9418     std::swap(PExp, IExp);
9419     if (PExp->getType()->isPointerType()) {
9420       isObjCPointer = false;
9421     } else if (PExp->getType()->isObjCObjectPointerType()) {
9422       isObjCPointer = true;
9423     } else {
9424       return InvalidOperands(Loc, LHS, RHS);
9425     }
9426   }
9427   assert(PExp->getType()->isAnyPointerType());
9428 
9429   if (!IExp->getType()->isIntegerType())
9430     return InvalidOperands(Loc, LHS, RHS);
9431 
9432   // Adding to a null pointer results in undefined behavior.
9433   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
9434           Context, Expr::NPC_ValueDependentIsNotNull)) {
9435     // In C++ adding zero to a null pointer is defined.
9436     Expr::EvalResult KnownVal;
9437     if (!getLangOpts().CPlusPlus ||
9438         (!IExp->isValueDependent() &&
9439          (!IExp->EvaluateAsInt(KnownVal, Context) ||
9440           KnownVal.Val.getInt() != 0))) {
9441       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
9442       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
9443           Context, BO_Add, PExp, IExp);
9444       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
9445     }
9446   }
9447 
9448   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
9449     return QualType();
9450 
9451   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
9452     return QualType();
9453 
9454   // Check array bounds for pointer arithemtic
9455   CheckArrayAccess(PExp, IExp);
9456 
9457   if (CompLHSTy) {
9458     QualType LHSTy = Context.isPromotableBitField(LHS.get());
9459     if (LHSTy.isNull()) {
9460       LHSTy = LHS.get()->getType();
9461       if (LHSTy->isPromotableIntegerType())
9462         LHSTy = Context.getPromotedIntegerType(LHSTy);
9463     }
9464     *CompLHSTy = LHSTy;
9465   }
9466 
9467   return PExp->getType();
9468 }
9469 
9470 // C99 6.5.6
9471 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
9472                                         SourceLocation Loc,
9473                                         QualType* CompLHSTy) {
9474   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9475 
9476   if (LHS.get()->getType()->isVectorType() ||
9477       RHS.get()->getType()->isVectorType()) {
9478     QualType compType = CheckVectorOperands(
9479         LHS, RHS, Loc, CompLHSTy,
9480         /*AllowBothBool*/getLangOpts().AltiVec,
9481         /*AllowBoolConversions*/getLangOpts().ZVector);
9482     if (CompLHSTy) *CompLHSTy = compType;
9483     return compType;
9484   }
9485 
9486   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9487   if (LHS.isInvalid() || RHS.isInvalid())
9488     return QualType();
9489 
9490   // Enforce type constraints: C99 6.5.6p3.
9491 
9492   // Handle the common case first (both operands are arithmetic).
9493   if (!compType.isNull() && compType->isArithmeticType()) {
9494     if (CompLHSTy) *CompLHSTy = compType;
9495     return compType;
9496   }
9497 
9498   // Either ptr - int   or   ptr - ptr.
9499   if (LHS.get()->getType()->isAnyPointerType()) {
9500     QualType lpointee = LHS.get()->getType()->getPointeeType();
9501 
9502     // Diagnose bad cases where we step over interface counts.
9503     if (LHS.get()->getType()->isObjCObjectPointerType() &&
9504         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
9505       return QualType();
9506 
9507     // The result type of a pointer-int computation is the pointer type.
9508     if (RHS.get()->getType()->isIntegerType()) {
9509       // Subtracting from a null pointer should produce a warning.
9510       // The last argument to the diagnose call says this doesn't match the
9511       // GNU int-to-pointer idiom.
9512       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
9513                                            Expr::NPC_ValueDependentIsNotNull)) {
9514         // In C++ adding zero to a null pointer is defined.
9515         Expr::EvalResult KnownVal;
9516         if (!getLangOpts().CPlusPlus ||
9517             (!RHS.get()->isValueDependent() &&
9518              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
9519               KnownVal.Val.getInt() != 0))) {
9520           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
9521         }
9522       }
9523 
9524       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
9525         return QualType();
9526 
9527       // Check array bounds for pointer arithemtic
9528       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
9529                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
9530 
9531       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9532       return LHS.get()->getType();
9533     }
9534 
9535     // Handle pointer-pointer subtractions.
9536     if (const PointerType *RHSPTy
9537           = RHS.get()->getType()->getAs<PointerType>()) {
9538       QualType rpointee = RHSPTy->getPointeeType();
9539 
9540       if (getLangOpts().CPlusPlus) {
9541         // Pointee types must be the same: C++ [expr.add]
9542         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
9543           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9544         }
9545       } else {
9546         // Pointee types must be compatible C99 6.5.6p3
9547         if (!Context.typesAreCompatible(
9548                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
9549                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
9550           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9551           return QualType();
9552         }
9553       }
9554 
9555       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
9556                                                LHS.get(), RHS.get()))
9557         return QualType();
9558 
9559       // FIXME: Add warnings for nullptr - ptr.
9560 
9561       // The pointee type may have zero size.  As an extension, a structure or
9562       // union may have zero size or an array may have zero length.  In this
9563       // case subtraction does not make sense.
9564       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
9565         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
9566         if (ElementSize.isZero()) {
9567           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
9568             << rpointee.getUnqualifiedType()
9569             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9570         }
9571       }
9572 
9573       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9574       return Context.getPointerDiffType();
9575     }
9576   }
9577 
9578   return InvalidOperands(Loc, LHS, RHS);
9579 }
9580 
9581 static bool isScopedEnumerationType(QualType T) {
9582   if (const EnumType *ET = T->getAs<EnumType>())
9583     return ET->getDecl()->isScoped();
9584   return false;
9585 }
9586 
9587 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
9588                                    SourceLocation Loc, BinaryOperatorKind Opc,
9589                                    QualType LHSType) {
9590   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
9591   // so skip remaining warnings as we don't want to modify values within Sema.
9592   if (S.getLangOpts().OpenCL)
9593     return;
9594 
9595   // Check right/shifter operand
9596   Expr::EvalResult RHSResult;
9597   if (RHS.get()->isValueDependent() ||
9598       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
9599     return;
9600   llvm::APSInt Right = RHSResult.Val.getInt();
9601 
9602   if (Right.isNegative()) {
9603     S.DiagRuntimeBehavior(Loc, RHS.get(),
9604                           S.PDiag(diag::warn_shift_negative)
9605                             << RHS.get()->getSourceRange());
9606     return;
9607   }
9608   llvm::APInt LeftBits(Right.getBitWidth(),
9609                        S.Context.getTypeSize(LHS.get()->getType()));
9610   if (Right.uge(LeftBits)) {
9611     S.DiagRuntimeBehavior(Loc, RHS.get(),
9612                           S.PDiag(diag::warn_shift_gt_typewidth)
9613                             << RHS.get()->getSourceRange());
9614     return;
9615   }
9616   if (Opc != BO_Shl)
9617     return;
9618 
9619   // When left shifting an ICE which is signed, we can check for overflow which
9620   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
9621   // integers have defined behavior modulo one more than the maximum value
9622   // representable in the result type, so never warn for those.
9623   Expr::EvalResult LHSResult;
9624   if (LHS.get()->isValueDependent() ||
9625       LHSType->hasUnsignedIntegerRepresentation() ||
9626       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
9627     return;
9628   llvm::APSInt Left = LHSResult.Val.getInt();
9629 
9630   // If LHS does not have a signed type and non-negative value
9631   // then, the behavior is undefined. Warn about it.
9632   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
9633     S.DiagRuntimeBehavior(Loc, LHS.get(),
9634                           S.PDiag(diag::warn_shift_lhs_negative)
9635                             << LHS.get()->getSourceRange());
9636     return;
9637   }
9638 
9639   llvm::APInt ResultBits =
9640       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9641   if (LeftBits.uge(ResultBits))
9642     return;
9643   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9644   Result = Result.shl(Right);
9645 
9646   // Print the bit representation of the signed integer as an unsigned
9647   // hexadecimal number.
9648   SmallString<40> HexResult;
9649   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9650 
9651   // If we are only missing a sign bit, this is less likely to result in actual
9652   // bugs -- if the result is cast back to an unsigned type, it will have the
9653   // expected value. Thus we place this behind a different warning that can be
9654   // turned off separately if needed.
9655   if (LeftBits == ResultBits - 1) {
9656     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
9657         << HexResult << LHSType
9658         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9659     return;
9660   }
9661 
9662   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
9663     << HexResult.str() << Result.getMinSignedBits() << LHSType
9664     << Left.getBitWidth() << LHS.get()->getSourceRange()
9665     << RHS.get()->getSourceRange();
9666 }
9667 
9668 /// Return the resulting type when a vector is shifted
9669 ///        by a scalar or vector shift amount.
9670 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
9671                                  SourceLocation Loc, bool IsCompAssign) {
9672   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
9673   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
9674       !LHS.get()->getType()->isVectorType()) {
9675     S.Diag(Loc, diag::err_shift_rhs_only_vector)
9676       << RHS.get()->getType() << LHS.get()->getType()
9677       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9678     return QualType();
9679   }
9680 
9681   if (!IsCompAssign) {
9682     LHS = S.UsualUnaryConversions(LHS.get());
9683     if (LHS.isInvalid()) return QualType();
9684   }
9685 
9686   RHS = S.UsualUnaryConversions(RHS.get());
9687   if (RHS.isInvalid()) return QualType();
9688 
9689   QualType LHSType = LHS.get()->getType();
9690   // Note that LHS might be a scalar because the routine calls not only in
9691   // OpenCL case.
9692   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
9693   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
9694 
9695   // Note that RHS might not be a vector.
9696   QualType RHSType = RHS.get()->getType();
9697   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
9698   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
9699 
9700   // The operands need to be integers.
9701   if (!LHSEleType->isIntegerType()) {
9702     S.Diag(Loc, diag::err_typecheck_expect_int)
9703       << LHS.get()->getType() << LHS.get()->getSourceRange();
9704     return QualType();
9705   }
9706 
9707   if (!RHSEleType->isIntegerType()) {
9708     S.Diag(Loc, diag::err_typecheck_expect_int)
9709       << RHS.get()->getType() << RHS.get()->getSourceRange();
9710     return QualType();
9711   }
9712 
9713   if (!LHSVecTy) {
9714     assert(RHSVecTy);
9715     if (IsCompAssign)
9716       return RHSType;
9717     if (LHSEleType != RHSEleType) {
9718       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9719       LHSEleType = RHSEleType;
9720     }
9721     QualType VecTy =
9722         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9723     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9724     LHSType = VecTy;
9725   } else if (RHSVecTy) {
9726     // OpenCL v1.1 s6.3.j says that for vector types, the operators
9727     // are applied component-wise. So if RHS is a vector, then ensure
9728     // that the number of elements is the same as LHS...
9729     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9730       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9731         << LHS.get()->getType() << RHS.get()->getType()
9732         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9733       return QualType();
9734     }
9735     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9736       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9737       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9738       if (LHSBT != RHSBT &&
9739           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9740         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9741             << LHS.get()->getType() << RHS.get()->getType()
9742             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9743       }
9744     }
9745   } else {
9746     // ...else expand RHS to match the number of elements in LHS.
9747     QualType VecTy =
9748       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9749     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9750   }
9751 
9752   return LHSType;
9753 }
9754 
9755 // C99 6.5.7
9756 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
9757                                   SourceLocation Loc, BinaryOperatorKind Opc,
9758                                   bool IsCompAssign) {
9759   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9760 
9761   // Vector shifts promote their scalar inputs to vector type.
9762   if (LHS.get()->getType()->isVectorType() ||
9763       RHS.get()->getType()->isVectorType()) {
9764     if (LangOpts.ZVector) {
9765       // The shift operators for the z vector extensions work basically
9766       // like general shifts, except that neither the LHS nor the RHS is
9767       // allowed to be a "vector bool".
9768       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9769         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9770           return InvalidOperands(Loc, LHS, RHS);
9771       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9772         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9773           return InvalidOperands(Loc, LHS, RHS);
9774     }
9775     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9776   }
9777 
9778   // Shifts don't perform usual arithmetic conversions, they just do integer
9779   // promotions on each operand. C99 6.5.7p3
9780 
9781   // For the LHS, do usual unary conversions, but then reset them away
9782   // if this is a compound assignment.
9783   ExprResult OldLHS = LHS;
9784   LHS = UsualUnaryConversions(LHS.get());
9785   if (LHS.isInvalid())
9786     return QualType();
9787   QualType LHSType = LHS.get()->getType();
9788   if (IsCompAssign) LHS = OldLHS;
9789 
9790   // The RHS is simpler.
9791   RHS = UsualUnaryConversions(RHS.get());
9792   if (RHS.isInvalid())
9793     return QualType();
9794   QualType RHSType = RHS.get()->getType();
9795 
9796   // C99 6.5.7p2: Each of the operands shall have integer type.
9797   if (!LHSType->hasIntegerRepresentation() ||
9798       !RHSType->hasIntegerRepresentation())
9799     return InvalidOperands(Loc, LHS, RHS);
9800 
9801   // C++0x: Don't allow scoped enums. FIXME: Use something better than
9802   // hasIntegerRepresentation() above instead of this.
9803   if (isScopedEnumerationType(LHSType) ||
9804       isScopedEnumerationType(RHSType)) {
9805     return InvalidOperands(Loc, LHS, RHS);
9806   }
9807   // Sanity-check shift operands
9808   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
9809 
9810   // "The type of the result is that of the promoted left operand."
9811   return LHSType;
9812 }
9813 
9814 /// If two different enums are compared, raise a warning.
9815 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
9816                                 Expr *RHS) {
9817   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
9818   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
9819 
9820   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
9821   if (!LHSEnumType)
9822     return;
9823   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
9824   if (!RHSEnumType)
9825     return;
9826 
9827   // Ignore anonymous enums.
9828   if (!LHSEnumType->getDecl()->getIdentifier() &&
9829       !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9830     return;
9831   if (!RHSEnumType->getDecl()->getIdentifier() &&
9832       !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9833     return;
9834 
9835   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
9836     return;
9837 
9838   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
9839       << LHSStrippedType << RHSStrippedType
9840       << LHS->getSourceRange() << RHS->getSourceRange();
9841 }
9842 
9843 /// Diagnose bad pointer comparisons.
9844 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
9845                                               ExprResult &LHS, ExprResult &RHS,
9846                                               bool IsError) {
9847   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9848                       : diag::ext_typecheck_comparison_of_distinct_pointers)
9849     << LHS.get()->getType() << RHS.get()->getType()
9850     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9851 }
9852 
9853 /// Returns false if the pointers are converted to a composite type,
9854 /// true otherwise.
9855 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
9856                                            ExprResult &LHS, ExprResult &RHS) {
9857   // C++ [expr.rel]p2:
9858   //   [...] Pointer conversions (4.10) and qualification
9859   //   conversions (4.4) are performed on pointer operands (or on
9860   //   a pointer operand and a null pointer constant) to bring
9861   //   them to their composite pointer type. [...]
9862   //
9863   // C++ [expr.eq]p1 uses the same notion for (in)equality
9864   // comparisons of pointers.
9865 
9866   QualType LHSType = LHS.get()->getType();
9867   QualType RHSType = RHS.get()->getType();
9868   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9869          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9870 
9871   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9872   if (T.isNull()) {
9873     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9874         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9875       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9876     else
9877       S.InvalidOperands(Loc, LHS, RHS);
9878     return true;
9879   }
9880 
9881   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9882   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9883   return false;
9884 }
9885 
9886 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9887                                                     ExprResult &LHS,
9888                                                     ExprResult &RHS,
9889                                                     bool IsError) {
9890   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9891                       : diag::ext_typecheck_comparison_of_fptr_to_void)
9892     << LHS.get()->getType() << RHS.get()->getType()
9893     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9894 }
9895 
9896 static bool isObjCObjectLiteral(ExprResult &E) {
9897   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9898   case Stmt::ObjCArrayLiteralClass:
9899   case Stmt::ObjCDictionaryLiteralClass:
9900   case Stmt::ObjCStringLiteralClass:
9901   case Stmt::ObjCBoxedExprClass:
9902     return true;
9903   default:
9904     // Note that ObjCBoolLiteral is NOT an object literal!
9905     return false;
9906   }
9907 }
9908 
9909 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9910   const ObjCObjectPointerType *Type =
9911     LHS->getType()->getAs<ObjCObjectPointerType>();
9912 
9913   // If this is not actually an Objective-C object, bail out.
9914   if (!Type)
9915     return false;
9916 
9917   // Get the LHS object's interface type.
9918   QualType InterfaceType = Type->getPointeeType();
9919 
9920   // If the RHS isn't an Objective-C object, bail out.
9921   if (!RHS->getType()->isObjCObjectPointerType())
9922     return false;
9923 
9924   // Try to find the -isEqual: method.
9925   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9926   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9927                                                       InterfaceType,
9928                                                       /*instance=*/true);
9929   if (!Method) {
9930     if (Type->isObjCIdType()) {
9931       // For 'id', just check the global pool.
9932       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9933                                                   /*receiverId=*/true);
9934     } else {
9935       // Check protocols.
9936       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9937                                              /*instance=*/true);
9938     }
9939   }
9940 
9941   if (!Method)
9942     return false;
9943 
9944   QualType T = Method->parameters()[0]->getType();
9945   if (!T->isObjCObjectPointerType())
9946     return false;
9947 
9948   QualType R = Method->getReturnType();
9949   if (!R->isScalarType())
9950     return false;
9951 
9952   return true;
9953 }
9954 
9955 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9956   FromE = FromE->IgnoreParenImpCasts();
9957   switch (FromE->getStmtClass()) {
9958     default:
9959       break;
9960     case Stmt::ObjCStringLiteralClass:
9961       // "string literal"
9962       return LK_String;
9963     case Stmt::ObjCArrayLiteralClass:
9964       // "array literal"
9965       return LK_Array;
9966     case Stmt::ObjCDictionaryLiteralClass:
9967       // "dictionary literal"
9968       return LK_Dictionary;
9969     case Stmt::BlockExprClass:
9970       return LK_Block;
9971     case Stmt::ObjCBoxedExprClass: {
9972       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9973       switch (Inner->getStmtClass()) {
9974         case Stmt::IntegerLiteralClass:
9975         case Stmt::FloatingLiteralClass:
9976         case Stmt::CharacterLiteralClass:
9977         case Stmt::ObjCBoolLiteralExprClass:
9978         case Stmt::CXXBoolLiteralExprClass:
9979           // "numeric literal"
9980           return LK_Numeric;
9981         case Stmt::ImplicitCastExprClass: {
9982           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9983           // Boolean literals can be represented by implicit casts.
9984           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9985             return LK_Numeric;
9986           break;
9987         }
9988         default:
9989           break;
9990       }
9991       return LK_Boxed;
9992     }
9993   }
9994   return LK_None;
9995 }
9996 
9997 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9998                                           ExprResult &LHS, ExprResult &RHS,
9999                                           BinaryOperator::Opcode Opc){
10000   Expr *Literal;
10001   Expr *Other;
10002   if (isObjCObjectLiteral(LHS)) {
10003     Literal = LHS.get();
10004     Other = RHS.get();
10005   } else {
10006     Literal = RHS.get();
10007     Other = LHS.get();
10008   }
10009 
10010   // Don't warn on comparisons against nil.
10011   Other = Other->IgnoreParenCasts();
10012   if (Other->isNullPointerConstant(S.getASTContext(),
10013                                    Expr::NPC_ValueDependentIsNotNull))
10014     return;
10015 
10016   // This should be kept in sync with warn_objc_literal_comparison.
10017   // LK_String should always be after the other literals, since it has its own
10018   // warning flag.
10019   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
10020   assert(LiteralKind != Sema::LK_Block);
10021   if (LiteralKind == Sema::LK_None) {
10022     llvm_unreachable("Unknown Objective-C object literal kind");
10023   }
10024 
10025   if (LiteralKind == Sema::LK_String)
10026     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
10027       << Literal->getSourceRange();
10028   else
10029     S.Diag(Loc, diag::warn_objc_literal_comparison)
10030       << LiteralKind << Literal->getSourceRange();
10031 
10032   if (BinaryOperator::isEqualityOp(Opc) &&
10033       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
10034     SourceLocation Start = LHS.get()->getBeginLoc();
10035     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
10036     CharSourceRange OpRange =
10037       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
10038 
10039     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
10040       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
10041       << FixItHint::CreateReplacement(OpRange, " isEqual:")
10042       << FixItHint::CreateInsertion(End, "]");
10043   }
10044 }
10045 
10046 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
10047 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
10048                                            ExprResult &RHS, SourceLocation Loc,
10049                                            BinaryOperatorKind Opc) {
10050   // Check that left hand side is !something.
10051   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
10052   if (!UO || UO->getOpcode() != UO_LNot) return;
10053 
10054   // Only check if the right hand side is non-bool arithmetic type.
10055   if (RHS.get()->isKnownToHaveBooleanValue()) return;
10056 
10057   // Make sure that the something in !something is not bool.
10058   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
10059   if (SubExpr->isKnownToHaveBooleanValue()) return;
10060 
10061   // Emit warning.
10062   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
10063   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
10064       << Loc << IsBitwiseOp;
10065 
10066   // First note suggest !(x < y)
10067   SourceLocation FirstOpen = SubExpr->getBeginLoc();
10068   SourceLocation FirstClose = RHS.get()->getEndLoc();
10069   FirstClose = S.getLocForEndOfToken(FirstClose);
10070   if (FirstClose.isInvalid())
10071     FirstOpen = SourceLocation();
10072   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
10073       << IsBitwiseOp
10074       << FixItHint::CreateInsertion(FirstOpen, "(")
10075       << FixItHint::CreateInsertion(FirstClose, ")");
10076 
10077   // Second note suggests (!x) < y
10078   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
10079   SourceLocation SecondClose = LHS.get()->getEndLoc();
10080   SecondClose = S.getLocForEndOfToken(SecondClose);
10081   if (SecondClose.isInvalid())
10082     SecondOpen = SourceLocation();
10083   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
10084       << FixItHint::CreateInsertion(SecondOpen, "(")
10085       << FixItHint::CreateInsertion(SecondClose, ")");
10086 }
10087 
10088 // Get the decl for a simple expression: a reference to a variable,
10089 // an implicit C++ field reference, or an implicit ObjC ivar reference.
10090 static ValueDecl *getCompareDecl(Expr *E) {
10091   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
10092     return DR->getDecl();
10093   if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
10094     if (Ivar->isFreeIvar())
10095       return Ivar->getDecl();
10096   }
10097   if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
10098     if (Mem->isImplicitAccess())
10099       return Mem->getMemberDecl();
10100   }
10101   return nullptr;
10102 }
10103 
10104 /// Diagnose some forms of syntactically-obvious tautological comparison.
10105 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
10106                                            Expr *LHS, Expr *RHS,
10107                                            BinaryOperatorKind Opc) {
10108   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
10109   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
10110 
10111   QualType LHSType = LHS->getType();
10112   QualType RHSType = RHS->getType();
10113   if (LHSType->hasFloatingRepresentation() ||
10114       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
10115       LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() ||
10116       S.inTemplateInstantiation())
10117     return;
10118 
10119   // Comparisons between two array types are ill-formed for operator<=>, so
10120   // we shouldn't emit any additional warnings about it.
10121   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
10122     return;
10123 
10124   // For non-floating point types, check for self-comparisons of the form
10125   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10126   // often indicate logic errors in the program.
10127   //
10128   // NOTE: Don't warn about comparison expressions resulting from macro
10129   // expansion. Also don't warn about comparisons which are only self
10130   // comparisons within a template instantiation. The warnings should catch
10131   // obvious cases in the definition of the template anyways. The idea is to
10132   // warn when the typed comparison operator will always evaluate to the same
10133   // result.
10134   ValueDecl *DL = getCompareDecl(LHSStripped);
10135   ValueDecl *DR = getCompareDecl(RHSStripped);
10136   if (DL && DR && declaresSameEntity(DL, DR)) {
10137     StringRef Result;
10138     switch (Opc) {
10139     case BO_EQ: case BO_LE: case BO_GE:
10140       Result = "true";
10141       break;
10142     case BO_NE: case BO_LT: case BO_GT:
10143       Result = "false";
10144       break;
10145     case BO_Cmp:
10146       Result = "'std::strong_ordering::equal'";
10147       break;
10148     default:
10149       break;
10150     }
10151     S.DiagRuntimeBehavior(Loc, nullptr,
10152                           S.PDiag(diag::warn_comparison_always)
10153                               << 0 /*self-comparison*/ << !Result.empty()
10154                               << Result);
10155   } else if (DL && DR &&
10156              DL->getType()->isArrayType() && DR->getType()->isArrayType() &&
10157              !DL->isWeak() && !DR->isWeak()) {
10158     // What is it always going to evaluate to?
10159     StringRef Result;
10160     switch(Opc) {
10161     case BO_EQ: // e.g. array1 == array2
10162       Result = "false";
10163       break;
10164     case BO_NE: // e.g. array1 != array2
10165       Result = "true";
10166       break;
10167     default: // e.g. array1 <= array2
10168       // The best we can say is 'a constant'
10169       break;
10170     }
10171     S.DiagRuntimeBehavior(Loc, nullptr,
10172                           S.PDiag(diag::warn_comparison_always)
10173                               << 1 /*array comparison*/
10174                               << !Result.empty() << Result);
10175   }
10176 
10177   if (isa<CastExpr>(LHSStripped))
10178     LHSStripped = LHSStripped->IgnoreParenCasts();
10179   if (isa<CastExpr>(RHSStripped))
10180     RHSStripped = RHSStripped->IgnoreParenCasts();
10181 
10182   // Warn about comparisons against a string constant (unless the other
10183   // operand is null); the user probably wants strcmp.
10184   Expr *LiteralString = nullptr;
10185   Expr *LiteralStringStripped = nullptr;
10186   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
10187       !RHSStripped->isNullPointerConstant(S.Context,
10188                                           Expr::NPC_ValueDependentIsNull)) {
10189     LiteralString = LHS;
10190     LiteralStringStripped = LHSStripped;
10191   } else if ((isa<StringLiteral>(RHSStripped) ||
10192               isa<ObjCEncodeExpr>(RHSStripped)) &&
10193              !LHSStripped->isNullPointerConstant(S.Context,
10194                                           Expr::NPC_ValueDependentIsNull)) {
10195     LiteralString = RHS;
10196     LiteralStringStripped = RHSStripped;
10197   }
10198 
10199   if (LiteralString) {
10200     S.DiagRuntimeBehavior(Loc, nullptr,
10201                           S.PDiag(diag::warn_stringcompare)
10202                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
10203                               << LiteralString->getSourceRange());
10204   }
10205 }
10206 
10207 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
10208   switch (CK) {
10209   default: {
10210 #ifndef NDEBUG
10211     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
10212                  << "\n";
10213 #endif
10214     llvm_unreachable("unhandled cast kind");
10215   }
10216   case CK_UserDefinedConversion:
10217     return ICK_Identity;
10218   case CK_LValueToRValue:
10219     return ICK_Lvalue_To_Rvalue;
10220   case CK_ArrayToPointerDecay:
10221     return ICK_Array_To_Pointer;
10222   case CK_FunctionToPointerDecay:
10223     return ICK_Function_To_Pointer;
10224   case CK_IntegralCast:
10225     return ICK_Integral_Conversion;
10226   case CK_FloatingCast:
10227     return ICK_Floating_Conversion;
10228   case CK_IntegralToFloating:
10229   case CK_FloatingToIntegral:
10230     return ICK_Floating_Integral;
10231   case CK_IntegralComplexCast:
10232   case CK_FloatingComplexCast:
10233   case CK_FloatingComplexToIntegralComplex:
10234   case CK_IntegralComplexToFloatingComplex:
10235     return ICK_Complex_Conversion;
10236   case CK_FloatingComplexToReal:
10237   case CK_FloatingRealToComplex:
10238   case CK_IntegralComplexToReal:
10239   case CK_IntegralRealToComplex:
10240     return ICK_Complex_Real;
10241   }
10242 }
10243 
10244 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
10245                                              QualType FromType,
10246                                              SourceLocation Loc) {
10247   // Check for a narrowing implicit conversion.
10248   StandardConversionSequence SCS;
10249   SCS.setAsIdentityConversion();
10250   SCS.setToType(0, FromType);
10251   SCS.setToType(1, ToType);
10252   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10253     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
10254 
10255   APValue PreNarrowingValue;
10256   QualType PreNarrowingType;
10257   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
10258                                PreNarrowingType,
10259                                /*IgnoreFloatToIntegralConversion*/ true)) {
10260   case NK_Dependent_Narrowing:
10261     // Implicit conversion to a narrower type, but the expression is
10262     // value-dependent so we can't tell whether it's actually narrowing.
10263   case NK_Not_Narrowing:
10264     return false;
10265 
10266   case NK_Constant_Narrowing:
10267     // Implicit conversion to a narrower type, and the value is not a constant
10268     // expression.
10269     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10270         << /*Constant*/ 1
10271         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
10272     return true;
10273 
10274   case NK_Variable_Narrowing:
10275     // Implicit conversion to a narrower type, and the value is not a constant
10276     // expression.
10277   case NK_Type_Narrowing:
10278     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10279         << /*Constant*/ 0 << FromType << ToType;
10280     // TODO: It's not a constant expression, but what if the user intended it
10281     // to be? Can we produce notes to help them figure out why it isn't?
10282     return true;
10283   }
10284   llvm_unreachable("unhandled case in switch");
10285 }
10286 
10287 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
10288                                                          ExprResult &LHS,
10289                                                          ExprResult &RHS,
10290                                                          SourceLocation Loc) {
10291   using CCT = ComparisonCategoryType;
10292 
10293   QualType LHSType = LHS.get()->getType();
10294   QualType RHSType = RHS.get()->getType();
10295   // Dig out the original argument type and expression before implicit casts
10296   // were applied. These are the types/expressions we need to check the
10297   // [expr.spaceship] requirements against.
10298   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
10299   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
10300   QualType LHSStrippedType = LHSStripped.get()->getType();
10301   QualType RHSStrippedType = RHSStripped.get()->getType();
10302 
10303   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
10304   // other is not, the program is ill-formed.
10305   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
10306     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10307     return QualType();
10308   }
10309 
10310   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
10311                     RHSStrippedType->isEnumeralType();
10312   if (NumEnumArgs == 1) {
10313     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
10314     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
10315     if (OtherTy->hasFloatingRepresentation()) {
10316       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10317       return QualType();
10318     }
10319   }
10320   if (NumEnumArgs == 2) {
10321     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
10322     // type E, the operator yields the result of converting the operands
10323     // to the underlying type of E and applying <=> to the converted operands.
10324     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
10325       S.InvalidOperands(Loc, LHS, RHS);
10326       return QualType();
10327     }
10328     QualType IntType =
10329         LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType();
10330     assert(IntType->isArithmeticType());
10331 
10332     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
10333     // promote the boolean type, and all other promotable integer types, to
10334     // avoid this.
10335     if (IntType->isPromotableIntegerType())
10336       IntType = S.Context.getPromotedIntegerType(IntType);
10337 
10338     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
10339     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
10340     LHSType = RHSType = IntType;
10341   }
10342 
10343   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
10344   // usual arithmetic conversions are applied to the operands.
10345   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10346   if (LHS.isInvalid() || RHS.isInvalid())
10347     return QualType();
10348   if (Type.isNull())
10349     return S.InvalidOperands(Loc, LHS, RHS);
10350   assert(Type->isArithmeticType() || Type->isEnumeralType());
10351 
10352   bool HasNarrowing = checkThreeWayNarrowingConversion(
10353       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
10354   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
10355                                                    RHS.get()->getBeginLoc());
10356   if (HasNarrowing)
10357     return QualType();
10358 
10359   assert(!Type.isNull() && "composite type for <=> has not been set");
10360 
10361   auto TypeKind = [&]() {
10362     if (const ComplexType *CT = Type->getAs<ComplexType>()) {
10363       if (CT->getElementType()->hasFloatingRepresentation())
10364         return CCT::WeakEquality;
10365       return CCT::StrongEquality;
10366     }
10367     if (Type->isIntegralOrEnumerationType())
10368       return CCT::StrongOrdering;
10369     if (Type->hasFloatingRepresentation())
10370       return CCT::PartialOrdering;
10371     llvm_unreachable("other types are unimplemented");
10372   }();
10373 
10374   return S.CheckComparisonCategoryType(TypeKind, Loc);
10375 }
10376 
10377 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
10378                                                  ExprResult &RHS,
10379                                                  SourceLocation Loc,
10380                                                  BinaryOperatorKind Opc) {
10381   if (Opc == BO_Cmp)
10382     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
10383 
10384   // C99 6.5.8p3 / C99 6.5.9p4
10385   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10386   if (LHS.isInvalid() || RHS.isInvalid())
10387     return QualType();
10388   if (Type.isNull())
10389     return S.InvalidOperands(Loc, LHS, RHS);
10390   assert(Type->isArithmeticType() || Type->isEnumeralType());
10391 
10392   checkEnumComparison(S, Loc, LHS.get(), RHS.get());
10393 
10394   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
10395     return S.InvalidOperands(Loc, LHS, RHS);
10396 
10397   // Check for comparisons of floating point operands using != and ==.
10398   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
10399     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
10400 
10401   // The result of comparisons is 'bool' in C++, 'int' in C.
10402   return S.Context.getLogicalOperationType();
10403 }
10404 
10405 // C99 6.5.8, C++ [expr.rel]
10406 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
10407                                     SourceLocation Loc,
10408                                     BinaryOperatorKind Opc) {
10409   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
10410   bool IsThreeWay = Opc == BO_Cmp;
10411   auto IsAnyPointerType = [](ExprResult E) {
10412     QualType Ty = E.get()->getType();
10413     return Ty->isPointerType() || Ty->isMemberPointerType();
10414   };
10415 
10416   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
10417   // type, array-to-pointer, ..., conversions are performed on both operands to
10418   // bring them to their composite type.
10419   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
10420   // any type-related checks.
10421   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
10422     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10423     if (LHS.isInvalid())
10424       return QualType();
10425     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10426     if (RHS.isInvalid())
10427       return QualType();
10428   } else {
10429     LHS = DefaultLvalueConversion(LHS.get());
10430     if (LHS.isInvalid())
10431       return QualType();
10432     RHS = DefaultLvalueConversion(RHS.get());
10433     if (RHS.isInvalid())
10434       return QualType();
10435   }
10436 
10437   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
10438 
10439   // Handle vector comparisons separately.
10440   if (LHS.get()->getType()->isVectorType() ||
10441       RHS.get()->getType()->isVectorType())
10442     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
10443 
10444   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10445   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10446 
10447   QualType LHSType = LHS.get()->getType();
10448   QualType RHSType = RHS.get()->getType();
10449   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
10450       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
10451     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
10452 
10453   const Expr::NullPointerConstantKind LHSNullKind =
10454       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10455   const Expr::NullPointerConstantKind RHSNullKind =
10456       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10457   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
10458   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
10459 
10460   auto computeResultTy = [&]() {
10461     if (Opc != BO_Cmp)
10462       return Context.getLogicalOperationType();
10463     assert(getLangOpts().CPlusPlus);
10464     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
10465 
10466     QualType CompositeTy = LHS.get()->getType();
10467     assert(!CompositeTy->isReferenceType());
10468 
10469     auto buildResultTy = [&](ComparisonCategoryType Kind) {
10470       return CheckComparisonCategoryType(Kind, Loc);
10471     };
10472 
10473     // C++2a [expr.spaceship]p7: If the composite pointer type is a function
10474     // pointer type, a pointer-to-member type, or std::nullptr_t, the
10475     // result is of type std::strong_equality
10476     if (CompositeTy->isFunctionPointerType() ||
10477         CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType())
10478       // FIXME: consider making the function pointer case produce
10479       // strong_ordering not strong_equality, per P0946R0-Jax18 discussion
10480       // and direction polls
10481       return buildResultTy(ComparisonCategoryType::StrongEquality);
10482 
10483     // C++2a [expr.spaceship]p8: If the composite pointer type is an object
10484     // pointer type, p <=> q is of type std::strong_ordering.
10485     if (CompositeTy->isPointerType()) {
10486       // P0946R0: Comparisons between a null pointer constant and an object
10487       // pointer result in std::strong_equality
10488       if (LHSIsNull != RHSIsNull)
10489         return buildResultTy(ComparisonCategoryType::StrongEquality);
10490       return buildResultTy(ComparisonCategoryType::StrongOrdering);
10491     }
10492     // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed.
10493     // TODO: Extend support for operator<=> to ObjC types.
10494     return InvalidOperands(Loc, LHS, RHS);
10495   };
10496 
10497 
10498   if (!IsRelational && LHSIsNull != RHSIsNull) {
10499     bool IsEquality = Opc == BO_EQ;
10500     if (RHSIsNull)
10501       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
10502                                    RHS.get()->getSourceRange());
10503     else
10504       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
10505                                    LHS.get()->getSourceRange());
10506   }
10507 
10508   if ((LHSType->isIntegerType() && !LHSIsNull) ||
10509       (RHSType->isIntegerType() && !RHSIsNull)) {
10510     // Skip normal pointer conversion checks in this case; we have better
10511     // diagnostics for this below.
10512   } else if (getLangOpts().CPlusPlus) {
10513     // Equality comparison of a function pointer to a void pointer is invalid,
10514     // but we allow it as an extension.
10515     // FIXME: If we really want to allow this, should it be part of composite
10516     // pointer type computation so it works in conditionals too?
10517     if (!IsRelational &&
10518         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
10519          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
10520       // This is a gcc extension compatibility comparison.
10521       // In a SFINAE context, we treat this as a hard error to maintain
10522       // conformance with the C++ standard.
10523       diagnoseFunctionPointerToVoidComparison(
10524           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
10525 
10526       if (isSFINAEContext())
10527         return QualType();
10528 
10529       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10530       return computeResultTy();
10531     }
10532 
10533     // C++ [expr.eq]p2:
10534     //   If at least one operand is a pointer [...] bring them to their
10535     //   composite pointer type.
10536     // C++ [expr.spaceship]p6
10537     //  If at least one of the operands is of pointer type, [...] bring them
10538     //  to their composite pointer type.
10539     // C++ [expr.rel]p2:
10540     //   If both operands are pointers, [...] bring them to their composite
10541     //   pointer type.
10542     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
10543             (IsRelational ? 2 : 1) &&
10544         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
10545                                          RHSType->isObjCObjectPointerType()))) {
10546       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10547         return QualType();
10548       return computeResultTy();
10549     }
10550   } else if (LHSType->isPointerType() &&
10551              RHSType->isPointerType()) { // C99 6.5.8p2
10552     // All of the following pointer-related warnings are GCC extensions, except
10553     // when handling null pointer constants.
10554     QualType LCanPointeeTy =
10555       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10556     QualType RCanPointeeTy =
10557       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10558 
10559     // C99 6.5.9p2 and C99 6.5.8p2
10560     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
10561                                    RCanPointeeTy.getUnqualifiedType())) {
10562       // Valid unless a relational comparison of function pointers
10563       if (IsRelational && LCanPointeeTy->isFunctionType()) {
10564         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
10565           << LHSType << RHSType << LHS.get()->getSourceRange()
10566           << RHS.get()->getSourceRange();
10567       }
10568     } else if (!IsRelational &&
10569                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
10570       // Valid unless comparison between non-null pointer and function pointer
10571       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
10572           && !LHSIsNull && !RHSIsNull)
10573         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
10574                                                 /*isError*/false);
10575     } else {
10576       // Invalid
10577       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
10578     }
10579     if (LCanPointeeTy != RCanPointeeTy) {
10580       // Treat NULL constant as a special case in OpenCL.
10581       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
10582         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
10583         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
10584           Diag(Loc,
10585                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10586               << LHSType << RHSType << 0 /* comparison */
10587               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10588         }
10589       }
10590       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
10591       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
10592       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
10593                                                : CK_BitCast;
10594       if (LHSIsNull && !RHSIsNull)
10595         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
10596       else
10597         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
10598     }
10599     return computeResultTy();
10600   }
10601 
10602   if (getLangOpts().CPlusPlus) {
10603     // C++ [expr.eq]p4:
10604     //   Two operands of type std::nullptr_t or one operand of type
10605     //   std::nullptr_t and the other a null pointer constant compare equal.
10606     if (!IsRelational && LHSIsNull && RHSIsNull) {
10607       if (LHSType->isNullPtrType()) {
10608         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10609         return computeResultTy();
10610       }
10611       if (RHSType->isNullPtrType()) {
10612         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10613         return computeResultTy();
10614       }
10615     }
10616 
10617     // Comparison of Objective-C pointers and block pointers against nullptr_t.
10618     // These aren't covered by the composite pointer type rules.
10619     if (!IsRelational && RHSType->isNullPtrType() &&
10620         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
10621       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10622       return computeResultTy();
10623     }
10624     if (!IsRelational && LHSType->isNullPtrType() &&
10625         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
10626       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10627       return computeResultTy();
10628     }
10629 
10630     if (IsRelational &&
10631         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
10632          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
10633       // HACK: Relational comparison of nullptr_t against a pointer type is
10634       // invalid per DR583, but we allow it within std::less<> and friends,
10635       // since otherwise common uses of it break.
10636       // FIXME: Consider removing this hack once LWG fixes std::less<> and
10637       // friends to have std::nullptr_t overload candidates.
10638       DeclContext *DC = CurContext;
10639       if (isa<FunctionDecl>(DC))
10640         DC = DC->getParent();
10641       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
10642         if (CTSD->isInStdNamespace() &&
10643             llvm::StringSwitch<bool>(CTSD->getName())
10644                 .Cases("less", "less_equal", "greater", "greater_equal", true)
10645                 .Default(false)) {
10646           if (RHSType->isNullPtrType())
10647             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10648           else
10649             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10650           return computeResultTy();
10651         }
10652       }
10653     }
10654 
10655     // C++ [expr.eq]p2:
10656     //   If at least one operand is a pointer to member, [...] bring them to
10657     //   their composite pointer type.
10658     if (!IsRelational &&
10659         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
10660       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10661         return QualType();
10662       else
10663         return computeResultTy();
10664     }
10665   }
10666 
10667   // Handle block pointer types.
10668   if (!IsRelational && LHSType->isBlockPointerType() &&
10669       RHSType->isBlockPointerType()) {
10670     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
10671     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
10672 
10673     if (!LHSIsNull && !RHSIsNull &&
10674         !Context.typesAreCompatible(lpointee, rpointee)) {
10675       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10676         << LHSType << RHSType << LHS.get()->getSourceRange()
10677         << RHS.get()->getSourceRange();
10678     }
10679     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10680     return computeResultTy();
10681   }
10682 
10683   // Allow block pointers to be compared with null pointer constants.
10684   if (!IsRelational
10685       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
10686           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
10687     if (!LHSIsNull && !RHSIsNull) {
10688       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
10689              ->getPointeeType()->isVoidType())
10690             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
10691                 ->getPointeeType()->isVoidType())))
10692         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10693           << LHSType << RHSType << LHS.get()->getSourceRange()
10694           << RHS.get()->getSourceRange();
10695     }
10696     if (LHSIsNull && !RHSIsNull)
10697       LHS = ImpCastExprToType(LHS.get(), RHSType,
10698                               RHSType->isPointerType() ? CK_BitCast
10699                                 : CK_AnyPointerToBlockPointerCast);
10700     else
10701       RHS = ImpCastExprToType(RHS.get(), LHSType,
10702                               LHSType->isPointerType() ? CK_BitCast
10703                                 : CK_AnyPointerToBlockPointerCast);
10704     return computeResultTy();
10705   }
10706 
10707   if (LHSType->isObjCObjectPointerType() ||
10708       RHSType->isObjCObjectPointerType()) {
10709     const PointerType *LPT = LHSType->getAs<PointerType>();
10710     const PointerType *RPT = RHSType->getAs<PointerType>();
10711     if (LPT || RPT) {
10712       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
10713       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
10714 
10715       if (!LPtrToVoid && !RPtrToVoid &&
10716           !Context.typesAreCompatible(LHSType, RHSType)) {
10717         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10718                                           /*isError*/false);
10719       }
10720       if (LHSIsNull && !RHSIsNull) {
10721         Expr *E = LHS.get();
10722         if (getLangOpts().ObjCAutoRefCount)
10723           CheckObjCConversion(SourceRange(), RHSType, E,
10724                               CCK_ImplicitConversion);
10725         LHS = ImpCastExprToType(E, RHSType,
10726                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10727       }
10728       else {
10729         Expr *E = RHS.get();
10730         if (getLangOpts().ObjCAutoRefCount)
10731           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
10732                               /*Diagnose=*/true,
10733                               /*DiagnoseCFAudited=*/false, Opc);
10734         RHS = ImpCastExprToType(E, LHSType,
10735                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10736       }
10737       return computeResultTy();
10738     }
10739     if (LHSType->isObjCObjectPointerType() &&
10740         RHSType->isObjCObjectPointerType()) {
10741       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
10742         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10743                                           /*isError*/false);
10744       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
10745         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
10746 
10747       if (LHSIsNull && !RHSIsNull)
10748         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10749       else
10750         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10751       return computeResultTy();
10752     }
10753 
10754     if (!IsRelational && LHSType->isBlockPointerType() &&
10755         RHSType->isBlockCompatibleObjCPointerType(Context)) {
10756       LHS = ImpCastExprToType(LHS.get(), RHSType,
10757                               CK_BlockPointerToObjCPointerCast);
10758       return computeResultTy();
10759     } else if (!IsRelational &&
10760                LHSType->isBlockCompatibleObjCPointerType(Context) &&
10761                RHSType->isBlockPointerType()) {
10762       RHS = ImpCastExprToType(RHS.get(), LHSType,
10763                               CK_BlockPointerToObjCPointerCast);
10764       return computeResultTy();
10765     }
10766   }
10767   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
10768       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
10769     unsigned DiagID = 0;
10770     bool isError = false;
10771     if (LangOpts.DebuggerSupport) {
10772       // Under a debugger, allow the comparison of pointers to integers,
10773       // since users tend to want to compare addresses.
10774     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
10775                (RHSIsNull && RHSType->isIntegerType())) {
10776       if (IsRelational) {
10777         isError = getLangOpts().CPlusPlus;
10778         DiagID =
10779           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
10780                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
10781       }
10782     } else if (getLangOpts().CPlusPlus) {
10783       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
10784       isError = true;
10785     } else if (IsRelational)
10786       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
10787     else
10788       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
10789 
10790     if (DiagID) {
10791       Diag(Loc, DiagID)
10792         << LHSType << RHSType << LHS.get()->getSourceRange()
10793         << RHS.get()->getSourceRange();
10794       if (isError)
10795         return QualType();
10796     }
10797 
10798     if (LHSType->isIntegerType())
10799       LHS = ImpCastExprToType(LHS.get(), RHSType,
10800                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10801     else
10802       RHS = ImpCastExprToType(RHS.get(), LHSType,
10803                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10804     return computeResultTy();
10805   }
10806 
10807   // Handle block pointers.
10808   if (!IsRelational && RHSIsNull
10809       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
10810     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10811     return computeResultTy();
10812   }
10813   if (!IsRelational && LHSIsNull
10814       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
10815     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10816     return computeResultTy();
10817   }
10818 
10819   if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
10820     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
10821       return computeResultTy();
10822     }
10823 
10824     if (LHSType->isQueueT() && RHSType->isQueueT()) {
10825       return computeResultTy();
10826     }
10827 
10828     if (LHSIsNull && RHSType->isQueueT()) {
10829       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10830       return computeResultTy();
10831     }
10832 
10833     if (LHSType->isQueueT() && RHSIsNull) {
10834       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10835       return computeResultTy();
10836     }
10837   }
10838 
10839   return InvalidOperands(Loc, LHS, RHS);
10840 }
10841 
10842 // Return a signed ext_vector_type that is of identical size and number of
10843 // elements. For floating point vectors, return an integer type of identical
10844 // size and number of elements. In the non ext_vector_type case, search from
10845 // the largest type to the smallest type to avoid cases where long long == long,
10846 // where long gets picked over long long.
10847 QualType Sema::GetSignedVectorType(QualType V) {
10848   const VectorType *VTy = V->getAs<VectorType>();
10849   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
10850 
10851   if (isa<ExtVectorType>(VTy)) {
10852     if (TypeSize == Context.getTypeSize(Context.CharTy))
10853       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
10854     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10855       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
10856     else if (TypeSize == Context.getTypeSize(Context.IntTy))
10857       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
10858     else if (TypeSize == Context.getTypeSize(Context.LongTy))
10859       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
10860     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
10861            "Unhandled vector element size in vector compare");
10862     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
10863   }
10864 
10865   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
10866     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
10867                                  VectorType::GenericVector);
10868   else if (TypeSize == Context.getTypeSize(Context.LongTy))
10869     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
10870                                  VectorType::GenericVector);
10871   else if (TypeSize == Context.getTypeSize(Context.IntTy))
10872     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
10873                                  VectorType::GenericVector);
10874   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10875     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
10876                                  VectorType::GenericVector);
10877   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
10878          "Unhandled vector element size in vector compare");
10879   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
10880                                VectorType::GenericVector);
10881 }
10882 
10883 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
10884 /// operates on extended vector types.  Instead of producing an IntTy result,
10885 /// like a scalar comparison, a vector comparison produces a vector of integer
10886 /// types.
10887 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
10888                                           SourceLocation Loc,
10889                                           BinaryOperatorKind Opc) {
10890   // Check to make sure we're operating on vectors of the same type and width,
10891   // Allowing one side to be a scalar of element type.
10892   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
10893                               /*AllowBothBool*/true,
10894                               /*AllowBoolConversions*/getLangOpts().ZVector);
10895   if (vType.isNull())
10896     return vType;
10897 
10898   QualType LHSType = LHS.get()->getType();
10899 
10900   // If AltiVec, the comparison results in a numeric type, i.e.
10901   // bool for C++, int for C
10902   if (getLangOpts().AltiVec &&
10903       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
10904     return Context.getLogicalOperationType();
10905 
10906   // For non-floating point types, check for self-comparisons of the form
10907   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10908   // often indicate logic errors in the program.
10909   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10910 
10911   // Check for comparisons of floating point operands using != and ==.
10912   if (BinaryOperator::isEqualityOp(Opc) &&
10913       LHSType->hasFloatingRepresentation()) {
10914     assert(RHS.get()->getType()->hasFloatingRepresentation());
10915     CheckFloatComparison(Loc, LHS.get(), RHS.get());
10916   }
10917 
10918   // Return a signed type for the vector.
10919   return GetSignedVectorType(vType);
10920 }
10921 
10922 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10923                                           SourceLocation Loc) {
10924   // Ensure that either both operands are of the same vector type, or
10925   // one operand is of a vector type and the other is of its element type.
10926   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
10927                                        /*AllowBothBool*/true,
10928                                        /*AllowBoolConversions*/false);
10929   if (vType.isNull())
10930     return InvalidOperands(Loc, LHS, RHS);
10931   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
10932       !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
10933     return InvalidOperands(Loc, LHS, RHS);
10934   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
10935   //        usage of the logical operators && and || with vectors in C. This
10936   //        check could be notionally dropped.
10937   if (!getLangOpts().CPlusPlus &&
10938       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
10939     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
10940 
10941   return GetSignedVectorType(LHS.get()->getType());
10942 }
10943 
10944 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
10945                                            SourceLocation Loc,
10946                                            BinaryOperatorKind Opc) {
10947   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
10948 
10949   bool IsCompAssign =
10950       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
10951 
10952   if (LHS.get()->getType()->isVectorType() ||
10953       RHS.get()->getType()->isVectorType()) {
10954     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10955         RHS.get()->getType()->hasIntegerRepresentation())
10956       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10957                         /*AllowBothBool*/true,
10958                         /*AllowBoolConversions*/getLangOpts().ZVector);
10959     return InvalidOperands(Loc, LHS, RHS);
10960   }
10961 
10962   if (Opc == BO_And)
10963     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10964 
10965   ExprResult LHSResult = LHS, RHSResult = RHS;
10966   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
10967                                                  IsCompAssign);
10968   if (LHSResult.isInvalid() || RHSResult.isInvalid())
10969     return QualType();
10970   LHS = LHSResult.get();
10971   RHS = RHSResult.get();
10972 
10973   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
10974     return compType;
10975   return InvalidOperands(Loc, LHS, RHS);
10976 }
10977 
10978 // C99 6.5.[13,14]
10979 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10980                                            SourceLocation Loc,
10981                                            BinaryOperatorKind Opc) {
10982   // Check vector operands differently.
10983   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
10984     return CheckVectorLogicalOperands(LHS, RHS, Loc);
10985 
10986   // Diagnose cases where the user write a logical and/or but probably meant a
10987   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
10988   // is a constant.
10989   if (LHS.get()->getType()->isIntegerType() &&
10990       !LHS.get()->getType()->isBooleanType() &&
10991       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
10992       // Don't warn in macros or template instantiations.
10993       !Loc.isMacroID() && !inTemplateInstantiation()) {
10994     // If the RHS can be constant folded, and if it constant folds to something
10995     // that isn't 0 or 1 (which indicate a potential logical operation that
10996     // happened to fold to true/false) then warn.
10997     // Parens on the RHS are ignored.
10998     Expr::EvalResult EVResult;
10999     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
11000       llvm::APSInt Result = EVResult.Val.getInt();
11001       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
11002            !RHS.get()->getExprLoc().isMacroID()) ||
11003           (Result != 0 && Result != 1)) {
11004         Diag(Loc, diag::warn_logical_instead_of_bitwise)
11005           << RHS.get()->getSourceRange()
11006           << (Opc == BO_LAnd ? "&&" : "||");
11007         // Suggest replacing the logical operator with the bitwise version
11008         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
11009             << (Opc == BO_LAnd ? "&" : "|")
11010             << FixItHint::CreateReplacement(SourceRange(
11011                                                  Loc, getLocForEndOfToken(Loc)),
11012                                             Opc == BO_LAnd ? "&" : "|");
11013         if (Opc == BO_LAnd)
11014           // Suggest replacing "Foo() && kNonZero" with "Foo()"
11015           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
11016               << FixItHint::CreateRemoval(
11017                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
11018                                  RHS.get()->getEndLoc()));
11019       }
11020     }
11021   }
11022 
11023   if (!Context.getLangOpts().CPlusPlus) {
11024     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
11025     // not operate on the built-in scalar and vector float types.
11026     if (Context.getLangOpts().OpenCL &&
11027         Context.getLangOpts().OpenCLVersion < 120) {
11028       if (LHS.get()->getType()->isFloatingType() ||
11029           RHS.get()->getType()->isFloatingType())
11030         return InvalidOperands(Loc, LHS, RHS);
11031     }
11032 
11033     LHS = UsualUnaryConversions(LHS.get());
11034     if (LHS.isInvalid())
11035       return QualType();
11036 
11037     RHS = UsualUnaryConversions(RHS.get());
11038     if (RHS.isInvalid())
11039       return QualType();
11040 
11041     if (!LHS.get()->getType()->isScalarType() ||
11042         !RHS.get()->getType()->isScalarType())
11043       return InvalidOperands(Loc, LHS, RHS);
11044 
11045     return Context.IntTy;
11046   }
11047 
11048   // The following is safe because we only use this method for
11049   // non-overloadable operands.
11050 
11051   // C++ [expr.log.and]p1
11052   // C++ [expr.log.or]p1
11053   // The operands are both contextually converted to type bool.
11054   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
11055   if (LHSRes.isInvalid())
11056     return InvalidOperands(Loc, LHS, RHS);
11057   LHS = LHSRes;
11058 
11059   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
11060   if (RHSRes.isInvalid())
11061     return InvalidOperands(Loc, LHS, RHS);
11062   RHS = RHSRes;
11063 
11064   // C++ [expr.log.and]p2
11065   // C++ [expr.log.or]p2
11066   // The result is a bool.
11067   return Context.BoolTy;
11068 }
11069 
11070 static bool IsReadonlyMessage(Expr *E, Sema &S) {
11071   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11072   if (!ME) return false;
11073   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
11074   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
11075       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
11076   if (!Base) return false;
11077   return Base->getMethodDecl() != nullptr;
11078 }
11079 
11080 /// Is the given expression (which must be 'const') a reference to a
11081 /// variable which was originally non-const, but which has become
11082 /// 'const' due to being captured within a block?
11083 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
11084 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
11085   assert(E->isLValue() && E->getType().isConstQualified());
11086   E = E->IgnoreParens();
11087 
11088   // Must be a reference to a declaration from an enclosing scope.
11089   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
11090   if (!DRE) return NCCK_None;
11091   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
11092 
11093   // The declaration must be a variable which is not declared 'const'.
11094   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
11095   if (!var) return NCCK_None;
11096   if (var->getType().isConstQualified()) return NCCK_None;
11097   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
11098 
11099   // Decide whether the first capture was for a block or a lambda.
11100   DeclContext *DC = S.CurContext, *Prev = nullptr;
11101   // Decide whether the first capture was for a block or a lambda.
11102   while (DC) {
11103     // For init-capture, it is possible that the variable belongs to the
11104     // template pattern of the current context.
11105     if (auto *FD = dyn_cast<FunctionDecl>(DC))
11106       if (var->isInitCapture() &&
11107           FD->getTemplateInstantiationPattern() == var->getDeclContext())
11108         break;
11109     if (DC == var->getDeclContext())
11110       break;
11111     Prev = DC;
11112     DC = DC->getParent();
11113   }
11114   // Unless we have an init-capture, we've gone one step too far.
11115   if (!var->isInitCapture())
11116     DC = Prev;
11117   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
11118 }
11119 
11120 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
11121   Ty = Ty.getNonReferenceType();
11122   if (IsDereference && Ty->isPointerType())
11123     Ty = Ty->getPointeeType();
11124   return !Ty.isConstQualified();
11125 }
11126 
11127 // Update err_typecheck_assign_const and note_typecheck_assign_const
11128 // when this enum is changed.
11129 enum {
11130   ConstFunction,
11131   ConstVariable,
11132   ConstMember,
11133   ConstMethod,
11134   NestedConstMember,
11135   ConstUnknown,  // Keep as last element
11136 };
11137 
11138 /// Emit the "read-only variable not assignable" error and print notes to give
11139 /// more information about why the variable is not assignable, such as pointing
11140 /// to the declaration of a const variable, showing that a method is const, or
11141 /// that the function is returning a const reference.
11142 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
11143                                     SourceLocation Loc) {
11144   SourceRange ExprRange = E->getSourceRange();
11145 
11146   // Only emit one error on the first const found.  All other consts will emit
11147   // a note to the error.
11148   bool DiagnosticEmitted = false;
11149 
11150   // Track if the current expression is the result of a dereference, and if the
11151   // next checked expression is the result of a dereference.
11152   bool IsDereference = false;
11153   bool NextIsDereference = false;
11154 
11155   // Loop to process MemberExpr chains.
11156   while (true) {
11157     IsDereference = NextIsDereference;
11158 
11159     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
11160     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11161       NextIsDereference = ME->isArrow();
11162       const ValueDecl *VD = ME->getMemberDecl();
11163       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
11164         // Mutable fields can be modified even if the class is const.
11165         if (Field->isMutable()) {
11166           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
11167           break;
11168         }
11169 
11170         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
11171           if (!DiagnosticEmitted) {
11172             S.Diag(Loc, diag::err_typecheck_assign_const)
11173                 << ExprRange << ConstMember << false /*static*/ << Field
11174                 << Field->getType();
11175             DiagnosticEmitted = true;
11176           }
11177           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11178               << ConstMember << false /*static*/ << Field << Field->getType()
11179               << Field->getSourceRange();
11180         }
11181         E = ME->getBase();
11182         continue;
11183       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
11184         if (VDecl->getType().isConstQualified()) {
11185           if (!DiagnosticEmitted) {
11186             S.Diag(Loc, diag::err_typecheck_assign_const)
11187                 << ExprRange << ConstMember << true /*static*/ << VDecl
11188                 << VDecl->getType();
11189             DiagnosticEmitted = true;
11190           }
11191           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11192               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
11193               << VDecl->getSourceRange();
11194         }
11195         // Static fields do not inherit constness from parents.
11196         break;
11197       }
11198       break; // End MemberExpr
11199     } else if (const ArraySubscriptExpr *ASE =
11200                    dyn_cast<ArraySubscriptExpr>(E)) {
11201       E = ASE->getBase()->IgnoreParenImpCasts();
11202       continue;
11203     } else if (const ExtVectorElementExpr *EVE =
11204                    dyn_cast<ExtVectorElementExpr>(E)) {
11205       E = EVE->getBase()->IgnoreParenImpCasts();
11206       continue;
11207     }
11208     break;
11209   }
11210 
11211   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11212     // Function calls
11213     const FunctionDecl *FD = CE->getDirectCallee();
11214     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
11215       if (!DiagnosticEmitted) {
11216         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11217                                                       << ConstFunction << FD;
11218         DiagnosticEmitted = true;
11219       }
11220       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
11221              diag::note_typecheck_assign_const)
11222           << ConstFunction << FD << FD->getReturnType()
11223           << FD->getReturnTypeSourceRange();
11224     }
11225   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11226     // Point to variable declaration.
11227     if (const ValueDecl *VD = DRE->getDecl()) {
11228       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
11229         if (!DiagnosticEmitted) {
11230           S.Diag(Loc, diag::err_typecheck_assign_const)
11231               << ExprRange << ConstVariable << VD << VD->getType();
11232           DiagnosticEmitted = true;
11233         }
11234         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11235             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
11236       }
11237     }
11238   } else if (isa<CXXThisExpr>(E)) {
11239     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
11240       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
11241         if (MD->isConst()) {
11242           if (!DiagnosticEmitted) {
11243             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11244                                                           << ConstMethod << MD;
11245             DiagnosticEmitted = true;
11246           }
11247           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
11248               << ConstMethod << MD << MD->getSourceRange();
11249         }
11250       }
11251     }
11252   }
11253 
11254   if (DiagnosticEmitted)
11255     return;
11256 
11257   // Can't determine a more specific message, so display the generic error.
11258   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
11259 }
11260 
11261 enum OriginalExprKind {
11262   OEK_Variable,
11263   OEK_Member,
11264   OEK_LValue
11265 };
11266 
11267 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
11268                                          const RecordType *Ty,
11269                                          SourceLocation Loc, SourceRange Range,
11270                                          OriginalExprKind OEK,
11271                                          bool &DiagnosticEmitted) {
11272   std::vector<const RecordType *> RecordTypeList;
11273   RecordTypeList.push_back(Ty);
11274   unsigned NextToCheckIndex = 0;
11275   // We walk the record hierarchy breadth-first to ensure that we print
11276   // diagnostics in field nesting order.
11277   while (RecordTypeList.size() > NextToCheckIndex) {
11278     bool IsNested = NextToCheckIndex > 0;
11279     for (const FieldDecl *Field :
11280          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
11281       // First, check every field for constness.
11282       QualType FieldTy = Field->getType();
11283       if (FieldTy.isConstQualified()) {
11284         if (!DiagnosticEmitted) {
11285           S.Diag(Loc, diag::err_typecheck_assign_const)
11286               << Range << NestedConstMember << OEK << VD
11287               << IsNested << Field;
11288           DiagnosticEmitted = true;
11289         }
11290         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
11291             << NestedConstMember << IsNested << Field
11292             << FieldTy << Field->getSourceRange();
11293       }
11294 
11295       // Then we append it to the list to check next in order.
11296       FieldTy = FieldTy.getCanonicalType();
11297       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
11298         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
11299           RecordTypeList.push_back(FieldRecTy);
11300       }
11301     }
11302     ++NextToCheckIndex;
11303   }
11304 }
11305 
11306 /// Emit an error for the case where a record we are trying to assign to has a
11307 /// const-qualified field somewhere in its hierarchy.
11308 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
11309                                          SourceLocation Loc) {
11310   QualType Ty = E->getType();
11311   assert(Ty->isRecordType() && "lvalue was not record?");
11312   SourceRange Range = E->getSourceRange();
11313   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
11314   bool DiagEmitted = false;
11315 
11316   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
11317     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
11318             Range, OEK_Member, DiagEmitted);
11319   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11320     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
11321             Range, OEK_Variable, DiagEmitted);
11322   else
11323     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
11324             Range, OEK_LValue, DiagEmitted);
11325   if (!DiagEmitted)
11326     DiagnoseConstAssignment(S, E, Loc);
11327 }
11328 
11329 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
11330 /// emit an error and return true.  If so, return false.
11331 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
11332   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
11333 
11334   S.CheckShadowingDeclModification(E, Loc);
11335 
11336   SourceLocation OrigLoc = Loc;
11337   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
11338                                                               &Loc);
11339   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
11340     IsLV = Expr::MLV_InvalidMessageExpression;
11341   if (IsLV == Expr::MLV_Valid)
11342     return false;
11343 
11344   unsigned DiagID = 0;
11345   bool NeedType = false;
11346   switch (IsLV) { // C99 6.5.16p2
11347   case Expr::MLV_ConstQualified:
11348     // Use a specialized diagnostic when we're assigning to an object
11349     // from an enclosing function or block.
11350     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
11351       if (NCCK == NCCK_Block)
11352         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
11353       else
11354         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
11355       break;
11356     }
11357 
11358     // In ARC, use some specialized diagnostics for occasions where we
11359     // infer 'const'.  These are always pseudo-strong variables.
11360     if (S.getLangOpts().ObjCAutoRefCount) {
11361       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
11362       if (declRef && isa<VarDecl>(declRef->getDecl())) {
11363         VarDecl *var = cast<VarDecl>(declRef->getDecl());
11364 
11365         // Use the normal diagnostic if it's pseudo-__strong but the
11366         // user actually wrote 'const'.
11367         if (var->isARCPseudoStrong() &&
11368             (!var->getTypeSourceInfo() ||
11369              !var->getTypeSourceInfo()->getType().isConstQualified())) {
11370           // There are three pseudo-strong cases:
11371           //  - self
11372           ObjCMethodDecl *method = S.getCurMethodDecl();
11373           if (method && var == method->getSelfDecl()) {
11374             DiagID = method->isClassMethod()
11375               ? diag::err_typecheck_arc_assign_self_class_method
11376               : diag::err_typecheck_arc_assign_self;
11377 
11378           //  - Objective-C externally_retained attribute.
11379           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
11380                      isa<ParmVarDecl>(var)) {
11381             DiagID = diag::err_typecheck_arc_assign_externally_retained;
11382 
11383           //  - fast enumeration variables
11384           } else {
11385             DiagID = diag::err_typecheck_arr_assign_enumeration;
11386           }
11387 
11388           SourceRange Assign;
11389           if (Loc != OrigLoc)
11390             Assign = SourceRange(OrigLoc, OrigLoc);
11391           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11392           // We need to preserve the AST regardless, so migration tool
11393           // can do its job.
11394           return false;
11395         }
11396       }
11397     }
11398 
11399     // If none of the special cases above are triggered, then this is a
11400     // simple const assignment.
11401     if (DiagID == 0) {
11402       DiagnoseConstAssignment(S, E, Loc);
11403       return true;
11404     }
11405 
11406     break;
11407   case Expr::MLV_ConstAddrSpace:
11408     DiagnoseConstAssignment(S, E, Loc);
11409     return true;
11410   case Expr::MLV_ConstQualifiedField:
11411     DiagnoseRecursiveConstFields(S, E, Loc);
11412     return true;
11413   case Expr::MLV_ArrayType:
11414   case Expr::MLV_ArrayTemporary:
11415     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
11416     NeedType = true;
11417     break;
11418   case Expr::MLV_NotObjectType:
11419     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
11420     NeedType = true;
11421     break;
11422   case Expr::MLV_LValueCast:
11423     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
11424     break;
11425   case Expr::MLV_Valid:
11426     llvm_unreachable("did not take early return for MLV_Valid");
11427   case Expr::MLV_InvalidExpression:
11428   case Expr::MLV_MemberFunction:
11429   case Expr::MLV_ClassTemporary:
11430     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
11431     break;
11432   case Expr::MLV_IncompleteType:
11433   case Expr::MLV_IncompleteVoidType:
11434     return S.RequireCompleteType(Loc, E->getType(),
11435              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
11436   case Expr::MLV_DuplicateVectorComponents:
11437     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
11438     break;
11439   case Expr::MLV_NoSetterProperty:
11440     llvm_unreachable("readonly properties should be processed differently");
11441   case Expr::MLV_InvalidMessageExpression:
11442     DiagID = diag::err_readonly_message_assignment;
11443     break;
11444   case Expr::MLV_SubObjCPropertySetting:
11445     DiagID = diag::err_no_subobject_property_setting;
11446     break;
11447   }
11448 
11449   SourceRange Assign;
11450   if (Loc != OrigLoc)
11451     Assign = SourceRange(OrigLoc, OrigLoc);
11452   if (NeedType)
11453     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
11454   else
11455     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11456   return true;
11457 }
11458 
11459 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
11460                                          SourceLocation Loc,
11461                                          Sema &Sema) {
11462   if (Sema.inTemplateInstantiation())
11463     return;
11464   if (Sema.isUnevaluatedContext())
11465     return;
11466   if (Loc.isInvalid() || Loc.isMacroID())
11467     return;
11468   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
11469     return;
11470 
11471   // C / C++ fields
11472   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
11473   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
11474   if (ML && MR) {
11475     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
11476       return;
11477     const ValueDecl *LHSDecl =
11478         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
11479     const ValueDecl *RHSDecl =
11480         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
11481     if (LHSDecl != RHSDecl)
11482       return;
11483     if (LHSDecl->getType().isVolatileQualified())
11484       return;
11485     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11486       if (RefTy->getPointeeType().isVolatileQualified())
11487         return;
11488 
11489     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
11490   }
11491 
11492   // Objective-C instance variables
11493   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
11494   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
11495   if (OL && OR && OL->getDecl() == OR->getDecl()) {
11496     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
11497     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
11498     if (RL && RR && RL->getDecl() == RR->getDecl())
11499       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
11500   }
11501 }
11502 
11503 // C99 6.5.16.1
11504 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
11505                                        SourceLocation Loc,
11506                                        QualType CompoundType) {
11507   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
11508 
11509   // Verify that LHS is a modifiable lvalue, and emit error if not.
11510   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
11511     return QualType();
11512 
11513   QualType LHSType = LHSExpr->getType();
11514   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
11515                                              CompoundType;
11516   // OpenCL v1.2 s6.1.1.1 p2:
11517   // The half data type can only be used to declare a pointer to a buffer that
11518   // contains half values
11519   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
11520     LHSType->isHalfType()) {
11521     Diag(Loc, diag::err_opencl_half_load_store) << 1
11522         << LHSType.getUnqualifiedType();
11523     return QualType();
11524   }
11525 
11526   AssignConvertType ConvTy;
11527   if (CompoundType.isNull()) {
11528     Expr *RHSCheck = RHS.get();
11529 
11530     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
11531 
11532     QualType LHSTy(LHSType);
11533     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
11534     if (RHS.isInvalid())
11535       return QualType();
11536     // Special case of NSObject attributes on c-style pointer types.
11537     if (ConvTy == IncompatiblePointer &&
11538         ((Context.isObjCNSObjectType(LHSType) &&
11539           RHSType->isObjCObjectPointerType()) ||
11540          (Context.isObjCNSObjectType(RHSType) &&
11541           LHSType->isObjCObjectPointerType())))
11542       ConvTy = Compatible;
11543 
11544     if (ConvTy == Compatible &&
11545         LHSType->isObjCObjectType())
11546         Diag(Loc, diag::err_objc_object_assignment)
11547           << LHSType;
11548 
11549     // If the RHS is a unary plus or minus, check to see if they = and + are
11550     // right next to each other.  If so, the user may have typo'd "x =+ 4"
11551     // instead of "x += 4".
11552     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
11553       RHSCheck = ICE->getSubExpr();
11554     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
11555       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
11556           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
11557           // Only if the two operators are exactly adjacent.
11558           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
11559           // And there is a space or other character before the subexpr of the
11560           // unary +/-.  We don't want to warn on "x=-1".
11561           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
11562           UO->getSubExpr()->getBeginLoc().isFileID()) {
11563         Diag(Loc, diag::warn_not_compound_assign)
11564           << (UO->getOpcode() == UO_Plus ? "+" : "-")
11565           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
11566       }
11567     }
11568 
11569     if (ConvTy == Compatible) {
11570       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
11571         // Warn about retain cycles where a block captures the LHS, but
11572         // not if the LHS is a simple variable into which the block is
11573         // being stored...unless that variable can be captured by reference!
11574         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
11575         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
11576         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
11577           checkRetainCycles(LHSExpr, RHS.get());
11578       }
11579 
11580       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
11581           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
11582         // It is safe to assign a weak reference into a strong variable.
11583         // Although this code can still have problems:
11584         //   id x = self.weakProp;
11585         //   id y = self.weakProp;
11586         // we do not warn to warn spuriously when 'x' and 'y' are on separate
11587         // paths through the function. This should be revisited if
11588         // -Wrepeated-use-of-weak is made flow-sensitive.
11589         // For ObjCWeak only, we do not warn if the assign is to a non-weak
11590         // variable, which will be valid for the current autorelease scope.
11591         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11592                              RHS.get()->getBeginLoc()))
11593           getCurFunction()->markSafeWeakUse(RHS.get());
11594 
11595       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
11596         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
11597       }
11598     }
11599   } else {
11600     // Compound assignment "x += y"
11601     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
11602   }
11603 
11604   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
11605                                RHS.get(), AA_Assigning))
11606     return QualType();
11607 
11608   CheckForNullPointerDereference(*this, LHSExpr);
11609 
11610   // C99 6.5.16p3: The type of an assignment expression is the type of the
11611   // left operand unless the left operand has qualified type, in which case
11612   // it is the unqualified version of the type of the left operand.
11613   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
11614   // is converted to the type of the assignment expression (above).
11615   // C++ 5.17p1: the type of the assignment expression is that of its left
11616   // operand.
11617   return (getLangOpts().CPlusPlus
11618           ? LHSType : LHSType.getUnqualifiedType());
11619 }
11620 
11621 // Only ignore explicit casts to void.
11622 static bool IgnoreCommaOperand(const Expr *E) {
11623   E = E->IgnoreParens();
11624 
11625   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
11626     if (CE->getCastKind() == CK_ToVoid) {
11627       return true;
11628     }
11629 
11630     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
11631     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
11632         CE->getSubExpr()->getType()->isDependentType()) {
11633       return true;
11634     }
11635   }
11636 
11637   return false;
11638 }
11639 
11640 // Look for instances where it is likely the comma operator is confused with
11641 // another operator.  There is a whitelist of acceptable expressions for the
11642 // left hand side of the comma operator, otherwise emit a warning.
11643 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
11644   // No warnings in macros
11645   if (Loc.isMacroID())
11646     return;
11647 
11648   // Don't warn in template instantiations.
11649   if (inTemplateInstantiation())
11650     return;
11651 
11652   // Scope isn't fine-grained enough to whitelist the specific cases, so
11653   // instead, skip more than needed, then call back into here with the
11654   // CommaVisitor in SemaStmt.cpp.
11655   // The whitelisted locations are the initialization and increment portions
11656   // of a for loop.  The additional checks are on the condition of
11657   // if statements, do/while loops, and for loops.
11658   // Differences in scope flags for C89 mode requires the extra logic.
11659   const unsigned ForIncrementFlags =
11660       getLangOpts().C99 || getLangOpts().CPlusPlus
11661           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
11662           : Scope::ContinueScope | Scope::BreakScope;
11663   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
11664   const unsigned ScopeFlags = getCurScope()->getFlags();
11665   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
11666       (ScopeFlags & ForInitFlags) == ForInitFlags)
11667     return;
11668 
11669   // If there are multiple comma operators used together, get the RHS of the
11670   // of the comma operator as the LHS.
11671   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
11672     if (BO->getOpcode() != BO_Comma)
11673       break;
11674     LHS = BO->getRHS();
11675   }
11676 
11677   // Only allow some expressions on LHS to not warn.
11678   if (IgnoreCommaOperand(LHS))
11679     return;
11680 
11681   Diag(Loc, diag::warn_comma_operator);
11682   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
11683       << LHS->getSourceRange()
11684       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
11685                                     LangOpts.CPlusPlus ? "static_cast<void>("
11686                                                        : "(void)(")
11687       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
11688                                     ")");
11689 }
11690 
11691 // C99 6.5.17
11692 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
11693                                    SourceLocation Loc) {
11694   LHS = S.CheckPlaceholderExpr(LHS.get());
11695   RHS = S.CheckPlaceholderExpr(RHS.get());
11696   if (LHS.isInvalid() || RHS.isInvalid())
11697     return QualType();
11698 
11699   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
11700   // operands, but not unary promotions.
11701   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
11702 
11703   // So we treat the LHS as a ignored value, and in C++ we allow the
11704   // containing site to determine what should be done with the RHS.
11705   LHS = S.IgnoredValueConversions(LHS.get());
11706   if (LHS.isInvalid())
11707     return QualType();
11708 
11709   S.DiagnoseUnusedExprResult(LHS.get());
11710 
11711   if (!S.getLangOpts().CPlusPlus) {
11712     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
11713     if (RHS.isInvalid())
11714       return QualType();
11715     if (!RHS.get()->getType()->isVoidType())
11716       S.RequireCompleteType(Loc, RHS.get()->getType(),
11717                             diag::err_incomplete_type);
11718   }
11719 
11720   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
11721     S.DiagnoseCommaOperator(LHS.get(), Loc);
11722 
11723   return RHS.get()->getType();
11724 }
11725 
11726 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
11727 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
11728 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
11729                                                ExprValueKind &VK,
11730                                                ExprObjectKind &OK,
11731                                                SourceLocation OpLoc,
11732                                                bool IsInc, bool IsPrefix) {
11733   if (Op->isTypeDependent())
11734     return S.Context.DependentTy;
11735 
11736   QualType ResType = Op->getType();
11737   // Atomic types can be used for increment / decrement where the non-atomic
11738   // versions can, so ignore the _Atomic() specifier for the purpose of
11739   // checking.
11740   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11741     ResType = ResAtomicType->getValueType();
11742 
11743   assert(!ResType.isNull() && "no type for increment/decrement expression");
11744 
11745   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
11746     // Decrement of bool is not allowed.
11747     if (!IsInc) {
11748       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
11749       return QualType();
11750     }
11751     // Increment of bool sets it to true, but is deprecated.
11752     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
11753                                               : diag::warn_increment_bool)
11754       << Op->getSourceRange();
11755   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
11756     // Error on enum increments and decrements in C++ mode
11757     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
11758     return QualType();
11759   } else if (ResType->isRealType()) {
11760     // OK!
11761   } else if (ResType->isPointerType()) {
11762     // C99 6.5.2.4p2, 6.5.6p2
11763     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
11764       return QualType();
11765   } else if (ResType->isObjCObjectPointerType()) {
11766     // On modern runtimes, ObjC pointer arithmetic is forbidden.
11767     // Otherwise, we just need a complete type.
11768     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
11769         checkArithmeticOnObjCPointer(S, OpLoc, Op))
11770       return QualType();
11771   } else if (ResType->isAnyComplexType()) {
11772     // C99 does not support ++/-- on complex types, we allow as an extension.
11773     S.Diag(OpLoc, diag::ext_integer_increment_complex)
11774       << ResType << Op->getSourceRange();
11775   } else if (ResType->isPlaceholderType()) {
11776     ExprResult PR = S.CheckPlaceholderExpr(Op);
11777     if (PR.isInvalid()) return QualType();
11778     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
11779                                           IsInc, IsPrefix);
11780   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
11781     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
11782   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
11783              (ResType->getAs<VectorType>()->getVectorKind() !=
11784               VectorType::AltiVecBool)) {
11785     // The z vector extensions allow ++ and -- for non-bool vectors.
11786   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
11787             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
11788     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
11789   } else {
11790     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
11791       << ResType << int(IsInc) << Op->getSourceRange();
11792     return QualType();
11793   }
11794   // At this point, we know we have a real, complex or pointer type.
11795   // Now make sure the operand is a modifiable lvalue.
11796   if (CheckForModifiableLvalue(Op, OpLoc, S))
11797     return QualType();
11798   // In C++, a prefix increment is the same type as the operand. Otherwise
11799   // (in C or with postfix), the increment is the unqualified type of the
11800   // operand.
11801   if (IsPrefix && S.getLangOpts().CPlusPlus) {
11802     VK = VK_LValue;
11803     OK = Op->getObjectKind();
11804     return ResType;
11805   } else {
11806     VK = VK_RValue;
11807     return ResType.getUnqualifiedType();
11808   }
11809 }
11810 
11811 
11812 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
11813 /// This routine allows us to typecheck complex/recursive expressions
11814 /// where the declaration is needed for type checking. We only need to
11815 /// handle cases when the expression references a function designator
11816 /// or is an lvalue. Here are some examples:
11817 ///  - &(x) => x
11818 ///  - &*****f => f for f a function designator.
11819 ///  - &s.xx => s
11820 ///  - &s.zz[1].yy -> s, if zz is an array
11821 ///  - *(x + 1) -> x, if x is an array
11822 ///  - &"123"[2] -> 0
11823 ///  - & __real__ x -> x
11824 static ValueDecl *getPrimaryDecl(Expr *E) {
11825   switch (E->getStmtClass()) {
11826   case Stmt::DeclRefExprClass:
11827     return cast<DeclRefExpr>(E)->getDecl();
11828   case Stmt::MemberExprClass:
11829     // If this is an arrow operator, the address is an offset from
11830     // the base's value, so the object the base refers to is
11831     // irrelevant.
11832     if (cast<MemberExpr>(E)->isArrow())
11833       return nullptr;
11834     // Otherwise, the expression refers to a part of the base
11835     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
11836   case Stmt::ArraySubscriptExprClass: {
11837     // FIXME: This code shouldn't be necessary!  We should catch the implicit
11838     // promotion of register arrays earlier.
11839     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
11840     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
11841       if (ICE->getSubExpr()->getType()->isArrayType())
11842         return getPrimaryDecl(ICE->getSubExpr());
11843     }
11844     return nullptr;
11845   }
11846   case Stmt::UnaryOperatorClass: {
11847     UnaryOperator *UO = cast<UnaryOperator>(E);
11848 
11849     switch(UO->getOpcode()) {
11850     case UO_Real:
11851     case UO_Imag:
11852     case UO_Extension:
11853       return getPrimaryDecl(UO->getSubExpr());
11854     default:
11855       return nullptr;
11856     }
11857   }
11858   case Stmt::ParenExprClass:
11859     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
11860   case Stmt::ImplicitCastExprClass:
11861     // If the result of an implicit cast is an l-value, we care about
11862     // the sub-expression; otherwise, the result here doesn't matter.
11863     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
11864   default:
11865     return nullptr;
11866   }
11867 }
11868 
11869 namespace {
11870   enum {
11871     AO_Bit_Field = 0,
11872     AO_Vector_Element = 1,
11873     AO_Property_Expansion = 2,
11874     AO_Register_Variable = 3,
11875     AO_No_Error = 4
11876   };
11877 }
11878 /// Diagnose invalid operand for address of operations.
11879 ///
11880 /// \param Type The type of operand which cannot have its address taken.
11881 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
11882                                          Expr *E, unsigned Type) {
11883   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
11884 }
11885 
11886 /// CheckAddressOfOperand - The operand of & must be either a function
11887 /// designator or an lvalue designating an object. If it is an lvalue, the
11888 /// object cannot be declared with storage class register or be a bit field.
11889 /// Note: The usual conversions are *not* applied to the operand of the &
11890 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
11891 /// In C++, the operand might be an overloaded function name, in which case
11892 /// we allow the '&' but retain the overloaded-function type.
11893 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
11894   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
11895     if (PTy->getKind() == BuiltinType::Overload) {
11896       Expr *E = OrigOp.get()->IgnoreParens();
11897       if (!isa<OverloadExpr>(E)) {
11898         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
11899         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
11900           << OrigOp.get()->getSourceRange();
11901         return QualType();
11902       }
11903 
11904       OverloadExpr *Ovl = cast<OverloadExpr>(E);
11905       if (isa<UnresolvedMemberExpr>(Ovl))
11906         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
11907           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11908             << OrigOp.get()->getSourceRange();
11909           return QualType();
11910         }
11911 
11912       return Context.OverloadTy;
11913     }
11914 
11915     if (PTy->getKind() == BuiltinType::UnknownAny)
11916       return Context.UnknownAnyTy;
11917 
11918     if (PTy->getKind() == BuiltinType::BoundMember) {
11919       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11920         << OrigOp.get()->getSourceRange();
11921       return QualType();
11922     }
11923 
11924     OrigOp = CheckPlaceholderExpr(OrigOp.get());
11925     if (OrigOp.isInvalid()) return QualType();
11926   }
11927 
11928   if (OrigOp.get()->isTypeDependent())
11929     return Context.DependentTy;
11930 
11931   assert(!OrigOp.get()->getType()->isPlaceholderType());
11932 
11933   // Make sure to ignore parentheses in subsequent checks
11934   Expr *op = OrigOp.get()->IgnoreParens();
11935 
11936   // In OpenCL captures for blocks called as lambda functions
11937   // are located in the private address space. Blocks used in
11938   // enqueue_kernel can be located in a different address space
11939   // depending on a vendor implementation. Thus preventing
11940   // taking an address of the capture to avoid invalid AS casts.
11941   if (LangOpts.OpenCL) {
11942     auto* VarRef = dyn_cast<DeclRefExpr>(op);
11943     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
11944       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
11945       return QualType();
11946     }
11947   }
11948 
11949   if (getLangOpts().C99) {
11950     // Implement C99-only parts of addressof rules.
11951     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
11952       if (uOp->getOpcode() == UO_Deref)
11953         // Per C99 6.5.3.2, the address of a deref always returns a valid result
11954         // (assuming the deref expression is valid).
11955         return uOp->getSubExpr()->getType();
11956     }
11957     // Technically, there should be a check for array subscript
11958     // expressions here, but the result of one is always an lvalue anyway.
11959   }
11960   ValueDecl *dcl = getPrimaryDecl(op);
11961 
11962   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
11963     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11964                                            op->getBeginLoc()))
11965       return QualType();
11966 
11967   Expr::LValueClassification lval = op->ClassifyLValue(Context);
11968   unsigned AddressOfError = AO_No_Error;
11969 
11970   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
11971     bool sfinae = (bool)isSFINAEContext();
11972     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
11973                                   : diag::ext_typecheck_addrof_temporary)
11974       << op->getType() << op->getSourceRange();
11975     if (sfinae)
11976       return QualType();
11977     // Materialize the temporary as an lvalue so that we can take its address.
11978     OrigOp = op =
11979         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
11980   } else if (isa<ObjCSelectorExpr>(op)) {
11981     return Context.getPointerType(op->getType());
11982   } else if (lval == Expr::LV_MemberFunction) {
11983     // If it's an instance method, make a member pointer.
11984     // The expression must have exactly the form &A::foo.
11985 
11986     // If the underlying expression isn't a decl ref, give up.
11987     if (!isa<DeclRefExpr>(op)) {
11988       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11989         << OrigOp.get()->getSourceRange();
11990       return QualType();
11991     }
11992     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
11993     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
11994 
11995     // The id-expression was parenthesized.
11996     if (OrigOp.get() != DRE) {
11997       Diag(OpLoc, diag::err_parens_pointer_member_function)
11998         << OrigOp.get()->getSourceRange();
11999 
12000     // The method was named without a qualifier.
12001     } else if (!DRE->getQualifier()) {
12002       if (MD->getParent()->getName().empty())
12003         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
12004           << op->getSourceRange();
12005       else {
12006         SmallString<32> Str;
12007         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
12008         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
12009           << op->getSourceRange()
12010           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
12011       }
12012     }
12013 
12014     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
12015     if (isa<CXXDestructorDecl>(MD))
12016       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
12017 
12018     QualType MPTy = Context.getMemberPointerType(
12019         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
12020     // Under the MS ABI, lock down the inheritance model now.
12021     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12022       (void)isCompleteType(OpLoc, MPTy);
12023     return MPTy;
12024   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
12025     // C99 6.5.3.2p1
12026     // The operand must be either an l-value or a function designator
12027     if (!op->getType()->isFunctionType()) {
12028       // Use a special diagnostic for loads from property references.
12029       if (isa<PseudoObjectExpr>(op)) {
12030         AddressOfError = AO_Property_Expansion;
12031       } else {
12032         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
12033           << op->getType() << op->getSourceRange();
12034         return QualType();
12035       }
12036     }
12037   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
12038     // The operand cannot be a bit-field
12039     AddressOfError = AO_Bit_Field;
12040   } else if (op->getObjectKind() == OK_VectorComponent) {
12041     // The operand cannot be an element of a vector
12042     AddressOfError = AO_Vector_Element;
12043   } else if (dcl) { // C99 6.5.3.2p1
12044     // We have an lvalue with a decl. Make sure the decl is not declared
12045     // with the register storage-class specifier.
12046     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
12047       // in C++ it is not error to take address of a register
12048       // variable (c++03 7.1.1P3)
12049       if (vd->getStorageClass() == SC_Register &&
12050           !getLangOpts().CPlusPlus) {
12051         AddressOfError = AO_Register_Variable;
12052       }
12053     } else if (isa<MSPropertyDecl>(dcl)) {
12054       AddressOfError = AO_Property_Expansion;
12055     } else if (isa<FunctionTemplateDecl>(dcl)) {
12056       return Context.OverloadTy;
12057     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
12058       // Okay: we can take the address of a field.
12059       // Could be a pointer to member, though, if there is an explicit
12060       // scope qualifier for the class.
12061       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
12062         DeclContext *Ctx = dcl->getDeclContext();
12063         if (Ctx && Ctx->isRecord()) {
12064           if (dcl->getType()->isReferenceType()) {
12065             Diag(OpLoc,
12066                  diag::err_cannot_form_pointer_to_member_of_reference_type)
12067               << dcl->getDeclName() << dcl->getType();
12068             return QualType();
12069           }
12070 
12071           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
12072             Ctx = Ctx->getParent();
12073 
12074           QualType MPTy = Context.getMemberPointerType(
12075               op->getType(),
12076               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
12077           // Under the MS ABI, lock down the inheritance model now.
12078           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12079             (void)isCompleteType(OpLoc, MPTy);
12080           return MPTy;
12081         }
12082       }
12083     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
12084                !isa<BindingDecl>(dcl))
12085       llvm_unreachable("Unknown/unexpected decl type");
12086   }
12087 
12088   if (AddressOfError != AO_No_Error) {
12089     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
12090     return QualType();
12091   }
12092 
12093   if (lval == Expr::LV_IncompleteVoidType) {
12094     // Taking the address of a void variable is technically illegal, but we
12095     // allow it in cases which are otherwise valid.
12096     // Example: "extern void x; void* y = &x;".
12097     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
12098   }
12099 
12100   // If the operand has type "type", the result has type "pointer to type".
12101   if (op->getType()->isObjCObjectType())
12102     return Context.getObjCObjectPointerType(op->getType());
12103 
12104   CheckAddressOfPackedMember(op);
12105 
12106   return Context.getPointerType(op->getType());
12107 }
12108 
12109 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
12110   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
12111   if (!DRE)
12112     return;
12113   const Decl *D = DRE->getDecl();
12114   if (!D)
12115     return;
12116   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
12117   if (!Param)
12118     return;
12119   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
12120     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
12121       return;
12122   if (FunctionScopeInfo *FD = S.getCurFunction())
12123     if (!FD->ModifiedNonNullParams.count(Param))
12124       FD->ModifiedNonNullParams.insert(Param);
12125 }
12126 
12127 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
12128 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
12129                                         SourceLocation OpLoc) {
12130   if (Op->isTypeDependent())
12131     return S.Context.DependentTy;
12132 
12133   ExprResult ConvResult = S.UsualUnaryConversions(Op);
12134   if (ConvResult.isInvalid())
12135     return QualType();
12136   Op = ConvResult.get();
12137   QualType OpTy = Op->getType();
12138   QualType Result;
12139 
12140   if (isa<CXXReinterpretCastExpr>(Op)) {
12141     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
12142     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
12143                                      Op->getSourceRange());
12144   }
12145 
12146   if (const PointerType *PT = OpTy->getAs<PointerType>())
12147   {
12148     Result = PT->getPointeeType();
12149   }
12150   else if (const ObjCObjectPointerType *OPT =
12151              OpTy->getAs<ObjCObjectPointerType>())
12152     Result = OPT->getPointeeType();
12153   else {
12154     ExprResult PR = S.CheckPlaceholderExpr(Op);
12155     if (PR.isInvalid()) return QualType();
12156     if (PR.get() != Op)
12157       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
12158   }
12159 
12160   if (Result.isNull()) {
12161     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
12162       << OpTy << Op->getSourceRange();
12163     return QualType();
12164   }
12165 
12166   // Note that per both C89 and C99, indirection is always legal, even if Result
12167   // is an incomplete type or void.  It would be possible to warn about
12168   // dereferencing a void pointer, but it's completely well-defined, and such a
12169   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
12170   // for pointers to 'void' but is fine for any other pointer type:
12171   //
12172   // C++ [expr.unary.op]p1:
12173   //   [...] the expression to which [the unary * operator] is applied shall
12174   //   be a pointer to an object type, or a pointer to a function type
12175   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
12176     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
12177       << OpTy << Op->getSourceRange();
12178 
12179   // Dereferences are usually l-values...
12180   VK = VK_LValue;
12181 
12182   // ...except that certain expressions are never l-values in C.
12183   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
12184     VK = VK_RValue;
12185 
12186   return Result;
12187 }
12188 
12189 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
12190   BinaryOperatorKind Opc;
12191   switch (Kind) {
12192   default: llvm_unreachable("Unknown binop!");
12193   case tok::periodstar:           Opc = BO_PtrMemD; break;
12194   case tok::arrowstar:            Opc = BO_PtrMemI; break;
12195   case tok::star:                 Opc = BO_Mul; break;
12196   case tok::slash:                Opc = BO_Div; break;
12197   case tok::percent:              Opc = BO_Rem; break;
12198   case tok::plus:                 Opc = BO_Add; break;
12199   case tok::minus:                Opc = BO_Sub; break;
12200   case tok::lessless:             Opc = BO_Shl; break;
12201   case tok::greatergreater:       Opc = BO_Shr; break;
12202   case tok::lessequal:            Opc = BO_LE; break;
12203   case tok::less:                 Opc = BO_LT; break;
12204   case tok::greaterequal:         Opc = BO_GE; break;
12205   case tok::greater:              Opc = BO_GT; break;
12206   case tok::exclaimequal:         Opc = BO_NE; break;
12207   case tok::equalequal:           Opc = BO_EQ; break;
12208   case tok::spaceship:            Opc = BO_Cmp; break;
12209   case tok::amp:                  Opc = BO_And; break;
12210   case tok::caret:                Opc = BO_Xor; break;
12211   case tok::pipe:                 Opc = BO_Or; break;
12212   case tok::ampamp:               Opc = BO_LAnd; break;
12213   case tok::pipepipe:             Opc = BO_LOr; break;
12214   case tok::equal:                Opc = BO_Assign; break;
12215   case tok::starequal:            Opc = BO_MulAssign; break;
12216   case tok::slashequal:           Opc = BO_DivAssign; break;
12217   case tok::percentequal:         Opc = BO_RemAssign; break;
12218   case tok::plusequal:            Opc = BO_AddAssign; break;
12219   case tok::minusequal:           Opc = BO_SubAssign; break;
12220   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
12221   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
12222   case tok::ampequal:             Opc = BO_AndAssign; break;
12223   case tok::caretequal:           Opc = BO_XorAssign; break;
12224   case tok::pipeequal:            Opc = BO_OrAssign; break;
12225   case tok::comma:                Opc = BO_Comma; break;
12226   }
12227   return Opc;
12228 }
12229 
12230 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
12231   tok::TokenKind Kind) {
12232   UnaryOperatorKind Opc;
12233   switch (Kind) {
12234   default: llvm_unreachable("Unknown unary op!");
12235   case tok::plusplus:     Opc = UO_PreInc; break;
12236   case tok::minusminus:   Opc = UO_PreDec; break;
12237   case tok::amp:          Opc = UO_AddrOf; break;
12238   case tok::star:         Opc = UO_Deref; break;
12239   case tok::plus:         Opc = UO_Plus; break;
12240   case tok::minus:        Opc = UO_Minus; break;
12241   case tok::tilde:        Opc = UO_Not; break;
12242   case tok::exclaim:      Opc = UO_LNot; break;
12243   case tok::kw___real:    Opc = UO_Real; break;
12244   case tok::kw___imag:    Opc = UO_Imag; break;
12245   case tok::kw___extension__: Opc = UO_Extension; break;
12246   }
12247   return Opc;
12248 }
12249 
12250 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
12251 /// This warning suppressed in the event of macro expansions.
12252 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
12253                                    SourceLocation OpLoc, bool IsBuiltin) {
12254   if (S.inTemplateInstantiation())
12255     return;
12256   if (S.isUnevaluatedContext())
12257     return;
12258   if (OpLoc.isInvalid() || OpLoc.isMacroID())
12259     return;
12260   LHSExpr = LHSExpr->IgnoreParenImpCasts();
12261   RHSExpr = RHSExpr->IgnoreParenImpCasts();
12262   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12263   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12264   if (!LHSDeclRef || !RHSDeclRef ||
12265       LHSDeclRef->getLocation().isMacroID() ||
12266       RHSDeclRef->getLocation().isMacroID())
12267     return;
12268   const ValueDecl *LHSDecl =
12269     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
12270   const ValueDecl *RHSDecl =
12271     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
12272   if (LHSDecl != RHSDecl)
12273     return;
12274   if (LHSDecl->getType().isVolatileQualified())
12275     return;
12276   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12277     if (RefTy->getPointeeType().isVolatileQualified())
12278       return;
12279 
12280   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
12281                           : diag::warn_self_assignment_overloaded)
12282       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
12283       << RHSExpr->getSourceRange();
12284 }
12285 
12286 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
12287 /// is usually indicative of introspection within the Objective-C pointer.
12288 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
12289                                           SourceLocation OpLoc) {
12290   if (!S.getLangOpts().ObjC)
12291     return;
12292 
12293   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
12294   const Expr *LHS = L.get();
12295   const Expr *RHS = R.get();
12296 
12297   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12298     ObjCPointerExpr = LHS;
12299     OtherExpr = RHS;
12300   }
12301   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12302     ObjCPointerExpr = RHS;
12303     OtherExpr = LHS;
12304   }
12305 
12306   // This warning is deliberately made very specific to reduce false
12307   // positives with logic that uses '&' for hashing.  This logic mainly
12308   // looks for code trying to introspect into tagged pointers, which
12309   // code should generally never do.
12310   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
12311     unsigned Diag = diag::warn_objc_pointer_masking;
12312     // Determine if we are introspecting the result of performSelectorXXX.
12313     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
12314     // Special case messages to -performSelector and friends, which
12315     // can return non-pointer values boxed in a pointer value.
12316     // Some clients may wish to silence warnings in this subcase.
12317     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
12318       Selector S = ME->getSelector();
12319       StringRef SelArg0 = S.getNameForSlot(0);
12320       if (SelArg0.startswith("performSelector"))
12321         Diag = diag::warn_objc_pointer_masking_performSelector;
12322     }
12323 
12324     S.Diag(OpLoc, Diag)
12325       << ObjCPointerExpr->getSourceRange();
12326   }
12327 }
12328 
12329 static NamedDecl *getDeclFromExpr(Expr *E) {
12330   if (!E)
12331     return nullptr;
12332   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
12333     return DRE->getDecl();
12334   if (auto *ME = dyn_cast<MemberExpr>(E))
12335     return ME->getMemberDecl();
12336   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
12337     return IRE->getDecl();
12338   return nullptr;
12339 }
12340 
12341 // This helper function promotes a binary operator's operands (which are of a
12342 // half vector type) to a vector of floats and then truncates the result to
12343 // a vector of either half or short.
12344 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
12345                                       BinaryOperatorKind Opc, QualType ResultTy,
12346                                       ExprValueKind VK, ExprObjectKind OK,
12347                                       bool IsCompAssign, SourceLocation OpLoc,
12348                                       FPOptions FPFeatures) {
12349   auto &Context = S.getASTContext();
12350   assert((isVector(ResultTy, Context.HalfTy) ||
12351           isVector(ResultTy, Context.ShortTy)) &&
12352          "Result must be a vector of half or short");
12353   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
12354          isVector(RHS.get()->getType(), Context.HalfTy) &&
12355          "both operands expected to be a half vector");
12356 
12357   RHS = convertVector(RHS.get(), Context.FloatTy, S);
12358   QualType BinOpResTy = RHS.get()->getType();
12359 
12360   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
12361   // change BinOpResTy to a vector of ints.
12362   if (isVector(ResultTy, Context.ShortTy))
12363     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
12364 
12365   if (IsCompAssign)
12366     return new (Context) CompoundAssignOperator(
12367         LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
12368         OpLoc, FPFeatures);
12369 
12370   LHS = convertVector(LHS.get(), Context.FloatTy, S);
12371   auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
12372                                           VK, OK, OpLoc, FPFeatures);
12373   return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S);
12374 }
12375 
12376 static std::pair<ExprResult, ExprResult>
12377 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
12378                            Expr *RHSExpr) {
12379   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12380   if (!S.getLangOpts().CPlusPlus) {
12381     // C cannot handle TypoExpr nodes on either side of a binop because it
12382     // doesn't handle dependent types properly, so make sure any TypoExprs have
12383     // been dealt with before checking the operands.
12384     LHS = S.CorrectDelayedTyposInExpr(LHS);
12385     RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
12386       if (Opc != BO_Assign)
12387         return ExprResult(E);
12388       // Avoid correcting the RHS to the same Expr as the LHS.
12389       Decl *D = getDeclFromExpr(E);
12390       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
12391     });
12392   }
12393   return std::make_pair(LHS, RHS);
12394 }
12395 
12396 /// Returns true if conversion between vectors of halfs and vectors of floats
12397 /// is needed.
12398 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
12399                                      QualType SrcType) {
12400   return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
12401          !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
12402          isVector(SrcType, Ctx.HalfTy);
12403 }
12404 
12405 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
12406 /// operator @p Opc at location @c TokLoc. This routine only supports
12407 /// built-in operations; ActOnBinOp handles overloaded operators.
12408 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
12409                                     BinaryOperatorKind Opc,
12410                                     Expr *LHSExpr, Expr *RHSExpr) {
12411   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
12412     // The syntax only allows initializer lists on the RHS of assignment,
12413     // so we don't need to worry about accepting invalid code for
12414     // non-assignment operators.
12415     // C++11 5.17p9:
12416     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
12417     //   of x = {} is x = T().
12418     InitializationKind Kind = InitializationKind::CreateDirectList(
12419         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12420     InitializedEntity Entity =
12421         InitializedEntity::InitializeTemporary(LHSExpr->getType());
12422     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
12423     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
12424     if (Init.isInvalid())
12425       return Init;
12426     RHSExpr = Init.get();
12427   }
12428 
12429   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12430   QualType ResultTy;     // Result type of the binary operator.
12431   // The following two variables are used for compound assignment operators
12432   QualType CompLHSTy;    // Type of LHS after promotions for computation
12433   QualType CompResultTy; // Type of computation result
12434   ExprValueKind VK = VK_RValue;
12435   ExprObjectKind OK = OK_Ordinary;
12436   bool ConvertHalfVec = false;
12437 
12438   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12439   if (!LHS.isUsable() || !RHS.isUsable())
12440     return ExprError();
12441 
12442   if (getLangOpts().OpenCL) {
12443     QualType LHSTy = LHSExpr->getType();
12444     QualType RHSTy = RHSExpr->getType();
12445     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
12446     // the ATOMIC_VAR_INIT macro.
12447     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
12448       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12449       if (BO_Assign == Opc)
12450         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
12451       else
12452         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12453       return ExprError();
12454     }
12455 
12456     // OpenCL special types - image, sampler, pipe, and blocks are to be used
12457     // only with a builtin functions and therefore should be disallowed here.
12458     if (LHSTy->isImageType() || RHSTy->isImageType() ||
12459         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
12460         LHSTy->isPipeType() || RHSTy->isPipeType() ||
12461         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
12462       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12463       return ExprError();
12464     }
12465   }
12466 
12467   // Diagnose operations on the unsupported types for OpenMP device compilation.
12468   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
12469     if (Opc != BO_Assign && Opc != BO_Comma) {
12470       checkOpenMPDeviceExpr(LHSExpr);
12471       checkOpenMPDeviceExpr(RHSExpr);
12472     }
12473   }
12474 
12475   switch (Opc) {
12476   case BO_Assign:
12477     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
12478     if (getLangOpts().CPlusPlus &&
12479         LHS.get()->getObjectKind() != OK_ObjCProperty) {
12480       VK = LHS.get()->getValueKind();
12481       OK = LHS.get()->getObjectKind();
12482     }
12483     if (!ResultTy.isNull()) {
12484       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12485       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
12486 
12487       // Avoid copying a block to the heap if the block is assigned to a local
12488       // auto variable that is declared in the same scope as the block. This
12489       // optimization is unsafe if the local variable is declared in an outer
12490       // scope. For example:
12491       //
12492       // BlockTy b;
12493       // {
12494       //   b = ^{...};
12495       // }
12496       // // It is unsafe to invoke the block here if it wasn't copied to the
12497       // // heap.
12498       // b();
12499 
12500       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
12501         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
12502           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
12503             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
12504               BE->getBlockDecl()->setCanAvoidCopyToHeap();
12505     }
12506     RecordModifiableNonNullParam(*this, LHS.get());
12507     break;
12508   case BO_PtrMemD:
12509   case BO_PtrMemI:
12510     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
12511                                             Opc == BO_PtrMemI);
12512     break;
12513   case BO_Mul:
12514   case BO_Div:
12515     ConvertHalfVec = true;
12516     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
12517                                            Opc == BO_Div);
12518     break;
12519   case BO_Rem:
12520     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
12521     break;
12522   case BO_Add:
12523     ConvertHalfVec = true;
12524     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
12525     break;
12526   case BO_Sub:
12527     ConvertHalfVec = true;
12528     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
12529     break;
12530   case BO_Shl:
12531   case BO_Shr:
12532     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
12533     break;
12534   case BO_LE:
12535   case BO_LT:
12536   case BO_GE:
12537   case BO_GT:
12538     ConvertHalfVec = true;
12539     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12540     break;
12541   case BO_EQ:
12542   case BO_NE:
12543     ConvertHalfVec = true;
12544     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12545     break;
12546   case BO_Cmp:
12547     ConvertHalfVec = true;
12548     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12549     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
12550     break;
12551   case BO_And:
12552     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
12553     LLVM_FALLTHROUGH;
12554   case BO_Xor:
12555   case BO_Or:
12556     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12557     break;
12558   case BO_LAnd:
12559   case BO_LOr:
12560     ConvertHalfVec = true;
12561     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
12562     break;
12563   case BO_MulAssign:
12564   case BO_DivAssign:
12565     ConvertHalfVec = true;
12566     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
12567                                                Opc == BO_DivAssign);
12568     CompLHSTy = CompResultTy;
12569     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12570       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12571     break;
12572   case BO_RemAssign:
12573     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
12574     CompLHSTy = CompResultTy;
12575     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12576       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12577     break;
12578   case BO_AddAssign:
12579     ConvertHalfVec = true;
12580     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
12581     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12582       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12583     break;
12584   case BO_SubAssign:
12585     ConvertHalfVec = true;
12586     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
12587     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12588       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12589     break;
12590   case BO_ShlAssign:
12591   case BO_ShrAssign:
12592     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
12593     CompLHSTy = CompResultTy;
12594     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12595       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12596     break;
12597   case BO_AndAssign:
12598   case BO_OrAssign: // fallthrough
12599     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12600     LLVM_FALLTHROUGH;
12601   case BO_XorAssign:
12602     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12603     CompLHSTy = CompResultTy;
12604     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12605       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12606     break;
12607   case BO_Comma:
12608     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
12609     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
12610       VK = RHS.get()->getValueKind();
12611       OK = RHS.get()->getObjectKind();
12612     }
12613     break;
12614   }
12615   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
12616     return ExprError();
12617 
12618   // Some of the binary operations require promoting operands of half vector to
12619   // float vectors and truncating the result back to half vector. For now, we do
12620   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
12621   // arm64).
12622   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
12623          isVector(LHS.get()->getType(), Context.HalfTy) &&
12624          "both sides are half vectors or neither sides are");
12625   ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
12626                                             LHS.get()->getType());
12627 
12628   // Check for array bounds violations for both sides of the BinaryOperator
12629   CheckArrayAccess(LHS.get());
12630   CheckArrayAccess(RHS.get());
12631 
12632   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
12633     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
12634                                                  &Context.Idents.get("object_setClass"),
12635                                                  SourceLocation(), LookupOrdinaryName);
12636     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
12637       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
12638       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
12639           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
12640                                         "object_setClass(")
12641           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
12642                                           ",")
12643           << FixItHint::CreateInsertion(RHSLocEnd, ")");
12644     }
12645     else
12646       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
12647   }
12648   else if (const ObjCIvarRefExpr *OIRE =
12649            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
12650     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
12651 
12652   // Opc is not a compound assignment if CompResultTy is null.
12653   if (CompResultTy.isNull()) {
12654     if (ConvertHalfVec)
12655       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
12656                                  OpLoc, FPFeatures);
12657     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
12658                                         OK, OpLoc, FPFeatures);
12659   }
12660 
12661   // Handle compound assignments.
12662   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
12663       OK_ObjCProperty) {
12664     VK = VK_LValue;
12665     OK = LHS.get()->getObjectKind();
12666   }
12667 
12668   if (ConvertHalfVec)
12669     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
12670                                OpLoc, FPFeatures);
12671 
12672   return new (Context) CompoundAssignOperator(
12673       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
12674       OpLoc, FPFeatures);
12675 }
12676 
12677 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
12678 /// operators are mixed in a way that suggests that the programmer forgot that
12679 /// comparison operators have higher precedence. The most typical example of
12680 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
12681 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
12682                                       SourceLocation OpLoc, Expr *LHSExpr,
12683                                       Expr *RHSExpr) {
12684   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
12685   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
12686 
12687   // Check that one of the sides is a comparison operator and the other isn't.
12688   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
12689   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
12690   if (isLeftComp == isRightComp)
12691     return;
12692 
12693   // Bitwise operations are sometimes used as eager logical ops.
12694   // Don't diagnose this.
12695   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
12696   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
12697   if (isLeftBitwise || isRightBitwise)
12698     return;
12699 
12700   SourceRange DiagRange = isLeftComp
12701                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
12702                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
12703   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
12704   SourceRange ParensRange =
12705       isLeftComp
12706           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
12707           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
12708 
12709   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
12710     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
12711   SuggestParentheses(Self, OpLoc,
12712     Self.PDiag(diag::note_precedence_silence) << OpStr,
12713     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
12714   SuggestParentheses(Self, OpLoc,
12715     Self.PDiag(diag::note_precedence_bitwise_first)
12716       << BinaryOperator::getOpcodeStr(Opc),
12717     ParensRange);
12718 }
12719 
12720 /// It accepts a '&&' expr that is inside a '||' one.
12721 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
12722 /// in parentheses.
12723 static void
12724 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
12725                                        BinaryOperator *Bop) {
12726   assert(Bop->getOpcode() == BO_LAnd);
12727   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
12728       << Bop->getSourceRange() << OpLoc;
12729   SuggestParentheses(Self, Bop->getOperatorLoc(),
12730     Self.PDiag(diag::note_precedence_silence)
12731       << Bop->getOpcodeStr(),
12732     Bop->getSourceRange());
12733 }
12734 
12735 /// Returns true if the given expression can be evaluated as a constant
12736 /// 'true'.
12737 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
12738   bool Res;
12739   return !E->isValueDependent() &&
12740          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
12741 }
12742 
12743 /// Returns true if the given expression can be evaluated as a constant
12744 /// 'false'.
12745 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
12746   bool Res;
12747   return !E->isValueDependent() &&
12748          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
12749 }
12750 
12751 /// Look for '&&' in the left hand of a '||' expr.
12752 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
12753                                              Expr *LHSExpr, Expr *RHSExpr) {
12754   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
12755     if (Bop->getOpcode() == BO_LAnd) {
12756       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
12757       if (EvaluatesAsFalse(S, RHSExpr))
12758         return;
12759       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
12760       if (!EvaluatesAsTrue(S, Bop->getLHS()))
12761         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12762     } else if (Bop->getOpcode() == BO_LOr) {
12763       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
12764         // If it's "a || b && 1 || c" we didn't warn earlier for
12765         // "a || b && 1", but warn now.
12766         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
12767           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
12768       }
12769     }
12770   }
12771 }
12772 
12773 /// Look for '&&' in the right hand of a '||' expr.
12774 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
12775                                              Expr *LHSExpr, Expr *RHSExpr) {
12776   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
12777     if (Bop->getOpcode() == BO_LAnd) {
12778       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
12779       if (EvaluatesAsFalse(S, LHSExpr))
12780         return;
12781       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
12782       if (!EvaluatesAsTrue(S, Bop->getRHS()))
12783         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12784     }
12785   }
12786 }
12787 
12788 /// Look for bitwise op in the left or right hand of a bitwise op with
12789 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
12790 /// the '&' expression in parentheses.
12791 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
12792                                          SourceLocation OpLoc, Expr *SubExpr) {
12793   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12794     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
12795       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
12796         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
12797         << Bop->getSourceRange() << OpLoc;
12798       SuggestParentheses(S, Bop->getOperatorLoc(),
12799         S.PDiag(diag::note_precedence_silence)
12800           << Bop->getOpcodeStr(),
12801         Bop->getSourceRange());
12802     }
12803   }
12804 }
12805 
12806 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
12807                                     Expr *SubExpr, StringRef Shift) {
12808   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12809     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
12810       StringRef Op = Bop->getOpcodeStr();
12811       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
12812           << Bop->getSourceRange() << OpLoc << Shift << Op;
12813       SuggestParentheses(S, Bop->getOperatorLoc(),
12814           S.PDiag(diag::note_precedence_silence) << Op,
12815           Bop->getSourceRange());
12816     }
12817   }
12818 }
12819 
12820 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
12821                                  Expr *LHSExpr, Expr *RHSExpr) {
12822   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
12823   if (!OCE)
12824     return;
12825 
12826   FunctionDecl *FD = OCE->getDirectCallee();
12827   if (!FD || !FD->isOverloadedOperator())
12828     return;
12829 
12830   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
12831   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
12832     return;
12833 
12834   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
12835       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
12836       << (Kind == OO_LessLess);
12837   SuggestParentheses(S, OCE->getOperatorLoc(),
12838                      S.PDiag(diag::note_precedence_silence)
12839                          << (Kind == OO_LessLess ? "<<" : ">>"),
12840                      OCE->getSourceRange());
12841   SuggestParentheses(
12842       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
12843       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
12844 }
12845 
12846 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
12847 /// precedence.
12848 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
12849                                     SourceLocation OpLoc, Expr *LHSExpr,
12850                                     Expr *RHSExpr){
12851   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
12852   if (BinaryOperator::isBitwiseOp(Opc))
12853     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
12854 
12855   // Diagnose "arg1 & arg2 | arg3"
12856   if ((Opc == BO_Or || Opc == BO_Xor) &&
12857       !OpLoc.isMacroID()/* Don't warn in macros. */) {
12858     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
12859     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
12860   }
12861 
12862   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
12863   // We don't warn for 'assert(a || b && "bad")' since this is safe.
12864   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
12865     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
12866     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
12867   }
12868 
12869   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
12870       || Opc == BO_Shr) {
12871     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
12872     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
12873     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
12874   }
12875 
12876   // Warn on overloaded shift operators and comparisons, such as:
12877   // cout << 5 == 4;
12878   if (BinaryOperator::isComparisonOp(Opc))
12879     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
12880 }
12881 
12882 // Binary Operators.  'Tok' is the token for the operator.
12883 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
12884                             tok::TokenKind Kind,
12885                             Expr *LHSExpr, Expr *RHSExpr) {
12886   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
12887   assert(LHSExpr && "ActOnBinOp(): missing left expression");
12888   assert(RHSExpr && "ActOnBinOp(): missing right expression");
12889 
12890   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
12891   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
12892 
12893   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
12894 }
12895 
12896 /// Build an overloaded binary operator expression in the given scope.
12897 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
12898                                        BinaryOperatorKind Opc,
12899                                        Expr *LHS, Expr *RHS) {
12900   switch (Opc) {
12901   case BO_Assign:
12902   case BO_DivAssign:
12903   case BO_RemAssign:
12904   case BO_SubAssign:
12905   case BO_AndAssign:
12906   case BO_OrAssign:
12907   case BO_XorAssign:
12908     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
12909     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
12910     break;
12911   default:
12912     break;
12913   }
12914 
12915   // Find all of the overloaded operators visible from this
12916   // point. We perform both an operator-name lookup from the local
12917   // scope and an argument-dependent lookup based on the types of
12918   // the arguments.
12919   UnresolvedSet<16> Functions;
12920   OverloadedOperatorKind OverOp
12921     = BinaryOperator::getOverloadedOperator(Opc);
12922   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
12923     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
12924                                    RHS->getType(), Functions);
12925 
12926   // Build the (potentially-overloaded, potentially-dependent)
12927   // binary operation.
12928   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
12929 }
12930 
12931 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
12932                             BinaryOperatorKind Opc,
12933                             Expr *LHSExpr, Expr *RHSExpr) {
12934   ExprResult LHS, RHS;
12935   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12936   if (!LHS.isUsable() || !RHS.isUsable())
12937     return ExprError();
12938   LHSExpr = LHS.get();
12939   RHSExpr = RHS.get();
12940 
12941   // We want to end up calling one of checkPseudoObjectAssignment
12942   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
12943   // both expressions are overloadable or either is type-dependent),
12944   // or CreateBuiltinBinOp (in any other case).  We also want to get
12945   // any placeholder types out of the way.
12946 
12947   // Handle pseudo-objects in the LHS.
12948   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
12949     // Assignments with a pseudo-object l-value need special analysis.
12950     if (pty->getKind() == BuiltinType::PseudoObject &&
12951         BinaryOperator::isAssignmentOp(Opc))
12952       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
12953 
12954     // Don't resolve overloads if the other type is overloadable.
12955     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
12956       // We can't actually test that if we still have a placeholder,
12957       // though.  Fortunately, none of the exceptions we see in that
12958       // code below are valid when the LHS is an overload set.  Note
12959       // that an overload set can be dependently-typed, but it never
12960       // instantiates to having an overloadable type.
12961       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12962       if (resolvedRHS.isInvalid()) return ExprError();
12963       RHSExpr = resolvedRHS.get();
12964 
12965       if (RHSExpr->isTypeDependent() ||
12966           RHSExpr->getType()->isOverloadableType())
12967         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12968     }
12969 
12970     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
12971     // template, diagnose the missing 'template' keyword instead of diagnosing
12972     // an invalid use of a bound member function.
12973     //
12974     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
12975     // to C++1z [over.over]/1.4, but we already checked for that case above.
12976     if (Opc == BO_LT && inTemplateInstantiation() &&
12977         (pty->getKind() == BuiltinType::BoundMember ||
12978          pty->getKind() == BuiltinType::Overload)) {
12979       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
12980       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
12981           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
12982             return isa<FunctionTemplateDecl>(ND);
12983           })) {
12984         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
12985                                 : OE->getNameLoc(),
12986              diag::err_template_kw_missing)
12987           << OE->getName().getAsString() << "";
12988         return ExprError();
12989       }
12990     }
12991 
12992     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
12993     if (LHS.isInvalid()) return ExprError();
12994     LHSExpr = LHS.get();
12995   }
12996 
12997   // Handle pseudo-objects in the RHS.
12998   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
12999     // An overload in the RHS can potentially be resolved by the type
13000     // being assigned to.
13001     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
13002       if (getLangOpts().CPlusPlus &&
13003           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
13004            LHSExpr->getType()->isOverloadableType()))
13005         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13006 
13007       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
13008     }
13009 
13010     // Don't resolve overloads if the other type is overloadable.
13011     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
13012         LHSExpr->getType()->isOverloadableType())
13013       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13014 
13015     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
13016     if (!resolvedRHS.isUsable()) return ExprError();
13017     RHSExpr = resolvedRHS.get();
13018   }
13019 
13020   if (getLangOpts().CPlusPlus) {
13021     // If either expression is type-dependent, always build an
13022     // overloaded op.
13023     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
13024       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13025 
13026     // Otherwise, build an overloaded op if either expression has an
13027     // overloadable type.
13028     if (LHSExpr->getType()->isOverloadableType() ||
13029         RHSExpr->getType()->isOverloadableType())
13030       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13031   }
13032 
13033   // Build a built-in binary operation.
13034   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
13035 }
13036 
13037 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
13038   if (T.isNull() || T->isDependentType())
13039     return false;
13040 
13041   if (!T->isPromotableIntegerType())
13042     return true;
13043 
13044   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
13045 }
13046 
13047 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
13048                                       UnaryOperatorKind Opc,
13049                                       Expr *InputExpr) {
13050   ExprResult Input = InputExpr;
13051   ExprValueKind VK = VK_RValue;
13052   ExprObjectKind OK = OK_Ordinary;
13053   QualType resultType;
13054   bool CanOverflow = false;
13055 
13056   bool ConvertHalfVec = false;
13057   if (getLangOpts().OpenCL) {
13058     QualType Ty = InputExpr->getType();
13059     // The only legal unary operation for atomics is '&'.
13060     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
13061     // OpenCL special types - image, sampler, pipe, and blocks are to be used
13062     // only with a builtin functions and therefore should be disallowed here.
13063         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
13064         || Ty->isBlockPointerType())) {
13065       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13066                        << InputExpr->getType()
13067                        << Input.get()->getSourceRange());
13068     }
13069   }
13070   // Diagnose operations on the unsupported types for OpenMP device compilation.
13071   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
13072     if (UnaryOperator::isIncrementDecrementOp(Opc) ||
13073         UnaryOperator::isArithmeticOp(Opc))
13074       checkOpenMPDeviceExpr(InputExpr);
13075   }
13076 
13077   switch (Opc) {
13078   case UO_PreInc:
13079   case UO_PreDec:
13080   case UO_PostInc:
13081   case UO_PostDec:
13082     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
13083                                                 OpLoc,
13084                                                 Opc == UO_PreInc ||
13085                                                 Opc == UO_PostInc,
13086                                                 Opc == UO_PreInc ||
13087                                                 Opc == UO_PreDec);
13088     CanOverflow = isOverflowingIntegerType(Context, resultType);
13089     break;
13090   case UO_AddrOf:
13091     resultType = CheckAddressOfOperand(Input, OpLoc);
13092     CheckAddressOfNoDeref(InputExpr);
13093     RecordModifiableNonNullParam(*this, InputExpr);
13094     break;
13095   case UO_Deref: {
13096     Input = DefaultFunctionArrayLvalueConversion(Input.get());
13097     if (Input.isInvalid()) return ExprError();
13098     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
13099     break;
13100   }
13101   case UO_Plus:
13102   case UO_Minus:
13103     CanOverflow = Opc == UO_Minus &&
13104                   isOverflowingIntegerType(Context, Input.get()->getType());
13105     Input = UsualUnaryConversions(Input.get());
13106     if (Input.isInvalid()) return ExprError();
13107     // Unary plus and minus require promoting an operand of half vector to a
13108     // float vector and truncating the result back to a half vector. For now, we
13109     // do this only when HalfArgsAndReturns is set (that is, when the target is
13110     // arm or arm64).
13111     ConvertHalfVec =
13112         needsConversionOfHalfVec(true, Context, Input.get()->getType());
13113 
13114     // If the operand is a half vector, promote it to a float vector.
13115     if (ConvertHalfVec)
13116       Input = convertVector(Input.get(), Context.FloatTy, *this);
13117     resultType = Input.get()->getType();
13118     if (resultType->isDependentType())
13119       break;
13120     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
13121       break;
13122     else if (resultType->isVectorType() &&
13123              // The z vector extensions don't allow + or - with bool vectors.
13124              (!Context.getLangOpts().ZVector ||
13125               resultType->getAs<VectorType>()->getVectorKind() !=
13126               VectorType::AltiVecBool))
13127       break;
13128     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
13129              Opc == UO_Plus &&
13130              resultType->isPointerType())
13131       break;
13132 
13133     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13134       << resultType << Input.get()->getSourceRange());
13135 
13136   case UO_Not: // bitwise complement
13137     Input = UsualUnaryConversions(Input.get());
13138     if (Input.isInvalid())
13139       return ExprError();
13140     resultType = Input.get()->getType();
13141 
13142     if (resultType->isDependentType())
13143       break;
13144     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
13145     if (resultType->isComplexType() || resultType->isComplexIntegerType())
13146       // C99 does not support '~' for complex conjugation.
13147       Diag(OpLoc, diag::ext_integer_complement_complex)
13148           << resultType << Input.get()->getSourceRange();
13149     else if (resultType->hasIntegerRepresentation())
13150       break;
13151     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
13152       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
13153       // on vector float types.
13154       QualType T = resultType->getAs<ExtVectorType>()->getElementType();
13155       if (!T->isIntegerType())
13156         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13157                           << resultType << Input.get()->getSourceRange());
13158     } else {
13159       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13160                        << resultType << Input.get()->getSourceRange());
13161     }
13162     break;
13163 
13164   case UO_LNot: // logical negation
13165     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
13166     Input = DefaultFunctionArrayLvalueConversion(Input.get());
13167     if (Input.isInvalid()) return ExprError();
13168     resultType = Input.get()->getType();
13169 
13170     // Though we still have to promote half FP to float...
13171     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
13172       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
13173       resultType = Context.FloatTy;
13174     }
13175 
13176     if (resultType->isDependentType())
13177       break;
13178     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
13179       // C99 6.5.3.3p1: ok, fallthrough;
13180       if (Context.getLangOpts().CPlusPlus) {
13181         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
13182         // operand contextually converted to bool.
13183         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
13184                                   ScalarTypeToBooleanCastKind(resultType));
13185       } else if (Context.getLangOpts().OpenCL &&
13186                  Context.getLangOpts().OpenCLVersion < 120) {
13187         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13188         // operate on scalar float types.
13189         if (!resultType->isIntegerType() && !resultType->isPointerType())
13190           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13191                            << resultType << Input.get()->getSourceRange());
13192       }
13193     } else if (resultType->isExtVectorType()) {
13194       if (Context.getLangOpts().OpenCL &&
13195           Context.getLangOpts().OpenCLVersion < 120 &&
13196           !Context.getLangOpts().OpenCLCPlusPlus) {
13197         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13198         // operate on vector float types.
13199         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
13200         if (!T->isIntegerType())
13201           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13202                            << resultType << Input.get()->getSourceRange());
13203       }
13204       // Vector logical not returns the signed variant of the operand type.
13205       resultType = GetSignedVectorType(resultType);
13206       break;
13207     } else {
13208       // FIXME: GCC's vector extension permits the usage of '!' with a vector
13209       //        type in C++. We should allow that here too.
13210       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13211         << resultType << Input.get()->getSourceRange());
13212     }
13213 
13214     // LNot always has type int. C99 6.5.3.3p5.
13215     // In C++, it's bool. C++ 5.3.1p8
13216     resultType = Context.getLogicalOperationType();
13217     break;
13218   case UO_Real:
13219   case UO_Imag:
13220     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
13221     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
13222     // complex l-values to ordinary l-values and all other values to r-values.
13223     if (Input.isInvalid()) return ExprError();
13224     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
13225       if (Input.get()->getValueKind() != VK_RValue &&
13226           Input.get()->getObjectKind() == OK_Ordinary)
13227         VK = Input.get()->getValueKind();
13228     } else if (!getLangOpts().CPlusPlus) {
13229       // In C, a volatile scalar is read by __imag. In C++, it is not.
13230       Input = DefaultLvalueConversion(Input.get());
13231     }
13232     break;
13233   case UO_Extension:
13234     resultType = Input.get()->getType();
13235     VK = Input.get()->getValueKind();
13236     OK = Input.get()->getObjectKind();
13237     break;
13238   case UO_Coawait:
13239     // It's unnecessary to represent the pass-through operator co_await in the
13240     // AST; just return the input expression instead.
13241     assert(!Input.get()->getType()->isDependentType() &&
13242                    "the co_await expression must be non-dependant before "
13243                    "building operator co_await");
13244     return Input;
13245   }
13246   if (resultType.isNull() || Input.isInvalid())
13247     return ExprError();
13248 
13249   // Check for array bounds violations in the operand of the UnaryOperator,
13250   // except for the '*' and '&' operators that have to be handled specially
13251   // by CheckArrayAccess (as there are special cases like &array[arraysize]
13252   // that are explicitly defined as valid by the standard).
13253   if (Opc != UO_AddrOf && Opc != UO_Deref)
13254     CheckArrayAccess(Input.get());
13255 
13256   auto *UO = new (Context)
13257       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
13258 
13259   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
13260       !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
13261     ExprEvalContexts.back().PossibleDerefs.insert(UO);
13262 
13263   // Convert the result back to a half vector.
13264   if (ConvertHalfVec)
13265     return convertVector(UO, Context.HalfTy, *this);
13266   return UO;
13267 }
13268 
13269 /// Determine whether the given expression is a qualified member
13270 /// access expression, of a form that could be turned into a pointer to member
13271 /// with the address-of operator.
13272 bool Sema::isQualifiedMemberAccess(Expr *E) {
13273   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13274     if (!DRE->getQualifier())
13275       return false;
13276 
13277     ValueDecl *VD = DRE->getDecl();
13278     if (!VD->isCXXClassMember())
13279       return false;
13280 
13281     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
13282       return true;
13283     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
13284       return Method->isInstance();
13285 
13286     return false;
13287   }
13288 
13289   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13290     if (!ULE->getQualifier())
13291       return false;
13292 
13293     for (NamedDecl *D : ULE->decls()) {
13294       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
13295         if (Method->isInstance())
13296           return true;
13297       } else {
13298         // Overload set does not contain methods.
13299         break;
13300       }
13301     }
13302 
13303     return false;
13304   }
13305 
13306   return false;
13307 }
13308 
13309 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
13310                               UnaryOperatorKind Opc, Expr *Input) {
13311   // First things first: handle placeholders so that the
13312   // overloaded-operator check considers the right type.
13313   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
13314     // Increment and decrement of pseudo-object references.
13315     if (pty->getKind() == BuiltinType::PseudoObject &&
13316         UnaryOperator::isIncrementDecrementOp(Opc))
13317       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
13318 
13319     // extension is always a builtin operator.
13320     if (Opc == UO_Extension)
13321       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13322 
13323     // & gets special logic for several kinds of placeholder.
13324     // The builtin code knows what to do.
13325     if (Opc == UO_AddrOf &&
13326         (pty->getKind() == BuiltinType::Overload ||
13327          pty->getKind() == BuiltinType::UnknownAny ||
13328          pty->getKind() == BuiltinType::BoundMember))
13329       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13330 
13331     // Anything else needs to be handled now.
13332     ExprResult Result = CheckPlaceholderExpr(Input);
13333     if (Result.isInvalid()) return ExprError();
13334     Input = Result.get();
13335   }
13336 
13337   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
13338       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
13339       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
13340     // Find all of the overloaded operators visible from this
13341     // point. We perform both an operator-name lookup from the local
13342     // scope and an argument-dependent lookup based on the types of
13343     // the arguments.
13344     UnresolvedSet<16> Functions;
13345     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
13346     if (S && OverOp != OO_None)
13347       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
13348                                    Functions);
13349 
13350     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
13351   }
13352 
13353   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13354 }
13355 
13356 // Unary Operators.  'Tok' is the token for the operator.
13357 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
13358                               tok::TokenKind Op, Expr *Input) {
13359   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
13360 }
13361 
13362 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
13363 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
13364                                 LabelDecl *TheDecl) {
13365   TheDecl->markUsed(Context);
13366   // Create the AST node.  The address of a label always has type 'void*'.
13367   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
13368                                      Context.getPointerType(Context.VoidTy));
13369 }
13370 
13371 void Sema::ActOnStartStmtExpr() {
13372   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13373 }
13374 
13375 void Sema::ActOnStmtExprError() {
13376   // Note that function is also called by TreeTransform when leaving a
13377   // StmtExpr scope without rebuilding anything.
13378 
13379   DiscardCleanupsInEvaluationContext();
13380   PopExpressionEvaluationContext();
13381 }
13382 
13383 ExprResult
13384 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
13385                     SourceLocation RPLoc) { // "({..})"
13386   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
13387   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
13388 
13389   if (hasAnyUnrecoverableErrorsInThisFunction())
13390     DiscardCleanupsInEvaluationContext();
13391   assert(!Cleanup.exprNeedsCleanups() &&
13392          "cleanups within StmtExpr not correctly bound!");
13393   PopExpressionEvaluationContext();
13394 
13395   // FIXME: there are a variety of strange constraints to enforce here, for
13396   // example, it is not possible to goto into a stmt expression apparently.
13397   // More semantic analysis is needed.
13398 
13399   // If there are sub-stmts in the compound stmt, take the type of the last one
13400   // as the type of the stmtexpr.
13401   QualType Ty = Context.VoidTy;
13402   bool StmtExprMayBindToTemp = false;
13403   if (!Compound->body_empty()) {
13404     if (const auto *LastStmt = dyn_cast<ValueStmt>(Compound->body_back())) {
13405       if (const Expr *Value = LastStmt->getExprStmt()) {
13406         StmtExprMayBindToTemp = true;
13407         Ty = Value->getType();
13408       }
13409     }
13410   }
13411 
13412   // FIXME: Check that expression type is complete/non-abstract; statement
13413   // expressions are not lvalues.
13414   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
13415   if (StmtExprMayBindToTemp)
13416     return MaybeBindToTemporary(ResStmtExpr);
13417   return ResStmtExpr;
13418 }
13419 
13420 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
13421   if (ER.isInvalid())
13422     return ExprError();
13423 
13424   // Do function/array conversion on the last expression, but not
13425   // lvalue-to-rvalue.  However, initialize an unqualified type.
13426   ER = DefaultFunctionArrayConversion(ER.get());
13427   if (ER.isInvalid())
13428     return ExprError();
13429   Expr *E = ER.get();
13430 
13431   if (E->isTypeDependent())
13432     return E;
13433 
13434   // In ARC, if the final expression ends in a consume, splice
13435   // the consume out and bind it later.  In the alternate case
13436   // (when dealing with a retainable type), the result
13437   // initialization will create a produce.  In both cases the
13438   // result will be +1, and we'll need to balance that out with
13439   // a bind.
13440   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
13441   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
13442     return Cast->getSubExpr();
13443 
13444   // FIXME: Provide a better location for the initialization.
13445   return PerformCopyInitialization(
13446       InitializedEntity::InitializeStmtExprResult(
13447           E->getBeginLoc(), E->getType().getUnqualifiedType()),
13448       SourceLocation(), E);
13449 }
13450 
13451 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
13452                                       TypeSourceInfo *TInfo,
13453                                       ArrayRef<OffsetOfComponent> Components,
13454                                       SourceLocation RParenLoc) {
13455   QualType ArgTy = TInfo->getType();
13456   bool Dependent = ArgTy->isDependentType();
13457   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
13458 
13459   // We must have at least one component that refers to the type, and the first
13460   // one is known to be a field designator.  Verify that the ArgTy represents
13461   // a struct/union/class.
13462   if (!Dependent && !ArgTy->isRecordType())
13463     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
13464                        << ArgTy << TypeRange);
13465 
13466   // Type must be complete per C99 7.17p3 because a declaring a variable
13467   // with an incomplete type would be ill-formed.
13468   if (!Dependent
13469       && RequireCompleteType(BuiltinLoc, ArgTy,
13470                              diag::err_offsetof_incomplete_type, TypeRange))
13471     return ExprError();
13472 
13473   bool DidWarnAboutNonPOD = false;
13474   QualType CurrentType = ArgTy;
13475   SmallVector<OffsetOfNode, 4> Comps;
13476   SmallVector<Expr*, 4> Exprs;
13477   for (const OffsetOfComponent &OC : Components) {
13478     if (OC.isBrackets) {
13479       // Offset of an array sub-field.  TODO: Should we allow vector elements?
13480       if (!CurrentType->isDependentType()) {
13481         const ArrayType *AT = Context.getAsArrayType(CurrentType);
13482         if(!AT)
13483           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
13484                            << CurrentType);
13485         CurrentType = AT->getElementType();
13486       } else
13487         CurrentType = Context.DependentTy;
13488 
13489       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
13490       if (IdxRval.isInvalid())
13491         return ExprError();
13492       Expr *Idx = IdxRval.get();
13493 
13494       // The expression must be an integral expression.
13495       // FIXME: An integral constant expression?
13496       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
13497           !Idx->getType()->isIntegerType())
13498         return ExprError(
13499             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
13500             << Idx->getSourceRange());
13501 
13502       // Record this array index.
13503       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
13504       Exprs.push_back(Idx);
13505       continue;
13506     }
13507 
13508     // Offset of a field.
13509     if (CurrentType->isDependentType()) {
13510       // We have the offset of a field, but we can't look into the dependent
13511       // type. Just record the identifier of the field.
13512       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
13513       CurrentType = Context.DependentTy;
13514       continue;
13515     }
13516 
13517     // We need to have a complete type to look into.
13518     if (RequireCompleteType(OC.LocStart, CurrentType,
13519                             diag::err_offsetof_incomplete_type))
13520       return ExprError();
13521 
13522     // Look for the designated field.
13523     const RecordType *RC = CurrentType->getAs<RecordType>();
13524     if (!RC)
13525       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
13526                        << CurrentType);
13527     RecordDecl *RD = RC->getDecl();
13528 
13529     // C++ [lib.support.types]p5:
13530     //   The macro offsetof accepts a restricted set of type arguments in this
13531     //   International Standard. type shall be a POD structure or a POD union
13532     //   (clause 9).
13533     // C++11 [support.types]p4:
13534     //   If type is not a standard-layout class (Clause 9), the results are
13535     //   undefined.
13536     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13537       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
13538       unsigned DiagID =
13539         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
13540                             : diag::ext_offsetof_non_pod_type;
13541 
13542       if (!IsSafe && !DidWarnAboutNonPOD &&
13543           DiagRuntimeBehavior(BuiltinLoc, nullptr,
13544                               PDiag(DiagID)
13545                               << SourceRange(Components[0].LocStart, OC.LocEnd)
13546                               << CurrentType))
13547         DidWarnAboutNonPOD = true;
13548     }
13549 
13550     // Look for the field.
13551     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
13552     LookupQualifiedName(R, RD);
13553     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
13554     IndirectFieldDecl *IndirectMemberDecl = nullptr;
13555     if (!MemberDecl) {
13556       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
13557         MemberDecl = IndirectMemberDecl->getAnonField();
13558     }
13559 
13560     if (!MemberDecl)
13561       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
13562                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
13563                                                               OC.LocEnd));
13564 
13565     // C99 7.17p3:
13566     //   (If the specified member is a bit-field, the behavior is undefined.)
13567     //
13568     // We diagnose this as an error.
13569     if (MemberDecl->isBitField()) {
13570       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
13571         << MemberDecl->getDeclName()
13572         << SourceRange(BuiltinLoc, RParenLoc);
13573       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
13574       return ExprError();
13575     }
13576 
13577     RecordDecl *Parent = MemberDecl->getParent();
13578     if (IndirectMemberDecl)
13579       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
13580 
13581     // If the member was found in a base class, introduce OffsetOfNodes for
13582     // the base class indirections.
13583     CXXBasePaths Paths;
13584     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
13585                       Paths)) {
13586       if (Paths.getDetectedVirtual()) {
13587         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
13588           << MemberDecl->getDeclName()
13589           << SourceRange(BuiltinLoc, RParenLoc);
13590         return ExprError();
13591       }
13592 
13593       CXXBasePath &Path = Paths.front();
13594       for (const CXXBasePathElement &B : Path)
13595         Comps.push_back(OffsetOfNode(B.Base));
13596     }
13597 
13598     if (IndirectMemberDecl) {
13599       for (auto *FI : IndirectMemberDecl->chain()) {
13600         assert(isa<FieldDecl>(FI));
13601         Comps.push_back(OffsetOfNode(OC.LocStart,
13602                                      cast<FieldDecl>(FI), OC.LocEnd));
13603       }
13604     } else
13605       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
13606 
13607     CurrentType = MemberDecl->getType().getNonReferenceType();
13608   }
13609 
13610   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
13611                               Comps, Exprs, RParenLoc);
13612 }
13613 
13614 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
13615                                       SourceLocation BuiltinLoc,
13616                                       SourceLocation TypeLoc,
13617                                       ParsedType ParsedArgTy,
13618                                       ArrayRef<OffsetOfComponent> Components,
13619                                       SourceLocation RParenLoc) {
13620 
13621   TypeSourceInfo *ArgTInfo;
13622   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
13623   if (ArgTy.isNull())
13624     return ExprError();
13625 
13626   if (!ArgTInfo)
13627     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
13628 
13629   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
13630 }
13631 
13632 
13633 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
13634                                  Expr *CondExpr,
13635                                  Expr *LHSExpr, Expr *RHSExpr,
13636                                  SourceLocation RPLoc) {
13637   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
13638 
13639   ExprValueKind VK = VK_RValue;
13640   ExprObjectKind OK = OK_Ordinary;
13641   QualType resType;
13642   bool ValueDependent = false;
13643   bool CondIsTrue = false;
13644   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
13645     resType = Context.DependentTy;
13646     ValueDependent = true;
13647   } else {
13648     // The conditional expression is required to be a constant expression.
13649     llvm::APSInt condEval(32);
13650     ExprResult CondICE
13651       = VerifyIntegerConstantExpression(CondExpr, &condEval,
13652           diag::err_typecheck_choose_expr_requires_constant, false);
13653     if (CondICE.isInvalid())
13654       return ExprError();
13655     CondExpr = CondICE.get();
13656     CondIsTrue = condEval.getZExtValue();
13657 
13658     // If the condition is > zero, then the AST type is the same as the LHSExpr.
13659     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
13660 
13661     resType = ActiveExpr->getType();
13662     ValueDependent = ActiveExpr->isValueDependent();
13663     VK = ActiveExpr->getValueKind();
13664     OK = ActiveExpr->getObjectKind();
13665   }
13666 
13667   return new (Context)
13668       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
13669                  CondIsTrue, resType->isDependentType(), ValueDependent);
13670 }
13671 
13672 //===----------------------------------------------------------------------===//
13673 // Clang Extensions.
13674 //===----------------------------------------------------------------------===//
13675 
13676 /// ActOnBlockStart - This callback is invoked when a block literal is started.
13677 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
13678   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
13679 
13680   if (LangOpts.CPlusPlus) {
13681     Decl *ManglingContextDecl;
13682     if (MangleNumberingContext *MCtx =
13683             getCurrentMangleNumberContext(Block->getDeclContext(),
13684                                           ManglingContextDecl)) {
13685       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
13686       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
13687     }
13688   }
13689 
13690   PushBlockScope(CurScope, Block);
13691   CurContext->addDecl(Block);
13692   if (CurScope)
13693     PushDeclContext(CurScope, Block);
13694   else
13695     CurContext = Block;
13696 
13697   getCurBlock()->HasImplicitReturnType = true;
13698 
13699   // Enter a new evaluation context to insulate the block from any
13700   // cleanups from the enclosing full-expression.
13701   PushExpressionEvaluationContext(
13702       ExpressionEvaluationContext::PotentiallyEvaluated);
13703 }
13704 
13705 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
13706                                Scope *CurScope) {
13707   assert(ParamInfo.getIdentifier() == nullptr &&
13708          "block-id should have no identifier!");
13709   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
13710   BlockScopeInfo *CurBlock = getCurBlock();
13711 
13712   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
13713   QualType T = Sig->getType();
13714 
13715   // FIXME: We should allow unexpanded parameter packs here, but that would,
13716   // in turn, make the block expression contain unexpanded parameter packs.
13717   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
13718     // Drop the parameters.
13719     FunctionProtoType::ExtProtoInfo EPI;
13720     EPI.HasTrailingReturn = false;
13721     EPI.TypeQuals.addConst();
13722     T = Context.getFunctionType(Context.DependentTy, None, EPI);
13723     Sig = Context.getTrivialTypeSourceInfo(T);
13724   }
13725 
13726   // GetTypeForDeclarator always produces a function type for a block
13727   // literal signature.  Furthermore, it is always a FunctionProtoType
13728   // unless the function was written with a typedef.
13729   assert(T->isFunctionType() &&
13730          "GetTypeForDeclarator made a non-function block signature");
13731 
13732   // Look for an explicit signature in that function type.
13733   FunctionProtoTypeLoc ExplicitSignature;
13734 
13735   if ((ExplicitSignature = Sig->getTypeLoc()
13736                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
13737 
13738     // Check whether that explicit signature was synthesized by
13739     // GetTypeForDeclarator.  If so, don't save that as part of the
13740     // written signature.
13741     if (ExplicitSignature.getLocalRangeBegin() ==
13742         ExplicitSignature.getLocalRangeEnd()) {
13743       // This would be much cheaper if we stored TypeLocs instead of
13744       // TypeSourceInfos.
13745       TypeLoc Result = ExplicitSignature.getReturnLoc();
13746       unsigned Size = Result.getFullDataSize();
13747       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
13748       Sig->getTypeLoc().initializeFullCopy(Result, Size);
13749 
13750       ExplicitSignature = FunctionProtoTypeLoc();
13751     }
13752   }
13753 
13754   CurBlock->TheDecl->setSignatureAsWritten(Sig);
13755   CurBlock->FunctionType = T;
13756 
13757   const FunctionType *Fn = T->getAs<FunctionType>();
13758   QualType RetTy = Fn->getReturnType();
13759   bool isVariadic =
13760     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
13761 
13762   CurBlock->TheDecl->setIsVariadic(isVariadic);
13763 
13764   // Context.DependentTy is used as a placeholder for a missing block
13765   // return type.  TODO:  what should we do with declarators like:
13766   //   ^ * { ... }
13767   // If the answer is "apply template argument deduction"....
13768   if (RetTy != Context.DependentTy) {
13769     CurBlock->ReturnType = RetTy;
13770     CurBlock->TheDecl->setBlockMissingReturnType(false);
13771     CurBlock->HasImplicitReturnType = false;
13772   }
13773 
13774   // Push block parameters from the declarator if we had them.
13775   SmallVector<ParmVarDecl*, 8> Params;
13776   if (ExplicitSignature) {
13777     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
13778       ParmVarDecl *Param = ExplicitSignature.getParam(I);
13779       if (Param->getIdentifier() == nullptr &&
13780           !Param->isImplicit() &&
13781           !Param->isInvalidDecl() &&
13782           !getLangOpts().CPlusPlus)
13783         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
13784       Params.push_back(Param);
13785     }
13786 
13787   // Fake up parameter variables if we have a typedef, like
13788   //   ^ fntype { ... }
13789   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
13790     for (const auto &I : Fn->param_types()) {
13791       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
13792           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
13793       Params.push_back(Param);
13794     }
13795   }
13796 
13797   // Set the parameters on the block decl.
13798   if (!Params.empty()) {
13799     CurBlock->TheDecl->setParams(Params);
13800     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
13801                              /*CheckParameterNames=*/false);
13802   }
13803 
13804   // Finally we can process decl attributes.
13805   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
13806 
13807   // Put the parameter variables in scope.
13808   for (auto AI : CurBlock->TheDecl->parameters()) {
13809     AI->setOwningFunction(CurBlock->TheDecl);
13810 
13811     // If this has an identifier, add it to the scope stack.
13812     if (AI->getIdentifier()) {
13813       CheckShadow(CurBlock->TheScope, AI);
13814 
13815       PushOnScopeChains(AI, CurBlock->TheScope);
13816     }
13817   }
13818 }
13819 
13820 /// ActOnBlockError - If there is an error parsing a block, this callback
13821 /// is invoked to pop the information about the block from the action impl.
13822 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
13823   // Leave the expression-evaluation context.
13824   DiscardCleanupsInEvaluationContext();
13825   PopExpressionEvaluationContext();
13826 
13827   // Pop off CurBlock, handle nested blocks.
13828   PopDeclContext();
13829   PopFunctionScopeInfo();
13830 }
13831 
13832 /// ActOnBlockStmtExpr - This is called when the body of a block statement
13833 /// literal was successfully completed.  ^(int x){...}
13834 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
13835                                     Stmt *Body, Scope *CurScope) {
13836   // If blocks are disabled, emit an error.
13837   if (!LangOpts.Blocks)
13838     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
13839 
13840   // Leave the expression-evaluation context.
13841   if (hasAnyUnrecoverableErrorsInThisFunction())
13842     DiscardCleanupsInEvaluationContext();
13843   assert(!Cleanup.exprNeedsCleanups() &&
13844          "cleanups within block not correctly bound!");
13845   PopExpressionEvaluationContext();
13846 
13847   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
13848   BlockDecl *BD = BSI->TheDecl;
13849 
13850   if (BSI->HasImplicitReturnType)
13851     deduceClosureReturnType(*BSI);
13852 
13853   QualType RetTy = Context.VoidTy;
13854   if (!BSI->ReturnType.isNull())
13855     RetTy = BSI->ReturnType;
13856 
13857   bool NoReturn = BD->hasAttr<NoReturnAttr>();
13858   QualType BlockTy;
13859 
13860   // If the user wrote a function type in some form, try to use that.
13861   if (!BSI->FunctionType.isNull()) {
13862     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
13863 
13864     FunctionType::ExtInfo Ext = FTy->getExtInfo();
13865     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
13866 
13867     // Turn protoless block types into nullary block types.
13868     if (isa<FunctionNoProtoType>(FTy)) {
13869       FunctionProtoType::ExtProtoInfo EPI;
13870       EPI.ExtInfo = Ext;
13871       BlockTy = Context.getFunctionType(RetTy, None, EPI);
13872 
13873     // Otherwise, if we don't need to change anything about the function type,
13874     // preserve its sugar structure.
13875     } else if (FTy->getReturnType() == RetTy &&
13876                (!NoReturn || FTy->getNoReturnAttr())) {
13877       BlockTy = BSI->FunctionType;
13878 
13879     // Otherwise, make the minimal modifications to the function type.
13880     } else {
13881       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
13882       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13883       EPI.TypeQuals = Qualifiers();
13884       EPI.ExtInfo = Ext;
13885       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
13886     }
13887 
13888   // If we don't have a function type, just build one from nothing.
13889   } else {
13890     FunctionProtoType::ExtProtoInfo EPI;
13891     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
13892     BlockTy = Context.getFunctionType(RetTy, None, EPI);
13893   }
13894 
13895   DiagnoseUnusedParameters(BD->parameters());
13896   BlockTy = Context.getBlockPointerType(BlockTy);
13897 
13898   // If needed, diagnose invalid gotos and switches in the block.
13899   if (getCurFunction()->NeedsScopeChecking() &&
13900       !PP.isCodeCompletionEnabled())
13901     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
13902 
13903   BD->setBody(cast<CompoundStmt>(Body));
13904 
13905   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13906     DiagnoseUnguardedAvailabilityViolations(BD);
13907 
13908   // Try to apply the named return value optimization. We have to check again
13909   // if we can do this, though, because blocks keep return statements around
13910   // to deduce an implicit return type.
13911   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
13912       !BD->isDependentContext())
13913     computeNRVO(Body, BSI);
13914 
13915   PopDeclContext();
13916 
13917   // Pop the block scope now but keep it alive to the end of this function.
13918   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13919   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
13920 
13921   // Set the captured variables on the block.
13922   SmallVector<BlockDecl::Capture, 4> Captures;
13923   for (Capture &Cap : BSI->Captures) {
13924     if (Cap.isInvalid() || Cap.isThisCapture())
13925       continue;
13926 
13927     VarDecl *Var = Cap.getVariable();
13928     Expr *CopyExpr = nullptr;
13929     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
13930       if (const RecordType *Record =
13931               Cap.getCaptureType()->getAs<RecordType>()) {
13932         // The capture logic needs the destructor, so make sure we mark it.
13933         // Usually this is unnecessary because most local variables have
13934         // their destructors marked at declaration time, but parameters are
13935         // an exception because it's technically only the call site that
13936         // actually requires the destructor.
13937         if (isa<ParmVarDecl>(Var))
13938           FinalizeVarWithDestructor(Var, Record);
13939 
13940         // Enter a separate potentially-evaluated context while building block
13941         // initializers to isolate their cleanups from those of the block
13942         // itself.
13943         // FIXME: Is this appropriate even when the block itself occurs in an
13944         // unevaluated operand?
13945         EnterExpressionEvaluationContext EvalContext(
13946             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
13947 
13948         SourceLocation Loc = Cap.getLocation();
13949 
13950         ExprResult Result = BuildDeclarationNameExpr(
13951             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
13952 
13953         // According to the blocks spec, the capture of a variable from
13954         // the stack requires a const copy constructor.  This is not true
13955         // of the copy/move done to move a __block variable to the heap.
13956         if (!Result.isInvalid() &&
13957             !Result.get()->getType().isConstQualified()) {
13958           Result = ImpCastExprToType(Result.get(),
13959                                      Result.get()->getType().withConst(),
13960                                      CK_NoOp, VK_LValue);
13961         }
13962 
13963         if (!Result.isInvalid()) {
13964           Result = PerformCopyInitialization(
13965               InitializedEntity::InitializeBlock(Var->getLocation(),
13966                                                  Cap.getCaptureType(), false),
13967               Loc, Result.get());
13968         }
13969 
13970         // Build a full-expression copy expression if initialization
13971         // succeeded and used a non-trivial constructor.  Recover from
13972         // errors by pretending that the copy isn't necessary.
13973         if (!Result.isInvalid() &&
13974             !cast<CXXConstructExpr>(Result.get())->getConstructor()
13975                 ->isTrivial()) {
13976           Result = MaybeCreateExprWithCleanups(Result);
13977           CopyExpr = Result.get();
13978         }
13979       }
13980     }
13981 
13982     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
13983                               CopyExpr);
13984     Captures.push_back(NewCap);
13985   }
13986   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
13987 
13988   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
13989 
13990   // If the block isn't obviously global, i.e. it captures anything at
13991   // all, then we need to do a few things in the surrounding context:
13992   if (Result->getBlockDecl()->hasCaptures()) {
13993     // First, this expression has a new cleanup object.
13994     ExprCleanupObjects.push_back(Result->getBlockDecl());
13995     Cleanup.setExprNeedsCleanups(true);
13996 
13997     // It also gets a branch-protected scope if any of the captured
13998     // variables needs destruction.
13999     for (const auto &CI : Result->getBlockDecl()->captures()) {
14000       const VarDecl *var = CI.getVariable();
14001       if (var->getType().isDestructedType() != QualType::DK_none) {
14002         setFunctionHasBranchProtectedScope();
14003         break;
14004       }
14005     }
14006   }
14007 
14008   if (getCurFunction())
14009     getCurFunction()->addBlock(BD);
14010 
14011   return Result;
14012 }
14013 
14014 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
14015                             SourceLocation RPLoc) {
14016   TypeSourceInfo *TInfo;
14017   GetTypeFromParser(Ty, &TInfo);
14018   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
14019 }
14020 
14021 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
14022                                 Expr *E, TypeSourceInfo *TInfo,
14023                                 SourceLocation RPLoc) {
14024   Expr *OrigExpr = E;
14025   bool IsMS = false;
14026 
14027   // CUDA device code does not support varargs.
14028   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
14029     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
14030       CUDAFunctionTarget T = IdentifyCUDATarget(F);
14031       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
14032         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
14033     }
14034   }
14035 
14036   // NVPTX does not support va_arg expression.
14037   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
14038       Context.getTargetInfo().getTriple().isNVPTX())
14039     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
14040 
14041   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
14042   // as Microsoft ABI on an actual Microsoft platform, where
14043   // __builtin_ms_va_list and __builtin_va_list are the same.)
14044   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
14045       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
14046     QualType MSVaListType = Context.getBuiltinMSVaListType();
14047     if (Context.hasSameType(MSVaListType, E->getType())) {
14048       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
14049         return ExprError();
14050       IsMS = true;
14051     }
14052   }
14053 
14054   // Get the va_list type
14055   QualType VaListType = Context.getBuiltinVaListType();
14056   if (!IsMS) {
14057     if (VaListType->isArrayType()) {
14058       // Deal with implicit array decay; for example, on x86-64,
14059       // va_list is an array, but it's supposed to decay to
14060       // a pointer for va_arg.
14061       VaListType = Context.getArrayDecayedType(VaListType);
14062       // Make sure the input expression also decays appropriately.
14063       ExprResult Result = UsualUnaryConversions(E);
14064       if (Result.isInvalid())
14065         return ExprError();
14066       E = Result.get();
14067     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
14068       // If va_list is a record type and we are compiling in C++ mode,
14069       // check the argument using reference binding.
14070       InitializedEntity Entity = InitializedEntity::InitializeParameter(
14071           Context, Context.getLValueReferenceType(VaListType), false);
14072       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
14073       if (Init.isInvalid())
14074         return ExprError();
14075       E = Init.getAs<Expr>();
14076     } else {
14077       // Otherwise, the va_list argument must be an l-value because
14078       // it is modified by va_arg.
14079       if (!E->isTypeDependent() &&
14080           CheckForModifiableLvalue(E, BuiltinLoc, *this))
14081         return ExprError();
14082     }
14083   }
14084 
14085   if (!IsMS && !E->isTypeDependent() &&
14086       !Context.hasSameType(VaListType, E->getType()))
14087     return ExprError(
14088         Diag(E->getBeginLoc(),
14089              diag::err_first_argument_to_va_arg_not_of_type_va_list)
14090         << OrigExpr->getType() << E->getSourceRange());
14091 
14092   if (!TInfo->getType()->isDependentType()) {
14093     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
14094                             diag::err_second_parameter_to_va_arg_incomplete,
14095                             TInfo->getTypeLoc()))
14096       return ExprError();
14097 
14098     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
14099                                TInfo->getType(),
14100                                diag::err_second_parameter_to_va_arg_abstract,
14101                                TInfo->getTypeLoc()))
14102       return ExprError();
14103 
14104     if (!TInfo->getType().isPODType(Context)) {
14105       Diag(TInfo->getTypeLoc().getBeginLoc(),
14106            TInfo->getType()->isObjCLifetimeType()
14107              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
14108              : diag::warn_second_parameter_to_va_arg_not_pod)
14109         << TInfo->getType()
14110         << TInfo->getTypeLoc().getSourceRange();
14111     }
14112 
14113     // Check for va_arg where arguments of the given type will be promoted
14114     // (i.e. this va_arg is guaranteed to have undefined behavior).
14115     QualType PromoteType;
14116     if (TInfo->getType()->isPromotableIntegerType()) {
14117       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
14118       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
14119         PromoteType = QualType();
14120     }
14121     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
14122       PromoteType = Context.DoubleTy;
14123     if (!PromoteType.isNull())
14124       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
14125                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
14126                           << TInfo->getType()
14127                           << PromoteType
14128                           << TInfo->getTypeLoc().getSourceRange());
14129   }
14130 
14131   QualType T = TInfo->getType().getNonLValueExprType(Context);
14132   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
14133 }
14134 
14135 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
14136   // The type of __null will be int or long, depending on the size of
14137   // pointers on the target.
14138   QualType Ty;
14139   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
14140   if (pw == Context.getTargetInfo().getIntWidth())
14141     Ty = Context.IntTy;
14142   else if (pw == Context.getTargetInfo().getLongWidth())
14143     Ty = Context.LongTy;
14144   else if (pw == Context.getTargetInfo().getLongLongWidth())
14145     Ty = Context.LongLongTy;
14146   else {
14147     llvm_unreachable("I don't know size of pointer!");
14148   }
14149 
14150   return new (Context) GNUNullExpr(Ty, TokenLoc);
14151 }
14152 
14153 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
14154                                     SourceLocation BuiltinLoc,
14155                                     SourceLocation RPLoc) {
14156   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
14157 }
14158 
14159 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
14160                                     SourceLocation BuiltinLoc,
14161                                     SourceLocation RPLoc,
14162                                     DeclContext *ParentContext) {
14163   return new (Context)
14164       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
14165 }
14166 
14167 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
14168                                               bool Diagnose) {
14169   if (!getLangOpts().ObjC)
14170     return false;
14171 
14172   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
14173   if (!PT)
14174     return false;
14175 
14176   if (!PT->isObjCIdType()) {
14177     // Check if the destination is the 'NSString' interface.
14178     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
14179     if (!ID || !ID->getIdentifier()->isStr("NSString"))
14180       return false;
14181   }
14182 
14183   // Ignore any parens, implicit casts (should only be
14184   // array-to-pointer decays), and not-so-opaque values.  The last is
14185   // important for making this trigger for property assignments.
14186   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
14187   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
14188     if (OV->getSourceExpr())
14189       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
14190 
14191   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
14192   if (!SL || !SL->isAscii())
14193     return false;
14194   if (Diagnose) {
14195     Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
14196         << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
14197     Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
14198   }
14199   return true;
14200 }
14201 
14202 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
14203                                               const Expr *SrcExpr) {
14204   if (!DstType->isFunctionPointerType() ||
14205       !SrcExpr->getType()->isFunctionType())
14206     return false;
14207 
14208   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
14209   if (!DRE)
14210     return false;
14211 
14212   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14213   if (!FD)
14214     return false;
14215 
14216   return !S.checkAddressOfFunctionIsAvailable(FD,
14217                                               /*Complain=*/true,
14218                                               SrcExpr->getBeginLoc());
14219 }
14220 
14221 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
14222                                     SourceLocation Loc,
14223                                     QualType DstType, QualType SrcType,
14224                                     Expr *SrcExpr, AssignmentAction Action,
14225                                     bool *Complained) {
14226   if (Complained)
14227     *Complained = false;
14228 
14229   // Decode the result (notice that AST's are still created for extensions).
14230   bool CheckInferredResultType = false;
14231   bool isInvalid = false;
14232   unsigned DiagKind = 0;
14233   FixItHint Hint;
14234   ConversionFixItGenerator ConvHints;
14235   bool MayHaveConvFixit = false;
14236   bool MayHaveFunctionDiff = false;
14237   const ObjCInterfaceDecl *IFace = nullptr;
14238   const ObjCProtocolDecl *PDecl = nullptr;
14239 
14240   switch (ConvTy) {
14241   case Compatible:
14242       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
14243       return false;
14244 
14245   case PointerToInt:
14246     DiagKind = diag::ext_typecheck_convert_pointer_int;
14247     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14248     MayHaveConvFixit = true;
14249     break;
14250   case IntToPointer:
14251     DiagKind = diag::ext_typecheck_convert_int_pointer;
14252     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14253     MayHaveConvFixit = true;
14254     break;
14255   case IncompatiblePointer:
14256     if (Action == AA_Passing_CFAudited)
14257       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
14258     else if (SrcType->isFunctionPointerType() &&
14259              DstType->isFunctionPointerType())
14260       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
14261     else
14262       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
14263 
14264     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
14265       SrcType->isObjCObjectPointerType();
14266     if (Hint.isNull() && !CheckInferredResultType) {
14267       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14268     }
14269     else if (CheckInferredResultType) {
14270       SrcType = SrcType.getUnqualifiedType();
14271       DstType = DstType.getUnqualifiedType();
14272     }
14273     MayHaveConvFixit = true;
14274     break;
14275   case IncompatiblePointerSign:
14276     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
14277     break;
14278   case FunctionVoidPointer:
14279     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
14280     break;
14281   case IncompatiblePointerDiscardsQualifiers: {
14282     // Perform array-to-pointer decay if necessary.
14283     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
14284 
14285     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
14286     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
14287     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
14288       DiagKind = diag::err_typecheck_incompatible_address_space;
14289       break;
14290 
14291     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
14292       DiagKind = diag::err_typecheck_incompatible_ownership;
14293       break;
14294     }
14295 
14296     llvm_unreachable("unknown error case for discarding qualifiers!");
14297     // fallthrough
14298   }
14299   case CompatiblePointerDiscardsQualifiers:
14300     // If the qualifiers lost were because we were applying the
14301     // (deprecated) C++ conversion from a string literal to a char*
14302     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
14303     // Ideally, this check would be performed in
14304     // checkPointerTypesForAssignment. However, that would require a
14305     // bit of refactoring (so that the second argument is an
14306     // expression, rather than a type), which should be done as part
14307     // of a larger effort to fix checkPointerTypesForAssignment for
14308     // C++ semantics.
14309     if (getLangOpts().CPlusPlus &&
14310         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
14311       return false;
14312     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
14313     break;
14314   case IncompatibleNestedPointerQualifiers:
14315     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
14316     break;
14317   case IncompatibleNestedPointerAddressSpaceMismatch:
14318     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
14319     break;
14320   case IntToBlockPointer:
14321     DiagKind = diag::err_int_to_block_pointer;
14322     break;
14323   case IncompatibleBlockPointer:
14324     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
14325     break;
14326   case IncompatibleObjCQualifiedId: {
14327     if (SrcType->isObjCQualifiedIdType()) {
14328       const ObjCObjectPointerType *srcOPT =
14329                 SrcType->getAs<ObjCObjectPointerType>();
14330       for (auto *srcProto : srcOPT->quals()) {
14331         PDecl = srcProto;
14332         break;
14333       }
14334       if (const ObjCInterfaceType *IFaceT =
14335             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
14336         IFace = IFaceT->getDecl();
14337     }
14338     else if (DstType->isObjCQualifiedIdType()) {
14339       const ObjCObjectPointerType *dstOPT =
14340         DstType->getAs<ObjCObjectPointerType>();
14341       for (auto *dstProto : dstOPT->quals()) {
14342         PDecl = dstProto;
14343         break;
14344       }
14345       if (const ObjCInterfaceType *IFaceT =
14346             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
14347         IFace = IFaceT->getDecl();
14348     }
14349     DiagKind = diag::warn_incompatible_qualified_id;
14350     break;
14351   }
14352   case IncompatibleVectors:
14353     DiagKind = diag::warn_incompatible_vectors;
14354     break;
14355   case IncompatibleObjCWeakRef:
14356     DiagKind = diag::err_arc_weak_unavailable_assign;
14357     break;
14358   case Incompatible:
14359     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
14360       if (Complained)
14361         *Complained = true;
14362       return true;
14363     }
14364 
14365     DiagKind = diag::err_typecheck_convert_incompatible;
14366     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14367     MayHaveConvFixit = true;
14368     isInvalid = true;
14369     MayHaveFunctionDiff = true;
14370     break;
14371   }
14372 
14373   QualType FirstType, SecondType;
14374   switch (Action) {
14375   case AA_Assigning:
14376   case AA_Initializing:
14377     // The destination type comes first.
14378     FirstType = DstType;
14379     SecondType = SrcType;
14380     break;
14381 
14382   case AA_Returning:
14383   case AA_Passing:
14384   case AA_Passing_CFAudited:
14385   case AA_Converting:
14386   case AA_Sending:
14387   case AA_Casting:
14388     // The source type comes first.
14389     FirstType = SrcType;
14390     SecondType = DstType;
14391     break;
14392   }
14393 
14394   PartialDiagnostic FDiag = PDiag(DiagKind);
14395   if (Action == AA_Passing_CFAudited)
14396     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
14397   else
14398     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
14399 
14400   // If we can fix the conversion, suggest the FixIts.
14401   assert(ConvHints.isNull() || Hint.isNull());
14402   if (!ConvHints.isNull()) {
14403     for (FixItHint &H : ConvHints.Hints)
14404       FDiag << H;
14405   } else {
14406     FDiag << Hint;
14407   }
14408   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
14409 
14410   if (MayHaveFunctionDiff)
14411     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
14412 
14413   Diag(Loc, FDiag);
14414   if (DiagKind == diag::warn_incompatible_qualified_id &&
14415       PDecl && IFace && !IFace->hasDefinition())
14416       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
14417         << IFace << PDecl;
14418 
14419   if (SecondType == Context.OverloadTy)
14420     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
14421                               FirstType, /*TakingAddress=*/true);
14422 
14423   if (CheckInferredResultType)
14424     EmitRelatedResultTypeNote(SrcExpr);
14425 
14426   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
14427     EmitRelatedResultTypeNoteForReturn(DstType);
14428 
14429   if (Complained)
14430     *Complained = true;
14431   return isInvalid;
14432 }
14433 
14434 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14435                                                  llvm::APSInt *Result) {
14436   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
14437   public:
14438     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14439       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
14440     }
14441   } Diagnoser;
14442 
14443   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
14444 }
14445 
14446 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14447                                                  llvm::APSInt *Result,
14448                                                  unsigned DiagID,
14449                                                  bool AllowFold) {
14450   class IDDiagnoser : public VerifyICEDiagnoser {
14451     unsigned DiagID;
14452 
14453   public:
14454     IDDiagnoser(unsigned DiagID)
14455       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
14456 
14457     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14458       S.Diag(Loc, DiagID) << SR;
14459     }
14460   } Diagnoser(DiagID);
14461 
14462   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
14463 }
14464 
14465 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
14466                                             SourceRange SR) {
14467   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
14468 }
14469 
14470 ExprResult
14471 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
14472                                       VerifyICEDiagnoser &Diagnoser,
14473                                       bool AllowFold) {
14474   SourceLocation DiagLoc = E->getBeginLoc();
14475 
14476   if (getLangOpts().CPlusPlus11) {
14477     // C++11 [expr.const]p5:
14478     //   If an expression of literal class type is used in a context where an
14479     //   integral constant expression is required, then that class type shall
14480     //   have a single non-explicit conversion function to an integral or
14481     //   unscoped enumeration type
14482     ExprResult Converted;
14483     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
14484     public:
14485       CXX11ConvertDiagnoser(bool Silent)
14486           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
14487                                 Silent, true) {}
14488 
14489       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
14490                                            QualType T) override {
14491         return S.Diag(Loc, diag::err_ice_not_integral) << T;
14492       }
14493 
14494       SemaDiagnosticBuilder diagnoseIncomplete(
14495           Sema &S, SourceLocation Loc, QualType T) override {
14496         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
14497       }
14498 
14499       SemaDiagnosticBuilder diagnoseExplicitConv(
14500           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14501         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
14502       }
14503 
14504       SemaDiagnosticBuilder noteExplicitConv(
14505           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14506         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14507                  << ConvTy->isEnumeralType() << ConvTy;
14508       }
14509 
14510       SemaDiagnosticBuilder diagnoseAmbiguous(
14511           Sema &S, SourceLocation Loc, QualType T) override {
14512         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
14513       }
14514 
14515       SemaDiagnosticBuilder noteAmbiguous(
14516           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14517         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14518                  << ConvTy->isEnumeralType() << ConvTy;
14519       }
14520 
14521       SemaDiagnosticBuilder diagnoseConversion(
14522           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14523         llvm_unreachable("conversion functions are permitted");
14524       }
14525     } ConvertDiagnoser(Diagnoser.Suppress);
14526 
14527     Converted = PerformContextualImplicitConversion(DiagLoc, E,
14528                                                     ConvertDiagnoser);
14529     if (Converted.isInvalid())
14530       return Converted;
14531     E = Converted.get();
14532     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
14533       return ExprError();
14534   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
14535     // An ICE must be of integral or unscoped enumeration type.
14536     if (!Diagnoser.Suppress)
14537       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14538     return ExprError();
14539   }
14540 
14541   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
14542   // in the non-ICE case.
14543   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
14544     if (Result)
14545       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
14546     if (!isa<ConstantExpr>(E))
14547       E = ConstantExpr::Create(Context, E);
14548     return E;
14549   }
14550 
14551   Expr::EvalResult EvalResult;
14552   SmallVector<PartialDiagnosticAt, 8> Notes;
14553   EvalResult.Diag = &Notes;
14554 
14555   // Try to evaluate the expression, and produce diagnostics explaining why it's
14556   // not a constant expression as a side-effect.
14557   bool Folded =
14558       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
14559       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
14560 
14561   if (!isa<ConstantExpr>(E))
14562     E = ConstantExpr::Create(Context, E, EvalResult.Val);
14563 
14564   // In C++11, we can rely on diagnostics being produced for any expression
14565   // which is not a constant expression. If no diagnostics were produced, then
14566   // this is a constant expression.
14567   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
14568     if (Result)
14569       *Result = EvalResult.Val.getInt();
14570     return E;
14571   }
14572 
14573   // If our only note is the usual "invalid subexpression" note, just point
14574   // the caret at its location rather than producing an essentially
14575   // redundant note.
14576   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14577         diag::note_invalid_subexpr_in_const_expr) {
14578     DiagLoc = Notes[0].first;
14579     Notes.clear();
14580   }
14581 
14582   if (!Folded || !AllowFold) {
14583     if (!Diagnoser.Suppress) {
14584       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14585       for (const PartialDiagnosticAt &Note : Notes)
14586         Diag(Note.first, Note.second);
14587     }
14588 
14589     return ExprError();
14590   }
14591 
14592   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
14593   for (const PartialDiagnosticAt &Note : Notes)
14594     Diag(Note.first, Note.second);
14595 
14596   if (Result)
14597     *Result = EvalResult.Val.getInt();
14598   return E;
14599 }
14600 
14601 namespace {
14602   // Handle the case where we conclude a expression which we speculatively
14603   // considered to be unevaluated is actually evaluated.
14604   class TransformToPE : public TreeTransform<TransformToPE> {
14605     typedef TreeTransform<TransformToPE> BaseTransform;
14606 
14607   public:
14608     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
14609 
14610     // Make sure we redo semantic analysis
14611     bool AlwaysRebuild() { return true; }
14612     bool ReplacingOriginal() { return true; }
14613 
14614     // We need to special-case DeclRefExprs referring to FieldDecls which
14615     // are not part of a member pointer formation; normal TreeTransforming
14616     // doesn't catch this case because of the way we represent them in the AST.
14617     // FIXME: This is a bit ugly; is it really the best way to handle this
14618     // case?
14619     //
14620     // Error on DeclRefExprs referring to FieldDecls.
14621     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
14622       if (isa<FieldDecl>(E->getDecl()) &&
14623           !SemaRef.isUnevaluatedContext())
14624         return SemaRef.Diag(E->getLocation(),
14625                             diag::err_invalid_non_static_member_use)
14626             << E->getDecl() << E->getSourceRange();
14627 
14628       return BaseTransform::TransformDeclRefExpr(E);
14629     }
14630 
14631     // Exception: filter out member pointer formation
14632     ExprResult TransformUnaryOperator(UnaryOperator *E) {
14633       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
14634         return E;
14635 
14636       return BaseTransform::TransformUnaryOperator(E);
14637     }
14638 
14639     // The body of a lambda-expression is in a separate expression evaluation
14640     // context so never needs to be transformed.
14641     // FIXME: Ideally we wouldn't transform the closure type either, and would
14642     // just recreate the capture expressions and lambda expression.
14643     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
14644       return SkipLambdaBody(E, Body);
14645     }
14646   };
14647 }
14648 
14649 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
14650   assert(isUnevaluatedContext() &&
14651          "Should only transform unevaluated expressions");
14652   ExprEvalContexts.back().Context =
14653       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
14654   if (isUnevaluatedContext())
14655     return E;
14656   return TransformToPE(*this).TransformExpr(E);
14657 }
14658 
14659 void
14660 Sema::PushExpressionEvaluationContext(
14661     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
14662     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
14663   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
14664                                 LambdaContextDecl, ExprContext);
14665   Cleanup.reset();
14666   if (!MaybeODRUseExprs.empty())
14667     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
14668 }
14669 
14670 void
14671 Sema::PushExpressionEvaluationContext(
14672     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
14673     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
14674   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
14675   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
14676 }
14677 
14678 namespace {
14679 
14680 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
14681   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
14682   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
14683     if (E->getOpcode() == UO_Deref)
14684       return CheckPossibleDeref(S, E->getSubExpr());
14685   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
14686     return CheckPossibleDeref(S, E->getBase());
14687   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
14688     return CheckPossibleDeref(S, E->getBase());
14689   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
14690     QualType Inner;
14691     QualType Ty = E->getType();
14692     if (const auto *Ptr = Ty->getAs<PointerType>())
14693       Inner = Ptr->getPointeeType();
14694     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
14695       Inner = Arr->getElementType();
14696     else
14697       return nullptr;
14698 
14699     if (Inner->hasAttr(attr::NoDeref))
14700       return E;
14701   }
14702   return nullptr;
14703 }
14704 
14705 } // namespace
14706 
14707 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
14708   for (const Expr *E : Rec.PossibleDerefs) {
14709     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
14710     if (DeclRef) {
14711       const ValueDecl *Decl = DeclRef->getDecl();
14712       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
14713           << Decl->getName() << E->getSourceRange();
14714       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
14715     } else {
14716       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
14717           << E->getSourceRange();
14718     }
14719   }
14720   Rec.PossibleDerefs.clear();
14721 }
14722 
14723 void Sema::PopExpressionEvaluationContext() {
14724   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
14725   unsigned NumTypos = Rec.NumTypos;
14726 
14727   if (!Rec.Lambdas.empty()) {
14728     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
14729     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
14730         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
14731       unsigned D;
14732       if (Rec.isUnevaluated()) {
14733         // C++11 [expr.prim.lambda]p2:
14734         //   A lambda-expression shall not appear in an unevaluated operand
14735         //   (Clause 5).
14736         D = diag::err_lambda_unevaluated_operand;
14737       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
14738         // C++1y [expr.const]p2:
14739         //   A conditional-expression e is a core constant expression unless the
14740         //   evaluation of e, following the rules of the abstract machine, would
14741         //   evaluate [...] a lambda-expression.
14742         D = diag::err_lambda_in_constant_expression;
14743       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
14744         // C++17 [expr.prim.lamda]p2:
14745         // A lambda-expression shall not appear [...] in a template-argument.
14746         D = diag::err_lambda_in_invalid_context;
14747       } else
14748         llvm_unreachable("Couldn't infer lambda error message.");
14749 
14750       for (const auto *L : Rec.Lambdas)
14751         Diag(L->getBeginLoc(), D);
14752     }
14753   }
14754 
14755   WarnOnPendingNoDerefs(Rec);
14756 
14757   // When are coming out of an unevaluated context, clear out any
14758   // temporaries that we may have created as part of the evaluation of
14759   // the expression in that context: they aren't relevant because they
14760   // will never be constructed.
14761   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
14762     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
14763                              ExprCleanupObjects.end());
14764     Cleanup = Rec.ParentCleanup;
14765     CleanupVarDeclMarking();
14766     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
14767   // Otherwise, merge the contexts together.
14768   } else {
14769     Cleanup.mergeFrom(Rec.ParentCleanup);
14770     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
14771                             Rec.SavedMaybeODRUseExprs.end());
14772   }
14773 
14774   // Pop the current expression evaluation context off the stack.
14775   ExprEvalContexts.pop_back();
14776 
14777   // The global expression evaluation context record is never popped.
14778   ExprEvalContexts.back().NumTypos += NumTypos;
14779 }
14780 
14781 void Sema::DiscardCleanupsInEvaluationContext() {
14782   ExprCleanupObjects.erase(
14783          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
14784          ExprCleanupObjects.end());
14785   Cleanup.reset();
14786   MaybeODRUseExprs.clear();
14787 }
14788 
14789 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
14790   ExprResult Result = CheckPlaceholderExpr(E);
14791   if (Result.isInvalid())
14792     return ExprError();
14793   E = Result.get();
14794   if (!E->getType()->isVariablyModifiedType())
14795     return E;
14796   return TransformToPotentiallyEvaluated(E);
14797 }
14798 
14799 /// Are we in a context that is potentially constant evaluated per C++20
14800 /// [expr.const]p12?
14801 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
14802   /// C++2a [expr.const]p12:
14803   //   An expression or conversion is potentially constant evaluated if it is
14804   switch (SemaRef.ExprEvalContexts.back().Context) {
14805     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
14806       // -- a manifestly constant-evaluated expression,
14807     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
14808     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14809     case Sema::ExpressionEvaluationContext::DiscardedStatement:
14810       // -- a potentially-evaluated expression,
14811     case Sema::ExpressionEvaluationContext::UnevaluatedList:
14812       // -- an immediate subexpression of a braced-init-list,
14813 
14814       // -- [FIXME] an expression of the form & cast-expression that occurs
14815       //    within a templated entity
14816       // -- a subexpression of one of the above that is not a subexpression of
14817       // a nested unevaluated operand.
14818       return true;
14819 
14820     case Sema::ExpressionEvaluationContext::Unevaluated:
14821     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
14822       // Expressions in this context are never evaluated.
14823       return false;
14824   }
14825   llvm_unreachable("Invalid context");
14826 }
14827 
14828 /// Return true if this function has a calling convention that requires mangling
14829 /// in the size of the parameter pack.
14830 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
14831   // These manglings don't do anything on non-Windows or non-x86 platforms, so
14832   // we don't need parameter type sizes.
14833   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
14834   if (!TT.isOSWindows() || (TT.getArch() != llvm::Triple::x86 &&
14835                             TT.getArch() != llvm::Triple::x86_64))
14836     return false;
14837 
14838   // If this is C++ and this isn't an extern "C" function, parameters do not
14839   // need to be complete. In this case, C++ mangling will apply, which doesn't
14840   // use the size of the parameters.
14841   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
14842     return false;
14843 
14844   // Stdcall, fastcall, and vectorcall need this special treatment.
14845   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
14846   switch (CC) {
14847   case CC_X86StdCall:
14848   case CC_X86FastCall:
14849   case CC_X86VectorCall:
14850     return true;
14851   default:
14852     break;
14853   }
14854   return false;
14855 }
14856 
14857 /// Require that all of the parameter types of function be complete. Normally,
14858 /// parameter types are only required to be complete when a function is called
14859 /// or defined, but to mangle functions with certain calling conventions, the
14860 /// mangler needs to know the size of the parameter list. In this situation,
14861 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
14862 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
14863 /// result in a linker error. Clang doesn't implement this behavior, and instead
14864 /// attempts to error at compile time.
14865 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
14866                                                   SourceLocation Loc) {
14867   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
14868     FunctionDecl *FD;
14869     ParmVarDecl *Param;
14870 
14871   public:
14872     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
14873         : FD(FD), Param(Param) {}
14874 
14875     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
14876       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
14877       StringRef CCName;
14878       switch (CC) {
14879       case CC_X86StdCall:
14880         CCName = "stdcall";
14881         break;
14882       case CC_X86FastCall:
14883         CCName = "fastcall";
14884         break;
14885       case CC_X86VectorCall:
14886         CCName = "vectorcall";
14887         break;
14888       default:
14889         llvm_unreachable("CC does not need mangling");
14890       }
14891 
14892       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
14893           << Param->getDeclName() << FD->getDeclName() << CCName;
14894     }
14895   };
14896 
14897   for (ParmVarDecl *Param : FD->parameters()) {
14898     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
14899     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
14900   }
14901 }
14902 
14903 namespace {
14904 enum class OdrUseContext {
14905   /// Declarations in this context are not odr-used.
14906   None,
14907   /// Declarations in this context are formally odr-used, but this is a
14908   /// dependent context.
14909   Dependent,
14910   /// Declarations in this context are odr-used but not actually used (yet).
14911   FormallyOdrUsed,
14912   /// Declarations in this context are used.
14913   Used
14914 };
14915 }
14916 
14917 /// Are we within a context in which references to resolved functions or to
14918 /// variables result in odr-use?
14919 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
14920   OdrUseContext Result;
14921 
14922   switch (SemaRef.ExprEvalContexts.back().Context) {
14923     case Sema::ExpressionEvaluationContext::Unevaluated:
14924     case Sema::ExpressionEvaluationContext::UnevaluatedList:
14925     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
14926       return OdrUseContext::None;
14927 
14928     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
14929     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
14930       Result = OdrUseContext::Used;
14931       break;
14932 
14933     case Sema::ExpressionEvaluationContext::DiscardedStatement:
14934       Result = OdrUseContext::FormallyOdrUsed;
14935       break;
14936 
14937     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14938       // A default argument formally results in odr-use, but doesn't actually
14939       // result in a use in any real sense until it itself is used.
14940       Result = OdrUseContext::FormallyOdrUsed;
14941       break;
14942   }
14943 
14944   if (SemaRef.CurContext->isDependentContext())
14945     return OdrUseContext::Dependent;
14946 
14947   return Result;
14948 }
14949 
14950 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
14951   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
14952   return Func->isConstexpr() &&
14953          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
14954 }
14955 
14956 /// Mark a function referenced, and check whether it is odr-used
14957 /// (C++ [basic.def.odr]p2, C99 6.9p3)
14958 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
14959                                   bool MightBeOdrUse) {
14960   assert(Func && "No function?");
14961 
14962   Func->setReferenced();
14963 
14964   // Recursive functions aren't really used until they're used from some other
14965   // context.
14966   bool IsRecursiveCall = CurContext == Func;
14967 
14968   // C++11 [basic.def.odr]p3:
14969   //   A function whose name appears as a potentially-evaluated expression is
14970   //   odr-used if it is the unique lookup result or the selected member of a
14971   //   set of overloaded functions [...].
14972   //
14973   // We (incorrectly) mark overload resolution as an unevaluated context, so we
14974   // can just check that here.
14975   OdrUseContext OdrUse =
14976       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
14977   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
14978     OdrUse = OdrUseContext::FormallyOdrUsed;
14979 
14980   // C++20 [expr.const]p12:
14981   //   A function [...] is needed for constant evaluation if it is [...] a
14982   //   constexpr function that is named by an expression that is potentially
14983   //   constant evaluated
14984   bool NeededForConstantEvaluation =
14985       isPotentiallyConstantEvaluatedContext(*this) &&
14986       isImplicitlyDefinableConstexprFunction(Func);
14987 
14988   // Determine whether we require a function definition to exist, per
14989   // C++11 [temp.inst]p3:
14990   //   Unless a function template specialization has been explicitly
14991   //   instantiated or explicitly specialized, the function template
14992   //   specialization is implicitly instantiated when the specialization is
14993   //   referenced in a context that requires a function definition to exist.
14994   // C++20 [temp.inst]p7:
14995   //   The existence of a definition of a [...] function is considered to
14996   //   affect the semantics of the program if the [...] function is needed for
14997   //   constant evaluation by an expression
14998   // C++20 [basic.def.odr]p10:
14999   //   Every program shall contain exactly one definition of every non-inline
15000   //   function or variable that is odr-used in that program outside of a
15001   //   discarded statement
15002   // C++20 [special]p1:
15003   //   The implementation will implicitly define [defaulted special members]
15004   //   if they are odr-used or needed for constant evaluation.
15005   //
15006   // Note that we skip the implicit instantiation of templates that are only
15007   // used in unused default arguments or by recursive calls to themselves.
15008   // This is formally non-conforming, but seems reasonable in practice.
15009   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
15010                                              NeededForConstantEvaluation);
15011 
15012   // C++14 [temp.expl.spec]p6:
15013   //   If a template [...] is explicitly specialized then that specialization
15014   //   shall be declared before the first use of that specialization that would
15015   //   cause an implicit instantiation to take place, in every translation unit
15016   //   in which such a use occurs
15017   if (NeedDefinition &&
15018       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
15019        Func->getMemberSpecializationInfo()))
15020     checkSpecializationVisibility(Loc, Func);
15021 
15022   // C++14 [except.spec]p17:
15023   //   An exception-specification is considered to be needed when:
15024   //   - the function is odr-used or, if it appears in an unevaluated operand,
15025   //     would be odr-used if the expression were potentially-evaluated;
15026   //
15027   // Note, we do this even if MightBeOdrUse is false. That indicates that the
15028   // function is a pure virtual function we're calling, and in that case the
15029   // function was selected by overload resolution and we need to resolve its
15030   // exception specification for a different reason.
15031   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
15032   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
15033     ResolveExceptionSpec(Loc, FPT);
15034 
15035   if (getLangOpts().CUDA)
15036     CheckCUDACall(Loc, Func);
15037 
15038   // If we need a definition, try to create one.
15039   if (NeedDefinition && !Func->getBody()) {
15040     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
15041       Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
15042       if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
15043         if (Constructor->isDefaultConstructor()) {
15044           if (Constructor->isTrivial() &&
15045               !Constructor->hasAttr<DLLExportAttr>())
15046             return;
15047           DefineImplicitDefaultConstructor(Loc, Constructor);
15048         } else if (Constructor->isCopyConstructor()) {
15049           DefineImplicitCopyConstructor(Loc, Constructor);
15050         } else if (Constructor->isMoveConstructor()) {
15051           DefineImplicitMoveConstructor(Loc, Constructor);
15052         }
15053       } else if (Constructor->getInheritedConstructor()) {
15054         DefineInheritingConstructor(Loc, Constructor);
15055       }
15056     } else if (CXXDestructorDecl *Destructor =
15057                    dyn_cast<CXXDestructorDecl>(Func)) {
15058       Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
15059       if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
15060         if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
15061           return;
15062         DefineImplicitDestructor(Loc, Destructor);
15063       }
15064       if (Destructor->isVirtual() && getLangOpts().AppleKext)
15065         MarkVTableUsed(Loc, Destructor->getParent());
15066     } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
15067       if (MethodDecl->isOverloadedOperator() &&
15068           MethodDecl->getOverloadedOperator() == OO_Equal) {
15069         MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
15070         if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
15071           if (MethodDecl->isCopyAssignmentOperator())
15072             DefineImplicitCopyAssignment(Loc, MethodDecl);
15073           else if (MethodDecl->isMoveAssignmentOperator())
15074             DefineImplicitMoveAssignment(Loc, MethodDecl);
15075         }
15076       } else if (isa<CXXConversionDecl>(MethodDecl) &&
15077                  MethodDecl->getParent()->isLambda()) {
15078         CXXConversionDecl *Conversion =
15079             cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
15080         if (Conversion->isLambdaToBlockPointerConversion())
15081           DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
15082         else
15083           DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
15084       } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
15085         MarkVTableUsed(Loc, MethodDecl->getParent());
15086     }
15087 
15088     // Implicit instantiation of function templates and member functions of
15089     // class templates.
15090     if (Func->isImplicitlyInstantiable()) {
15091       TemplateSpecializationKind TSK =
15092           Func->getTemplateSpecializationKindForInstantiation();
15093       SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
15094       bool FirstInstantiation = PointOfInstantiation.isInvalid();
15095       if (FirstInstantiation) {
15096         PointOfInstantiation = Loc;
15097         Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
15098       } else if (TSK != TSK_ImplicitInstantiation) {
15099         // Use the point of use as the point of instantiation, instead of the
15100         // point of explicit instantiation (which we track as the actual point
15101         // of instantiation). This gives better backtraces in diagnostics.
15102         PointOfInstantiation = Loc;
15103       }
15104 
15105       if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
15106           Func->isConstexpr()) {
15107         if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
15108             cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
15109             CodeSynthesisContexts.size())
15110           PendingLocalImplicitInstantiations.push_back(
15111               std::make_pair(Func, PointOfInstantiation));
15112         else if (Func->isConstexpr())
15113           // Do not defer instantiations of constexpr functions, to avoid the
15114           // expression evaluator needing to call back into Sema if it sees a
15115           // call to such a function.
15116           InstantiateFunctionDefinition(PointOfInstantiation, Func);
15117         else {
15118           Func->setInstantiationIsPending(true);
15119           PendingInstantiations.push_back(
15120               std::make_pair(Func, PointOfInstantiation));
15121           // Notify the consumer that a function was implicitly instantiated.
15122           Consumer.HandleCXXImplicitFunctionInstantiation(Func);
15123         }
15124       }
15125     } else {
15126       // Walk redefinitions, as some of them may be instantiable.
15127       for (auto i : Func->redecls()) {
15128         if (!i->isUsed(false) && i->isImplicitlyInstantiable())
15129           MarkFunctionReferenced(Loc, i, MightBeOdrUse);
15130       }
15131     }
15132   }
15133 
15134   // If this is the first "real" use, act on that.
15135   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
15136     // Keep track of used but undefined functions.
15137     if (!Func->isDefined()) {
15138       if (mightHaveNonExternalLinkage(Func))
15139         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15140       else if (Func->getMostRecentDecl()->isInlined() &&
15141                !LangOpts.GNUInline &&
15142                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
15143         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15144       else if (isExternalWithNoLinkageType(Func))
15145         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15146     }
15147 
15148     // Some x86 Windows calling conventions mangle the size of the parameter
15149     // pack into the name. Computing the size of the parameters requires the
15150     // parameter types to be complete. Check that now.
15151     if (funcHasParameterSizeMangling(*this, Func))
15152       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
15153 
15154     Func->markUsed(Context);
15155 
15156     if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)
15157       checkOpenMPDeviceFunction(Loc, Func);
15158   }
15159 }
15160 
15161 /// Directly mark a variable odr-used. Given a choice, prefer to use
15162 /// MarkVariableReferenced since it does additional checks and then
15163 /// calls MarkVarDeclODRUsed.
15164 /// If the variable must be captured:
15165 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
15166 ///  - else capture it in the DeclContext that maps to the
15167 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
15168 static void
15169 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
15170                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
15171   // Keep track of used but undefined variables.
15172   // FIXME: We shouldn't suppress this warning for static data members.
15173   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
15174       (!Var->isExternallyVisible() || Var->isInline() ||
15175        SemaRef.isExternalWithNoLinkageType(Var)) &&
15176       !(Var->isStaticDataMember() && Var->hasInit())) {
15177     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
15178     if (old.isInvalid())
15179       old = Loc;
15180   }
15181   QualType CaptureType, DeclRefType;
15182   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
15183     /*EllipsisLoc*/ SourceLocation(),
15184     /*BuildAndDiagnose*/ true,
15185     CaptureType, DeclRefType,
15186     FunctionScopeIndexToStopAt);
15187 
15188   Var->markUsed(SemaRef.Context);
15189 }
15190 
15191 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
15192                                              SourceLocation Loc,
15193                                              unsigned CapturingScopeIndex) {
15194   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
15195 }
15196 
15197 static void
15198 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
15199                                    ValueDecl *var, DeclContext *DC) {
15200   DeclContext *VarDC = var->getDeclContext();
15201 
15202   //  If the parameter still belongs to the translation unit, then
15203   //  we're actually just using one parameter in the declaration of
15204   //  the next.
15205   if (isa<ParmVarDecl>(var) &&
15206       isa<TranslationUnitDecl>(VarDC))
15207     return;
15208 
15209   // For C code, don't diagnose about capture if we're not actually in code
15210   // right now; it's impossible to write a non-constant expression outside of
15211   // function context, so we'll get other (more useful) diagnostics later.
15212   //
15213   // For C++, things get a bit more nasty... it would be nice to suppress this
15214   // diagnostic for certain cases like using a local variable in an array bound
15215   // for a member of a local class, but the correct predicate is not obvious.
15216   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
15217     return;
15218 
15219   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
15220   unsigned ContextKind = 3; // unknown
15221   if (isa<CXXMethodDecl>(VarDC) &&
15222       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
15223     ContextKind = 2;
15224   } else if (isa<FunctionDecl>(VarDC)) {
15225     ContextKind = 0;
15226   } else if (isa<BlockDecl>(VarDC)) {
15227     ContextKind = 1;
15228   }
15229 
15230   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
15231     << var << ValueKind << ContextKind << VarDC;
15232   S.Diag(var->getLocation(), diag::note_entity_declared_at)
15233       << var;
15234 
15235   // FIXME: Add additional diagnostic info about class etc. which prevents
15236   // capture.
15237 }
15238 
15239 
15240 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
15241                                       bool &SubCapturesAreNested,
15242                                       QualType &CaptureType,
15243                                       QualType &DeclRefType) {
15244    // Check whether we've already captured it.
15245   if (CSI->CaptureMap.count(Var)) {
15246     // If we found a capture, any subcaptures are nested.
15247     SubCapturesAreNested = true;
15248 
15249     // Retrieve the capture type for this variable.
15250     CaptureType = CSI->getCapture(Var).getCaptureType();
15251 
15252     // Compute the type of an expression that refers to this variable.
15253     DeclRefType = CaptureType.getNonReferenceType();
15254 
15255     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
15256     // are mutable in the sense that user can change their value - they are
15257     // private instances of the captured declarations.
15258     const Capture &Cap = CSI->getCapture(Var);
15259     if (Cap.isCopyCapture() &&
15260         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
15261         !(isa<CapturedRegionScopeInfo>(CSI) &&
15262           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
15263       DeclRefType.addConst();
15264     return true;
15265   }
15266   return false;
15267 }
15268 
15269 // Only block literals, captured statements, and lambda expressions can
15270 // capture; other scopes don't work.
15271 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
15272                                  SourceLocation Loc,
15273                                  const bool Diagnose, Sema &S) {
15274   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
15275     return getLambdaAwareParentOfDeclContext(DC);
15276   else if (Var->hasLocalStorage()) {
15277     if (Diagnose)
15278        diagnoseUncapturableValueReference(S, Loc, Var, DC);
15279   }
15280   return nullptr;
15281 }
15282 
15283 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
15284 // certain types of variables (unnamed, variably modified types etc.)
15285 // so check for eligibility.
15286 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
15287                                  SourceLocation Loc,
15288                                  const bool Diagnose, Sema &S) {
15289 
15290   bool IsBlock = isa<BlockScopeInfo>(CSI);
15291   bool IsLambda = isa<LambdaScopeInfo>(CSI);
15292 
15293   // Lambdas are not allowed to capture unnamed variables
15294   // (e.g. anonymous unions).
15295   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
15296   // assuming that's the intent.
15297   if (IsLambda && !Var->getDeclName()) {
15298     if (Diagnose) {
15299       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
15300       S.Diag(Var->getLocation(), diag::note_declared_at);
15301     }
15302     return false;
15303   }
15304 
15305   // Prohibit variably-modified types in blocks; they're difficult to deal with.
15306   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
15307     if (Diagnose) {
15308       S.Diag(Loc, diag::err_ref_vm_type);
15309       S.Diag(Var->getLocation(), diag::note_previous_decl)
15310         << Var->getDeclName();
15311     }
15312     return false;
15313   }
15314   // Prohibit structs with flexible array members too.
15315   // We cannot capture what is in the tail end of the struct.
15316   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
15317     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
15318       if (Diagnose) {
15319         if (IsBlock)
15320           S.Diag(Loc, diag::err_ref_flexarray_type);
15321         else
15322           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
15323             << Var->getDeclName();
15324         S.Diag(Var->getLocation(), diag::note_previous_decl)
15325           << Var->getDeclName();
15326       }
15327       return false;
15328     }
15329   }
15330   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15331   // Lambdas and captured statements are not allowed to capture __block
15332   // variables; they don't support the expected semantics.
15333   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
15334     if (Diagnose) {
15335       S.Diag(Loc, diag::err_capture_block_variable)
15336         << Var->getDeclName() << !IsLambda;
15337       S.Diag(Var->getLocation(), diag::note_previous_decl)
15338         << Var->getDeclName();
15339     }
15340     return false;
15341   }
15342   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
15343   if (S.getLangOpts().OpenCL && IsBlock &&
15344       Var->getType()->isBlockPointerType()) {
15345     if (Diagnose)
15346       S.Diag(Loc, diag::err_opencl_block_ref_block);
15347     return false;
15348   }
15349 
15350   return true;
15351 }
15352 
15353 // Returns true if the capture by block was successful.
15354 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
15355                                  SourceLocation Loc,
15356                                  const bool BuildAndDiagnose,
15357                                  QualType &CaptureType,
15358                                  QualType &DeclRefType,
15359                                  const bool Nested,
15360                                  Sema &S, bool Invalid) {
15361   bool ByRef = false;
15362 
15363   // Blocks are not allowed to capture arrays, excepting OpenCL.
15364   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
15365   // (decayed to pointers).
15366   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
15367     if (BuildAndDiagnose) {
15368       S.Diag(Loc, diag::err_ref_array_type);
15369       S.Diag(Var->getLocation(), diag::note_previous_decl)
15370       << Var->getDeclName();
15371       Invalid = true;
15372     } else {
15373       return false;
15374     }
15375   }
15376 
15377   // Forbid the block-capture of autoreleasing variables.
15378   if (!Invalid &&
15379       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
15380     if (BuildAndDiagnose) {
15381       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
15382         << /*block*/ 0;
15383       S.Diag(Var->getLocation(), diag::note_previous_decl)
15384         << Var->getDeclName();
15385       Invalid = true;
15386     } else {
15387       return false;
15388     }
15389   }
15390 
15391   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
15392   if (const auto *PT = CaptureType->getAs<PointerType>()) {
15393     // This function finds out whether there is an AttributedType of kind
15394     // attr::ObjCOwnership in Ty. The existence of AttributedType of kind
15395     // attr::ObjCOwnership implies __autoreleasing was explicitly specified
15396     // rather than being added implicitly by the compiler.
15397     auto IsObjCOwnershipAttributedType = [](QualType Ty) {
15398       while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
15399         if (AttrTy->getAttrKind() == attr::ObjCOwnership)
15400           return true;
15401 
15402         // Peel off AttributedTypes that are not of kind ObjCOwnership.
15403         Ty = AttrTy->getModifiedType();
15404       }
15405 
15406       return false;
15407     };
15408 
15409     QualType PointeeTy = PT->getPointeeType();
15410 
15411     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
15412         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
15413         !IsObjCOwnershipAttributedType(PointeeTy)) {
15414       if (BuildAndDiagnose) {
15415         SourceLocation VarLoc = Var->getLocation();
15416         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
15417         S.Diag(VarLoc, diag::note_declare_parameter_strong);
15418       }
15419     }
15420   }
15421 
15422   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15423   if (HasBlocksAttr || CaptureType->isReferenceType() ||
15424       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
15425     // Block capture by reference does not change the capture or
15426     // declaration reference types.
15427     ByRef = true;
15428   } else {
15429     // Block capture by copy introduces 'const'.
15430     CaptureType = CaptureType.getNonReferenceType().withConst();
15431     DeclRefType = CaptureType;
15432   }
15433 
15434   // Actually capture the variable.
15435   if (BuildAndDiagnose)
15436     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
15437                     CaptureType, Invalid);
15438 
15439   return !Invalid;
15440 }
15441 
15442 
15443 /// Capture the given variable in the captured region.
15444 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
15445                                     VarDecl *Var,
15446                                     SourceLocation Loc,
15447                                     const bool BuildAndDiagnose,
15448                                     QualType &CaptureType,
15449                                     QualType &DeclRefType,
15450                                     const bool RefersToCapturedVariable,
15451                                     Sema &S, bool Invalid) {
15452   // By default, capture variables by reference.
15453   bool ByRef = true;
15454   // Using an LValue reference type is consistent with Lambdas (see below).
15455   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
15456     if (S.isOpenMPCapturedDecl(Var)) {
15457       bool HasConst = DeclRefType.isConstQualified();
15458       DeclRefType = DeclRefType.getUnqualifiedType();
15459       // Don't lose diagnostics about assignments to const.
15460       if (HasConst)
15461         DeclRefType.addConst();
15462     }
15463     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
15464   }
15465 
15466   if (ByRef)
15467     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
15468   else
15469     CaptureType = DeclRefType;
15470 
15471   // Actually capture the variable.
15472   if (BuildAndDiagnose)
15473     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
15474                     Loc, SourceLocation(), CaptureType, Invalid);
15475 
15476   return !Invalid;
15477 }
15478 
15479 /// Capture the given variable in the lambda.
15480 static bool captureInLambda(LambdaScopeInfo *LSI,
15481                             VarDecl *Var,
15482                             SourceLocation Loc,
15483                             const bool BuildAndDiagnose,
15484                             QualType &CaptureType,
15485                             QualType &DeclRefType,
15486                             const bool RefersToCapturedVariable,
15487                             const Sema::TryCaptureKind Kind,
15488                             SourceLocation EllipsisLoc,
15489                             const bool IsTopScope,
15490                             Sema &S, bool Invalid) {
15491   // Determine whether we are capturing by reference or by value.
15492   bool ByRef = false;
15493   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
15494     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
15495   } else {
15496     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
15497   }
15498 
15499   // Compute the type of the field that will capture this variable.
15500   if (ByRef) {
15501     // C++11 [expr.prim.lambda]p15:
15502     //   An entity is captured by reference if it is implicitly or
15503     //   explicitly captured but not captured by copy. It is
15504     //   unspecified whether additional unnamed non-static data
15505     //   members are declared in the closure type for entities
15506     //   captured by reference.
15507     //
15508     // FIXME: It is not clear whether we want to build an lvalue reference
15509     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
15510     // to do the former, while EDG does the latter. Core issue 1249 will
15511     // clarify, but for now we follow GCC because it's a more permissive and
15512     // easily defensible position.
15513     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
15514   } else {
15515     // C++11 [expr.prim.lambda]p14:
15516     //   For each entity captured by copy, an unnamed non-static
15517     //   data member is declared in the closure type. The
15518     //   declaration order of these members is unspecified. The type
15519     //   of such a data member is the type of the corresponding
15520     //   captured entity if the entity is not a reference to an
15521     //   object, or the referenced type otherwise. [Note: If the
15522     //   captured entity is a reference to a function, the
15523     //   corresponding data member is also a reference to a
15524     //   function. - end note ]
15525     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
15526       if (!RefType->getPointeeType()->isFunctionType())
15527         CaptureType = RefType->getPointeeType();
15528     }
15529 
15530     // Forbid the lambda copy-capture of autoreleasing variables.
15531     if (!Invalid &&
15532         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
15533       if (BuildAndDiagnose) {
15534         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
15535         S.Diag(Var->getLocation(), diag::note_previous_decl)
15536           << Var->getDeclName();
15537         Invalid = true;
15538       } else {
15539         return false;
15540       }
15541     }
15542 
15543     // Make sure that by-copy captures are of a complete and non-abstract type.
15544     if (!Invalid && BuildAndDiagnose) {
15545       if (!CaptureType->isDependentType() &&
15546           S.RequireCompleteType(Loc, CaptureType,
15547                                 diag::err_capture_of_incomplete_type,
15548                                 Var->getDeclName()))
15549         Invalid = true;
15550       else if (S.RequireNonAbstractType(Loc, CaptureType,
15551                                         diag::err_capture_of_abstract_type))
15552         Invalid = true;
15553     }
15554   }
15555 
15556   // Compute the type of a reference to this captured variable.
15557   if (ByRef)
15558     DeclRefType = CaptureType.getNonReferenceType();
15559   else {
15560     // C++ [expr.prim.lambda]p5:
15561     //   The closure type for a lambda-expression has a public inline
15562     //   function call operator [...]. This function call operator is
15563     //   declared const (9.3.1) if and only if the lambda-expression's
15564     //   parameter-declaration-clause is not followed by mutable.
15565     DeclRefType = CaptureType.getNonReferenceType();
15566     if (!LSI->Mutable && !CaptureType->isReferenceType())
15567       DeclRefType.addConst();
15568   }
15569 
15570   // Add the capture.
15571   if (BuildAndDiagnose)
15572     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
15573                     Loc, EllipsisLoc, CaptureType, Invalid);
15574 
15575   return !Invalid;
15576 }
15577 
15578 bool Sema::tryCaptureVariable(
15579     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
15580     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
15581     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
15582   // An init-capture is notionally from the context surrounding its
15583   // declaration, but its parent DC is the lambda class.
15584   DeclContext *VarDC = Var->getDeclContext();
15585   if (Var->isInitCapture())
15586     VarDC = VarDC->getParent();
15587 
15588   DeclContext *DC = CurContext;
15589   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
15590       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
15591   // We need to sync up the Declaration Context with the
15592   // FunctionScopeIndexToStopAt
15593   if (FunctionScopeIndexToStopAt) {
15594     unsigned FSIndex = FunctionScopes.size() - 1;
15595     while (FSIndex != MaxFunctionScopesIndex) {
15596       DC = getLambdaAwareParentOfDeclContext(DC);
15597       --FSIndex;
15598     }
15599   }
15600 
15601 
15602   // If the variable is declared in the current context, there is no need to
15603   // capture it.
15604   if (VarDC == DC) return true;
15605 
15606   // Capture global variables if it is required to use private copy of this
15607   // variable.
15608   bool IsGlobal = !Var->hasLocalStorage();
15609   if (IsGlobal &&
15610       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
15611                                                 MaxFunctionScopesIndex)))
15612     return true;
15613   Var = Var->getCanonicalDecl();
15614 
15615   // Walk up the stack to determine whether we can capture the variable,
15616   // performing the "simple" checks that don't depend on type. We stop when
15617   // we've either hit the declared scope of the variable or find an existing
15618   // capture of that variable.  We start from the innermost capturing-entity
15619   // (the DC) and ensure that all intervening capturing-entities
15620   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
15621   // declcontext can either capture the variable or have already captured
15622   // the variable.
15623   CaptureType = Var->getType();
15624   DeclRefType = CaptureType.getNonReferenceType();
15625   bool Nested = false;
15626   bool Explicit = (Kind != TryCapture_Implicit);
15627   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
15628   do {
15629     // Only block literals, captured statements, and lambda expressions can
15630     // capture; other scopes don't work.
15631     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
15632                                                               ExprLoc,
15633                                                               BuildAndDiagnose,
15634                                                               *this);
15635     // We need to check for the parent *first* because, if we *have*
15636     // private-captured a global variable, we need to recursively capture it in
15637     // intermediate blocks, lambdas, etc.
15638     if (!ParentDC) {
15639       if (IsGlobal) {
15640         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
15641         break;
15642       }
15643       return true;
15644     }
15645 
15646     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
15647     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
15648 
15649 
15650     // Check whether we've already captured it.
15651     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
15652                                              DeclRefType)) {
15653       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
15654       break;
15655     }
15656     // If we are instantiating a generic lambda call operator body,
15657     // we do not want to capture new variables.  What was captured
15658     // during either a lambdas transformation or initial parsing
15659     // should be used.
15660     if (isGenericLambdaCallOperatorSpecialization(DC)) {
15661       if (BuildAndDiagnose) {
15662         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15663         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
15664           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15665           Diag(Var->getLocation(), diag::note_previous_decl)
15666              << Var->getDeclName();
15667           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
15668         } else
15669           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
15670       }
15671       return true;
15672     }
15673 
15674     // Try to capture variable-length arrays types.
15675     if (Var->getType()->isVariablyModifiedType()) {
15676       // We're going to walk down into the type and look for VLA
15677       // expressions.
15678       QualType QTy = Var->getType();
15679       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
15680         QTy = PVD->getOriginalType();
15681       captureVariablyModifiedType(Context, QTy, CSI);
15682     }
15683 
15684     if (getLangOpts().OpenMP) {
15685       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15686         // OpenMP private variables should not be captured in outer scope, so
15687         // just break here. Similarly, global variables that are captured in a
15688         // target region should not be captured outside the scope of the region.
15689         if (RSI->CapRegionKind == CR_OpenMP) {
15690           bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
15691           auto IsTargetCap = !IsOpenMPPrivateDecl &&
15692                              isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
15693           // When we detect target captures we are looking from inside the
15694           // target region, therefore we need to propagate the capture from the
15695           // enclosing region. Therefore, the capture is not initially nested.
15696           if (IsTargetCap)
15697             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
15698 
15699           if (IsTargetCap || IsOpenMPPrivateDecl) {
15700             Nested = !IsTargetCap;
15701             DeclRefType = DeclRefType.getUnqualifiedType();
15702             CaptureType = Context.getLValueReferenceType(DeclRefType);
15703             break;
15704           }
15705         }
15706       }
15707     }
15708     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
15709       // No capture-default, and this is not an explicit capture
15710       // so cannot capture this variable.
15711       if (BuildAndDiagnose) {
15712         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15713         Diag(Var->getLocation(), diag::note_previous_decl)
15714           << Var->getDeclName();
15715         if (cast<LambdaScopeInfo>(CSI)->Lambda)
15716           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
15717                diag::note_lambda_decl);
15718         // FIXME: If we error out because an outer lambda can not implicitly
15719         // capture a variable that an inner lambda explicitly captures, we
15720         // should have the inner lambda do the explicit capture - because
15721         // it makes for cleaner diagnostics later.  This would purely be done
15722         // so that the diagnostic does not misleadingly claim that a variable
15723         // can not be captured by a lambda implicitly even though it is captured
15724         // explicitly.  Suggestion:
15725         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
15726         //    at the function head
15727         //  - cache the StartingDeclContext - this must be a lambda
15728         //  - captureInLambda in the innermost lambda the variable.
15729       }
15730       return true;
15731     }
15732 
15733     FunctionScopesIndex--;
15734     DC = ParentDC;
15735     Explicit = false;
15736   } while (!VarDC->Equals(DC));
15737 
15738   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
15739   // computing the type of the capture at each step, checking type-specific
15740   // requirements, and adding captures if requested.
15741   // If the variable had already been captured previously, we start capturing
15742   // at the lambda nested within that one.
15743   bool Invalid = false;
15744   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
15745        ++I) {
15746     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
15747 
15748     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
15749     // certain types of variables (unnamed, variably modified types etc.)
15750     // so check for eligibility.
15751     if (!Invalid)
15752       Invalid =
15753           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
15754 
15755     // After encountering an error, if we're actually supposed to capture, keep
15756     // capturing in nested contexts to suppress any follow-on diagnostics.
15757     if (Invalid && !BuildAndDiagnose)
15758       return true;
15759 
15760     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
15761       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
15762                                DeclRefType, Nested, *this, Invalid);
15763       Nested = true;
15764     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15765       Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
15766                                          CaptureType, DeclRefType, Nested,
15767                                          *this, Invalid);
15768       Nested = true;
15769     } else {
15770       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15771       Invalid =
15772           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
15773                            DeclRefType, Nested, Kind, EllipsisLoc,
15774                            /*IsTopScope*/ I == N - 1, *this, Invalid);
15775       Nested = true;
15776     }
15777 
15778     if (Invalid && !BuildAndDiagnose)
15779       return true;
15780   }
15781   return Invalid;
15782 }
15783 
15784 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
15785                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
15786   QualType CaptureType;
15787   QualType DeclRefType;
15788   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
15789                             /*BuildAndDiagnose=*/true, CaptureType,
15790                             DeclRefType, nullptr);
15791 }
15792 
15793 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
15794   QualType CaptureType;
15795   QualType DeclRefType;
15796   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15797                              /*BuildAndDiagnose=*/false, CaptureType,
15798                              DeclRefType, nullptr);
15799 }
15800 
15801 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
15802   QualType CaptureType;
15803   QualType DeclRefType;
15804 
15805   // Determine whether we can capture this variable.
15806   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15807                          /*BuildAndDiagnose=*/false, CaptureType,
15808                          DeclRefType, nullptr))
15809     return QualType();
15810 
15811   return DeclRefType;
15812 }
15813 
15814 namespace {
15815 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
15816 // The produced TemplateArgumentListInfo* points to data stored within this
15817 // object, so should only be used in contexts where the pointer will not be
15818 // used after the CopiedTemplateArgs object is destroyed.
15819 class CopiedTemplateArgs {
15820   bool HasArgs;
15821   TemplateArgumentListInfo TemplateArgStorage;
15822 public:
15823   template<typename RefExpr>
15824   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
15825     if (HasArgs)
15826       E->copyTemplateArgumentsInto(TemplateArgStorage);
15827   }
15828   operator TemplateArgumentListInfo*()
15829 #ifdef __has_cpp_attribute
15830 #if __has_cpp_attribute(clang::lifetimebound)
15831   [[clang::lifetimebound]]
15832 #endif
15833 #endif
15834   {
15835     return HasArgs ? &TemplateArgStorage : nullptr;
15836   }
15837 };
15838 }
15839 
15840 /// Walk the set of potential results of an expression and mark them all as
15841 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
15842 ///
15843 /// \return A new expression if we found any potential results, ExprEmpty() if
15844 ///         not, and ExprError() if we diagnosed an error.
15845 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
15846                                                       NonOdrUseReason NOUR) {
15847   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
15848   // an object that satisfies the requirements for appearing in a
15849   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
15850   // is immediately applied."  This function handles the lvalue-to-rvalue
15851   // conversion part.
15852   //
15853   // If we encounter a node that claims to be an odr-use but shouldn't be, we
15854   // transform it into the relevant kind of non-odr-use node and rebuild the
15855   // tree of nodes leading to it.
15856   //
15857   // This is a mini-TreeTransform that only transforms a restricted subset of
15858   // nodes (and only certain operands of them).
15859 
15860   // Rebuild a subexpression.
15861   auto Rebuild = [&](Expr *Sub) {
15862     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
15863   };
15864 
15865   // Check whether a potential result satisfies the requirements of NOUR.
15866   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
15867     // Any entity other than a VarDecl is always odr-used whenever it's named
15868     // in a potentially-evaluated expression.
15869     auto *VD = dyn_cast<VarDecl>(D);
15870     if (!VD)
15871       return true;
15872 
15873     // C++2a [basic.def.odr]p4:
15874     //   A variable x whose name appears as a potentially-evalauted expression
15875     //   e is odr-used by e unless
15876     //   -- x is a reference that is usable in constant expressions, or
15877     //   -- x is a variable of non-reference type that is usable in constant
15878     //      expressions and has no mutable subobjects, and e is an element of
15879     //      the set of potential results of an expression of
15880     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
15881     //      conversion is applied, or
15882     //   -- x is a variable of non-reference type, and e is an element of the
15883     //      set of potential results of a discarded-value expression to which
15884     //      the lvalue-to-rvalue conversion is not applied
15885     //
15886     // We check the first bullet and the "potentially-evaluated" condition in
15887     // BuildDeclRefExpr. We check the type requirements in the second bullet
15888     // in CheckLValueToRValueConversionOperand below.
15889     switch (NOUR) {
15890     case NOUR_None:
15891     case NOUR_Unevaluated:
15892       llvm_unreachable("unexpected non-odr-use-reason");
15893 
15894     case NOUR_Constant:
15895       // Constant references were handled when they were built.
15896       if (VD->getType()->isReferenceType())
15897         return true;
15898       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
15899         if (RD->hasMutableFields())
15900           return true;
15901       if (!VD->isUsableInConstantExpressions(S.Context))
15902         return true;
15903       break;
15904 
15905     case NOUR_Discarded:
15906       if (VD->getType()->isReferenceType())
15907         return true;
15908       break;
15909     }
15910     return false;
15911   };
15912 
15913   // Mark that this expression does not constitute an odr-use.
15914   auto MarkNotOdrUsed = [&] {
15915     S.MaybeODRUseExprs.erase(E);
15916     if (LambdaScopeInfo *LSI = S.getCurLambda())
15917       LSI->markVariableExprAsNonODRUsed(E);
15918   };
15919 
15920   // C++2a [basic.def.odr]p2:
15921   //   The set of potential results of an expression e is defined as follows:
15922   switch (E->getStmtClass()) {
15923   //   -- If e is an id-expression, ...
15924   case Expr::DeclRefExprClass: {
15925     auto *DRE = cast<DeclRefExpr>(E);
15926     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
15927       break;
15928 
15929     // Rebuild as a non-odr-use DeclRefExpr.
15930     MarkNotOdrUsed();
15931     return DeclRefExpr::Create(
15932         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
15933         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
15934         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
15935         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
15936   }
15937 
15938   case Expr::FunctionParmPackExprClass: {
15939     auto *FPPE = cast<FunctionParmPackExpr>(E);
15940     // If any of the declarations in the pack is odr-used, then the expression
15941     // as a whole constitutes an odr-use.
15942     for (VarDecl *D : *FPPE)
15943       if (IsPotentialResultOdrUsed(D))
15944         return ExprEmpty();
15945 
15946     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
15947     // nothing cares about whether we marked this as an odr-use, but it might
15948     // be useful for non-compiler tools.
15949     MarkNotOdrUsed();
15950     break;
15951   }
15952 
15953   //   -- If e is a subscripting operation with an array operand...
15954   case Expr::ArraySubscriptExprClass: {
15955     auto *ASE = cast<ArraySubscriptExpr>(E);
15956     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
15957     if (!OldBase->getType()->isArrayType())
15958       break;
15959     ExprResult Base = Rebuild(OldBase);
15960     if (!Base.isUsable())
15961       return Base;
15962     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
15963     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
15964     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
15965     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
15966                                      ASE->getRBracketLoc());
15967   }
15968 
15969   case Expr::MemberExprClass: {
15970     auto *ME = cast<MemberExpr>(E);
15971     // -- If e is a class member access expression [...] naming a non-static
15972     //    data member...
15973     if (isa<FieldDecl>(ME->getMemberDecl())) {
15974       ExprResult Base = Rebuild(ME->getBase());
15975       if (!Base.isUsable())
15976         return Base;
15977       return MemberExpr::Create(
15978           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
15979           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
15980           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
15981           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
15982           ME->getObjectKind(), ME->isNonOdrUse());
15983     }
15984 
15985     if (ME->getMemberDecl()->isCXXInstanceMember())
15986       break;
15987 
15988     // -- If e is a class member access expression naming a static data member,
15989     //    ...
15990     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
15991       break;
15992 
15993     // Rebuild as a non-odr-use MemberExpr.
15994     MarkNotOdrUsed();
15995     return MemberExpr::Create(
15996         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
15997         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
15998         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
15999         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
16000     return ExprEmpty();
16001   }
16002 
16003   case Expr::BinaryOperatorClass: {
16004     auto *BO = cast<BinaryOperator>(E);
16005     Expr *LHS = BO->getLHS();
16006     Expr *RHS = BO->getRHS();
16007     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
16008     if (BO->getOpcode() == BO_PtrMemD) {
16009       ExprResult Sub = Rebuild(LHS);
16010       if (!Sub.isUsable())
16011         return Sub;
16012       LHS = Sub.get();
16013     //   -- If e is a comma expression, ...
16014     } else if (BO->getOpcode() == BO_Comma) {
16015       ExprResult Sub = Rebuild(RHS);
16016       if (!Sub.isUsable())
16017         return Sub;
16018       RHS = Sub.get();
16019     } else {
16020       break;
16021     }
16022     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
16023                         LHS, RHS);
16024   }
16025 
16026   //   -- If e has the form (e1)...
16027   case Expr::ParenExprClass: {
16028     auto *PE = cast<ParenExpr>(E);
16029     ExprResult Sub = Rebuild(PE->getSubExpr());
16030     if (!Sub.isUsable())
16031       return Sub;
16032     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
16033   }
16034 
16035   //   -- If e is a glvalue conditional expression, ...
16036   // We don't apply this to a binary conditional operator. FIXME: Should we?
16037   case Expr::ConditionalOperatorClass: {
16038     auto *CO = cast<ConditionalOperator>(E);
16039     ExprResult LHS = Rebuild(CO->getLHS());
16040     if (LHS.isInvalid())
16041       return ExprError();
16042     ExprResult RHS = Rebuild(CO->getRHS());
16043     if (RHS.isInvalid())
16044       return ExprError();
16045     if (!LHS.isUsable() && !RHS.isUsable())
16046       return ExprEmpty();
16047     if (!LHS.isUsable())
16048       LHS = CO->getLHS();
16049     if (!RHS.isUsable())
16050       RHS = CO->getRHS();
16051     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
16052                                 CO->getCond(), LHS.get(), RHS.get());
16053   }
16054 
16055   // [Clang extension]
16056   //   -- If e has the form __extension__ e1...
16057   case Expr::UnaryOperatorClass: {
16058     auto *UO = cast<UnaryOperator>(E);
16059     if (UO->getOpcode() != UO_Extension)
16060       break;
16061     ExprResult Sub = Rebuild(UO->getSubExpr());
16062     if (!Sub.isUsable())
16063       return Sub;
16064     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
16065                           Sub.get());
16066   }
16067 
16068   // [Clang extension]
16069   //   -- If e has the form _Generic(...), the set of potential results is the
16070   //      union of the sets of potential results of the associated expressions.
16071   case Expr::GenericSelectionExprClass: {
16072     auto *GSE = cast<GenericSelectionExpr>(E);
16073 
16074     SmallVector<Expr *, 4> AssocExprs;
16075     bool AnyChanged = false;
16076     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
16077       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
16078       if (AssocExpr.isInvalid())
16079         return ExprError();
16080       if (AssocExpr.isUsable()) {
16081         AssocExprs.push_back(AssocExpr.get());
16082         AnyChanged = true;
16083       } else {
16084         AssocExprs.push_back(OrigAssocExpr);
16085       }
16086     }
16087 
16088     return AnyChanged ? S.CreateGenericSelectionExpr(
16089                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
16090                             GSE->getRParenLoc(), GSE->getControllingExpr(),
16091                             GSE->getAssocTypeSourceInfos(), AssocExprs)
16092                       : ExprEmpty();
16093   }
16094 
16095   // [Clang extension]
16096   //   -- If e has the form __builtin_choose_expr(...), the set of potential
16097   //      results is the union of the sets of potential results of the
16098   //      second and third subexpressions.
16099   case Expr::ChooseExprClass: {
16100     auto *CE = cast<ChooseExpr>(E);
16101 
16102     ExprResult LHS = Rebuild(CE->getLHS());
16103     if (LHS.isInvalid())
16104       return ExprError();
16105 
16106     ExprResult RHS = Rebuild(CE->getLHS());
16107     if (RHS.isInvalid())
16108       return ExprError();
16109 
16110     if (!LHS.get() && !RHS.get())
16111       return ExprEmpty();
16112     if (!LHS.isUsable())
16113       LHS = CE->getLHS();
16114     if (!RHS.isUsable())
16115       RHS = CE->getRHS();
16116 
16117     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
16118                              RHS.get(), CE->getRParenLoc());
16119   }
16120 
16121   // Step through non-syntactic nodes.
16122   case Expr::ConstantExprClass: {
16123     auto *CE = cast<ConstantExpr>(E);
16124     ExprResult Sub = Rebuild(CE->getSubExpr());
16125     if (!Sub.isUsable())
16126       return Sub;
16127     return ConstantExpr::Create(S.Context, Sub.get());
16128   }
16129 
16130   // We could mostly rely on the recursive rebuilding to rebuild implicit
16131   // casts, but not at the top level, so rebuild them here.
16132   case Expr::ImplicitCastExprClass: {
16133     auto *ICE = cast<ImplicitCastExpr>(E);
16134     // Only step through the narrow set of cast kinds we expect to encounter.
16135     // Anything else suggests we've left the region in which potential results
16136     // can be found.
16137     switch (ICE->getCastKind()) {
16138     case CK_NoOp:
16139     case CK_DerivedToBase:
16140     case CK_UncheckedDerivedToBase: {
16141       ExprResult Sub = Rebuild(ICE->getSubExpr());
16142       if (!Sub.isUsable())
16143         return Sub;
16144       CXXCastPath Path(ICE->path());
16145       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
16146                                  ICE->getValueKind(), &Path);
16147     }
16148 
16149     default:
16150       break;
16151     }
16152     break;
16153   }
16154 
16155   default:
16156     break;
16157   }
16158 
16159   // Can't traverse through this node. Nothing to do.
16160   return ExprEmpty();
16161 }
16162 
16163 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
16164   // C++2a [basic.def.odr]p4:
16165   //   [...] an expression of non-volatile-qualified non-class type to which
16166   //   the lvalue-to-rvalue conversion is applied [...]
16167   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
16168     return E;
16169 
16170   ExprResult Result =
16171       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
16172   if (Result.isInvalid())
16173     return ExprError();
16174   return Result.get() ? Result : E;
16175 }
16176 
16177 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
16178   Res = CorrectDelayedTyposInExpr(Res);
16179 
16180   if (!Res.isUsable())
16181     return Res;
16182 
16183   // If a constant-expression is a reference to a variable where we delay
16184   // deciding whether it is an odr-use, just assume we will apply the
16185   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
16186   // (a non-type template argument), we have special handling anyway.
16187   return CheckLValueToRValueConversionOperand(Res.get());
16188 }
16189 
16190 void Sema::CleanupVarDeclMarking() {
16191   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
16192   // call.
16193   MaybeODRUseExprSet LocalMaybeODRUseExprs;
16194   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
16195 
16196   for (Expr *E : LocalMaybeODRUseExprs) {
16197     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
16198       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
16199                          DRE->getLocation(), *this);
16200     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
16201       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
16202                          *this);
16203     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
16204       for (VarDecl *VD : *FP)
16205         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
16206     } else {
16207       llvm_unreachable("Unexpected expression");
16208     }
16209   }
16210 
16211   assert(MaybeODRUseExprs.empty() &&
16212          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
16213 }
16214 
16215 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
16216                                     VarDecl *Var, Expr *E) {
16217   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
16218           isa<FunctionParmPackExpr>(E)) &&
16219          "Invalid Expr argument to DoMarkVarDeclReferenced");
16220   Var->setReferenced();
16221 
16222   if (Var->isInvalidDecl())
16223     return;
16224 
16225   auto *MSI = Var->getMemberSpecializationInfo();
16226   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
16227                                        : Var->getTemplateSpecializationKind();
16228 
16229   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
16230   bool UsableInConstantExpr =
16231       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
16232 
16233   // C++20 [expr.const]p12:
16234   //   A variable [...] is needed for constant evaluation if it is [...] a
16235   //   variable whose name appears as a potentially constant evaluated
16236   //   expression that is either a contexpr variable or is of non-volatile
16237   //   const-qualified integral type or of reference type
16238   bool NeededForConstantEvaluation =
16239       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
16240 
16241   bool NeedDefinition =
16242       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
16243 
16244   VarTemplateSpecializationDecl *VarSpec =
16245       dyn_cast<VarTemplateSpecializationDecl>(Var);
16246   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
16247          "Can't instantiate a partial template specialization.");
16248 
16249   // If this might be a member specialization of a static data member, check
16250   // the specialization is visible. We already did the checks for variable
16251   // template specializations when we created them.
16252   if (NeedDefinition && TSK != TSK_Undeclared &&
16253       !isa<VarTemplateSpecializationDecl>(Var))
16254     SemaRef.checkSpecializationVisibility(Loc, Var);
16255 
16256   // Perform implicit instantiation of static data members, static data member
16257   // templates of class templates, and variable template specializations. Delay
16258   // instantiations of variable templates, except for those that could be used
16259   // in a constant expression.
16260   if (NeedDefinition && isTemplateInstantiation(TSK)) {
16261     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
16262     // instantiation declaration if a variable is usable in a constant
16263     // expression (among other cases).
16264     bool TryInstantiating =
16265         TSK == TSK_ImplicitInstantiation ||
16266         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
16267 
16268     if (TryInstantiating) {
16269       SourceLocation PointOfInstantiation =
16270           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
16271       bool FirstInstantiation = PointOfInstantiation.isInvalid();
16272       if (FirstInstantiation) {
16273         PointOfInstantiation = Loc;
16274         if (MSI)
16275           MSI->setPointOfInstantiation(PointOfInstantiation);
16276         else
16277           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
16278       }
16279 
16280       bool InstantiationDependent = false;
16281       bool IsNonDependent =
16282           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
16283                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
16284                   : true;
16285 
16286       // Do not instantiate specializations that are still type-dependent.
16287       if (IsNonDependent) {
16288         if (UsableInConstantExpr) {
16289           // Do not defer instantiations of variables that could be used in a
16290           // constant expression.
16291           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
16292         } else if (FirstInstantiation ||
16293                    isa<VarTemplateSpecializationDecl>(Var)) {
16294           // FIXME: For a specialization of a variable template, we don't
16295           // distinguish between "declaration and type implicitly instantiated"
16296           // and "implicit instantiation of definition requested", so we have
16297           // no direct way to avoid enqueueing the pending instantiation
16298           // multiple times.
16299           SemaRef.PendingInstantiations
16300               .push_back(std::make_pair(Var, PointOfInstantiation));
16301         }
16302       }
16303     }
16304   }
16305 
16306   // C++2a [basic.def.odr]p4:
16307   //   A variable x whose name appears as a potentially-evaluated expression e
16308   //   is odr-used by e unless
16309   //   -- x is a reference that is usable in constant expressions
16310   //   -- x is a variable of non-reference type that is usable in constant
16311   //      expressions and has no mutable subobjects [FIXME], and e is an
16312   //      element of the set of potential results of an expression of
16313   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
16314   //      conversion is applied
16315   //   -- x is a variable of non-reference type, and e is an element of the set
16316   //      of potential results of a discarded-value expression to which the
16317   //      lvalue-to-rvalue conversion is not applied [FIXME]
16318   //
16319   // We check the first part of the second bullet here, and
16320   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
16321   // FIXME: To get the third bullet right, we need to delay this even for
16322   // variables that are not usable in constant expressions.
16323 
16324   // If we already know this isn't an odr-use, there's nothing more to do.
16325   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
16326     if (DRE->isNonOdrUse())
16327       return;
16328   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
16329     if (ME->isNonOdrUse())
16330       return;
16331 
16332   switch (OdrUse) {
16333   case OdrUseContext::None:
16334     assert((!E || isa<FunctionParmPackExpr>(E)) &&
16335            "missing non-odr-use marking for unevaluated decl ref");
16336     break;
16337 
16338   case OdrUseContext::FormallyOdrUsed:
16339     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
16340     // behavior.
16341     break;
16342 
16343   case OdrUseContext::Used:
16344     // If we might later find that this expression isn't actually an odr-use,
16345     // delay the marking.
16346     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
16347       SemaRef.MaybeODRUseExprs.insert(E);
16348     else
16349       MarkVarDeclODRUsed(Var, Loc, SemaRef);
16350     break;
16351 
16352   case OdrUseContext::Dependent:
16353     // If this is a dependent context, we don't need to mark variables as
16354     // odr-used, but we may still need to track them for lambda capture.
16355     // FIXME: Do we also need to do this inside dependent typeid expressions
16356     // (which are modeled as unevaluated at this point)?
16357     const bool RefersToEnclosingScope =
16358         (SemaRef.CurContext != Var->getDeclContext() &&
16359          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
16360     if (RefersToEnclosingScope) {
16361       LambdaScopeInfo *const LSI =
16362           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
16363       if (LSI && (!LSI->CallOperator ||
16364                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
16365         // If a variable could potentially be odr-used, defer marking it so
16366         // until we finish analyzing the full expression for any
16367         // lvalue-to-rvalue
16368         // or discarded value conversions that would obviate odr-use.
16369         // Add it to the list of potential captures that will be analyzed
16370         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
16371         // unless the variable is a reference that was initialized by a constant
16372         // expression (this will never need to be captured or odr-used).
16373         //
16374         // FIXME: We can simplify this a lot after implementing P0588R1.
16375         assert(E && "Capture variable should be used in an expression.");
16376         if (!Var->getType()->isReferenceType() ||
16377             !Var->isUsableInConstantExpressions(SemaRef.Context))
16378           LSI->addPotentialCapture(E->IgnoreParens());
16379       }
16380     }
16381     break;
16382   }
16383 }
16384 
16385 /// Mark a variable referenced, and check whether it is odr-used
16386 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
16387 /// used directly for normal expressions referring to VarDecl.
16388 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
16389   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
16390 }
16391 
16392 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
16393                                Decl *D, Expr *E, bool MightBeOdrUse) {
16394   if (SemaRef.isInOpenMPDeclareTargetContext())
16395     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
16396 
16397   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
16398     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
16399     return;
16400   }
16401 
16402   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
16403 
16404   // If this is a call to a method via a cast, also mark the method in the
16405   // derived class used in case codegen can devirtualize the call.
16406   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
16407   if (!ME)
16408     return;
16409   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
16410   if (!MD)
16411     return;
16412   // Only attempt to devirtualize if this is truly a virtual call.
16413   bool IsVirtualCall = MD->isVirtual() &&
16414                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
16415   if (!IsVirtualCall)
16416     return;
16417 
16418   // If it's possible to devirtualize the call, mark the called function
16419   // referenced.
16420   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
16421       ME->getBase(), SemaRef.getLangOpts().AppleKext);
16422   if (DM)
16423     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
16424 }
16425 
16426 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
16427 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
16428   // TODO: update this with DR# once a defect report is filed.
16429   // C++11 defect. The address of a pure member should not be an ODR use, even
16430   // if it's a qualified reference.
16431   bool OdrUse = true;
16432   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
16433     if (Method->isVirtual() &&
16434         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
16435       OdrUse = false;
16436   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
16437 }
16438 
16439 /// Perform reference-marking and odr-use handling for a MemberExpr.
16440 void Sema::MarkMemberReferenced(MemberExpr *E) {
16441   // C++11 [basic.def.odr]p2:
16442   //   A non-overloaded function whose name appears as a potentially-evaluated
16443   //   expression or a member of a set of candidate functions, if selected by
16444   //   overload resolution when referred to from a potentially-evaluated
16445   //   expression, is odr-used, unless it is a pure virtual function and its
16446   //   name is not explicitly qualified.
16447   bool MightBeOdrUse = true;
16448   if (E->performsVirtualDispatch(getLangOpts())) {
16449     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
16450       if (Method->isPure())
16451         MightBeOdrUse = false;
16452   }
16453   SourceLocation Loc =
16454       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
16455   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
16456 }
16457 
16458 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
16459 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
16460   for (VarDecl *VD : *E)
16461     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
16462 }
16463 
16464 /// Perform marking for a reference to an arbitrary declaration.  It
16465 /// marks the declaration referenced, and performs odr-use checking for
16466 /// functions and variables. This method should not be used when building a
16467 /// normal expression which refers to a variable.
16468 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
16469                                  bool MightBeOdrUse) {
16470   if (MightBeOdrUse) {
16471     if (auto *VD = dyn_cast<VarDecl>(D)) {
16472       MarkVariableReferenced(Loc, VD);
16473       return;
16474     }
16475   }
16476   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
16477     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
16478     return;
16479   }
16480   D->setReferenced();
16481 }
16482 
16483 namespace {
16484   // Mark all of the declarations used by a type as referenced.
16485   // FIXME: Not fully implemented yet! We need to have a better understanding
16486   // of when we're entering a context we should not recurse into.
16487   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
16488   // TreeTransforms rebuilding the type in a new context. Rather than
16489   // duplicating the TreeTransform logic, we should consider reusing it here.
16490   // Currently that causes problems when rebuilding LambdaExprs.
16491   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
16492     Sema &S;
16493     SourceLocation Loc;
16494 
16495   public:
16496     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
16497 
16498     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
16499 
16500     bool TraverseTemplateArgument(const TemplateArgument &Arg);
16501   };
16502 }
16503 
16504 bool MarkReferencedDecls::TraverseTemplateArgument(
16505     const TemplateArgument &Arg) {
16506   {
16507     // A non-type template argument is a constant-evaluated context.
16508     EnterExpressionEvaluationContext Evaluated(
16509         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
16510     if (Arg.getKind() == TemplateArgument::Declaration) {
16511       if (Decl *D = Arg.getAsDecl())
16512         S.MarkAnyDeclReferenced(Loc, D, true);
16513     } else if (Arg.getKind() == TemplateArgument::Expression) {
16514       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
16515     }
16516   }
16517 
16518   return Inherited::TraverseTemplateArgument(Arg);
16519 }
16520 
16521 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
16522   MarkReferencedDecls Marker(*this, Loc);
16523   Marker.TraverseType(T);
16524 }
16525 
16526 namespace {
16527   /// Helper class that marks all of the declarations referenced by
16528   /// potentially-evaluated subexpressions as "referenced".
16529   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
16530     Sema &S;
16531     bool SkipLocalVariables;
16532 
16533   public:
16534     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
16535 
16536     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
16537       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
16538 
16539     void VisitDeclRefExpr(DeclRefExpr *E) {
16540       // If we were asked not to visit local variables, don't.
16541       if (SkipLocalVariables) {
16542         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
16543           if (VD->hasLocalStorage())
16544             return;
16545       }
16546 
16547       S.MarkDeclRefReferenced(E);
16548     }
16549 
16550     void VisitMemberExpr(MemberExpr *E) {
16551       S.MarkMemberReferenced(E);
16552       Inherited::VisitMemberExpr(E);
16553     }
16554 
16555     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
16556       S.MarkFunctionReferenced(
16557           E->getBeginLoc(),
16558           const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor()));
16559       Visit(E->getSubExpr());
16560     }
16561 
16562     void VisitCXXNewExpr(CXXNewExpr *E) {
16563       if (E->getOperatorNew())
16564         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew());
16565       if (E->getOperatorDelete())
16566         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
16567       Inherited::VisitCXXNewExpr(E);
16568     }
16569 
16570     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
16571       if (E->getOperatorDelete())
16572         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
16573       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
16574       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
16575         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
16576         S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record));
16577       }
16578 
16579       Inherited::VisitCXXDeleteExpr(E);
16580     }
16581 
16582     void VisitCXXConstructExpr(CXXConstructExpr *E) {
16583       S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor());
16584       Inherited::VisitCXXConstructExpr(E);
16585     }
16586 
16587     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
16588       Visit(E->getExpr());
16589     }
16590   };
16591 }
16592 
16593 /// Mark any declarations that appear within this expression or any
16594 /// potentially-evaluated subexpressions as "referenced".
16595 ///
16596 /// \param SkipLocalVariables If true, don't mark local variables as
16597 /// 'referenced'.
16598 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
16599                                             bool SkipLocalVariables) {
16600   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
16601 }
16602 
16603 /// Emit a diagnostic that describes an effect on the run-time behavior
16604 /// of the program being compiled.
16605 ///
16606 /// This routine emits the given diagnostic when the code currently being
16607 /// type-checked is "potentially evaluated", meaning that there is a
16608 /// possibility that the code will actually be executable. Code in sizeof()
16609 /// expressions, code used only during overload resolution, etc., are not
16610 /// potentially evaluated. This routine will suppress such diagnostics or,
16611 /// in the absolutely nutty case of potentially potentially evaluated
16612 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
16613 /// later.
16614 ///
16615 /// This routine should be used for all diagnostics that describe the run-time
16616 /// behavior of a program, such as passing a non-POD value through an ellipsis.
16617 /// Failure to do so will likely result in spurious diagnostics or failures
16618 /// during overload resolution or within sizeof/alignof/typeof/typeid.
16619 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
16620                                const PartialDiagnostic &PD) {
16621   switch (ExprEvalContexts.back().Context) {
16622   case ExpressionEvaluationContext::Unevaluated:
16623   case ExpressionEvaluationContext::UnevaluatedList:
16624   case ExpressionEvaluationContext::UnevaluatedAbstract:
16625   case ExpressionEvaluationContext::DiscardedStatement:
16626     // The argument will never be evaluated, so don't complain.
16627     break;
16628 
16629   case ExpressionEvaluationContext::ConstantEvaluated:
16630     // Relevant diagnostics should be produced by constant evaluation.
16631     break;
16632 
16633   case ExpressionEvaluationContext::PotentiallyEvaluated:
16634   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16635     if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
16636       FunctionScopes.back()->PossiblyUnreachableDiags.
16637         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
16638       return true;
16639     }
16640 
16641     // The initializer of a constexpr variable or of the first declaration of a
16642     // static data member is not syntactically a constant evaluated constant,
16643     // but nonetheless is always required to be a constant expression, so we
16644     // can skip diagnosing.
16645     // FIXME: Using the mangling context here is a hack.
16646     if (auto *VD = dyn_cast_or_null<VarDecl>(
16647             ExprEvalContexts.back().ManglingContextDecl)) {
16648       if (VD->isConstexpr() ||
16649           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
16650         break;
16651       // FIXME: For any other kind of variable, we should build a CFG for its
16652       // initializer and check whether the context in question is reachable.
16653     }
16654 
16655     Diag(Loc, PD);
16656     return true;
16657   }
16658 
16659   return false;
16660 }
16661 
16662 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
16663                                const PartialDiagnostic &PD) {
16664   return DiagRuntimeBehavior(
16665       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
16666 }
16667 
16668 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
16669                                CallExpr *CE, FunctionDecl *FD) {
16670   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
16671     return false;
16672 
16673   // If we're inside a decltype's expression, don't check for a valid return
16674   // type or construct temporaries until we know whether this is the last call.
16675   if (ExprEvalContexts.back().ExprContext ==
16676       ExpressionEvaluationContextRecord::EK_Decltype) {
16677     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
16678     return false;
16679   }
16680 
16681   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
16682     FunctionDecl *FD;
16683     CallExpr *CE;
16684 
16685   public:
16686     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
16687       : FD(FD), CE(CE) { }
16688 
16689     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16690       if (!FD) {
16691         S.Diag(Loc, diag::err_call_incomplete_return)
16692           << T << CE->getSourceRange();
16693         return;
16694       }
16695 
16696       S.Diag(Loc, diag::err_call_function_incomplete_return)
16697         << CE->getSourceRange() << FD->getDeclName() << T;
16698       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
16699           << FD->getDeclName();
16700     }
16701   } Diagnoser(FD, CE);
16702 
16703   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
16704     return true;
16705 
16706   return false;
16707 }
16708 
16709 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
16710 // will prevent this condition from triggering, which is what we want.
16711 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
16712   SourceLocation Loc;
16713 
16714   unsigned diagnostic = diag::warn_condition_is_assignment;
16715   bool IsOrAssign = false;
16716 
16717   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
16718     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
16719       return;
16720 
16721     IsOrAssign = Op->getOpcode() == BO_OrAssign;
16722 
16723     // Greylist some idioms by putting them into a warning subcategory.
16724     if (ObjCMessageExpr *ME
16725           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
16726       Selector Sel = ME->getSelector();
16727 
16728       // self = [<foo> init...]
16729       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
16730         diagnostic = diag::warn_condition_is_idiomatic_assignment;
16731 
16732       // <foo> = [<bar> nextObject]
16733       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
16734         diagnostic = diag::warn_condition_is_idiomatic_assignment;
16735     }
16736 
16737     Loc = Op->getOperatorLoc();
16738   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
16739     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
16740       return;
16741 
16742     IsOrAssign = Op->getOperator() == OO_PipeEqual;
16743     Loc = Op->getOperatorLoc();
16744   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
16745     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
16746   else {
16747     // Not an assignment.
16748     return;
16749   }
16750 
16751   Diag(Loc, diagnostic) << E->getSourceRange();
16752 
16753   SourceLocation Open = E->getBeginLoc();
16754   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
16755   Diag(Loc, diag::note_condition_assign_silence)
16756         << FixItHint::CreateInsertion(Open, "(")
16757         << FixItHint::CreateInsertion(Close, ")");
16758 
16759   if (IsOrAssign)
16760     Diag(Loc, diag::note_condition_or_assign_to_comparison)
16761       << FixItHint::CreateReplacement(Loc, "!=");
16762   else
16763     Diag(Loc, diag::note_condition_assign_to_comparison)
16764       << FixItHint::CreateReplacement(Loc, "==");
16765 }
16766 
16767 /// Redundant parentheses over an equality comparison can indicate
16768 /// that the user intended an assignment used as condition.
16769 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
16770   // Don't warn if the parens came from a macro.
16771   SourceLocation parenLoc = ParenE->getBeginLoc();
16772   if (parenLoc.isInvalid() || parenLoc.isMacroID())
16773     return;
16774   // Don't warn for dependent expressions.
16775   if (ParenE->isTypeDependent())
16776     return;
16777 
16778   Expr *E = ParenE->IgnoreParens();
16779 
16780   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
16781     if (opE->getOpcode() == BO_EQ &&
16782         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
16783                                                            == Expr::MLV_Valid) {
16784       SourceLocation Loc = opE->getOperatorLoc();
16785 
16786       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
16787       SourceRange ParenERange = ParenE->getSourceRange();
16788       Diag(Loc, diag::note_equality_comparison_silence)
16789         << FixItHint::CreateRemoval(ParenERange.getBegin())
16790         << FixItHint::CreateRemoval(ParenERange.getEnd());
16791       Diag(Loc, diag::note_equality_comparison_to_assign)
16792         << FixItHint::CreateReplacement(Loc, "=");
16793     }
16794 }
16795 
16796 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
16797                                        bool IsConstexpr) {
16798   DiagnoseAssignmentAsCondition(E);
16799   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
16800     DiagnoseEqualityWithExtraParens(parenE);
16801 
16802   ExprResult result = CheckPlaceholderExpr(E);
16803   if (result.isInvalid()) return ExprError();
16804   E = result.get();
16805 
16806   if (!E->isTypeDependent()) {
16807     if (getLangOpts().CPlusPlus)
16808       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
16809 
16810     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
16811     if (ERes.isInvalid())
16812       return ExprError();
16813     E = ERes.get();
16814 
16815     QualType T = E->getType();
16816     if (!T->isScalarType()) { // C99 6.8.4.1p1
16817       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
16818         << T << E->getSourceRange();
16819       return ExprError();
16820     }
16821     CheckBoolLikeConversion(E, Loc);
16822   }
16823 
16824   return E;
16825 }
16826 
16827 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
16828                                            Expr *SubExpr, ConditionKind CK) {
16829   // Empty conditions are valid in for-statements.
16830   if (!SubExpr)
16831     return ConditionResult();
16832 
16833   ExprResult Cond;
16834   switch (CK) {
16835   case ConditionKind::Boolean:
16836     Cond = CheckBooleanCondition(Loc, SubExpr);
16837     break;
16838 
16839   case ConditionKind::ConstexprIf:
16840     Cond = CheckBooleanCondition(Loc, SubExpr, true);
16841     break;
16842 
16843   case ConditionKind::Switch:
16844     Cond = CheckSwitchCondition(Loc, SubExpr);
16845     break;
16846   }
16847   if (Cond.isInvalid())
16848     return ConditionError();
16849 
16850   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
16851   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
16852   if (!FullExpr.get())
16853     return ConditionError();
16854 
16855   return ConditionResult(*this, nullptr, FullExpr,
16856                          CK == ConditionKind::ConstexprIf);
16857 }
16858 
16859 namespace {
16860   /// A visitor for rebuilding a call to an __unknown_any expression
16861   /// to have an appropriate type.
16862   struct RebuildUnknownAnyFunction
16863     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
16864 
16865     Sema &S;
16866 
16867     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
16868 
16869     ExprResult VisitStmt(Stmt *S) {
16870       llvm_unreachable("unexpected statement!");
16871     }
16872 
16873     ExprResult VisitExpr(Expr *E) {
16874       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
16875         << E->getSourceRange();
16876       return ExprError();
16877     }
16878 
16879     /// Rebuild an expression which simply semantically wraps another
16880     /// expression which it shares the type and value kind of.
16881     template <class T> ExprResult rebuildSugarExpr(T *E) {
16882       ExprResult SubResult = Visit(E->getSubExpr());
16883       if (SubResult.isInvalid()) return ExprError();
16884 
16885       Expr *SubExpr = SubResult.get();
16886       E->setSubExpr(SubExpr);
16887       E->setType(SubExpr->getType());
16888       E->setValueKind(SubExpr->getValueKind());
16889       assert(E->getObjectKind() == OK_Ordinary);
16890       return E;
16891     }
16892 
16893     ExprResult VisitParenExpr(ParenExpr *E) {
16894       return rebuildSugarExpr(E);
16895     }
16896 
16897     ExprResult VisitUnaryExtension(UnaryOperator *E) {
16898       return rebuildSugarExpr(E);
16899     }
16900 
16901     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
16902       ExprResult SubResult = Visit(E->getSubExpr());
16903       if (SubResult.isInvalid()) return ExprError();
16904 
16905       Expr *SubExpr = SubResult.get();
16906       E->setSubExpr(SubExpr);
16907       E->setType(S.Context.getPointerType(SubExpr->getType()));
16908       assert(E->getValueKind() == VK_RValue);
16909       assert(E->getObjectKind() == OK_Ordinary);
16910       return E;
16911     }
16912 
16913     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
16914       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
16915 
16916       E->setType(VD->getType());
16917 
16918       assert(E->getValueKind() == VK_RValue);
16919       if (S.getLangOpts().CPlusPlus &&
16920           !(isa<CXXMethodDecl>(VD) &&
16921             cast<CXXMethodDecl>(VD)->isInstance()))
16922         E->setValueKind(VK_LValue);
16923 
16924       return E;
16925     }
16926 
16927     ExprResult VisitMemberExpr(MemberExpr *E) {
16928       return resolveDecl(E, E->getMemberDecl());
16929     }
16930 
16931     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
16932       return resolveDecl(E, E->getDecl());
16933     }
16934   };
16935 }
16936 
16937 /// Given a function expression of unknown-any type, try to rebuild it
16938 /// to have a function type.
16939 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
16940   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
16941   if (Result.isInvalid()) return ExprError();
16942   return S.DefaultFunctionArrayConversion(Result.get());
16943 }
16944 
16945 namespace {
16946   /// A visitor for rebuilding an expression of type __unknown_anytype
16947   /// into one which resolves the type directly on the referring
16948   /// expression.  Strict preservation of the original source
16949   /// structure is not a goal.
16950   struct RebuildUnknownAnyExpr
16951     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
16952 
16953     Sema &S;
16954 
16955     /// The current destination type.
16956     QualType DestType;
16957 
16958     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
16959       : S(S), DestType(CastType) {}
16960 
16961     ExprResult VisitStmt(Stmt *S) {
16962       llvm_unreachable("unexpected statement!");
16963     }
16964 
16965     ExprResult VisitExpr(Expr *E) {
16966       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
16967         << E->getSourceRange();
16968       return ExprError();
16969     }
16970 
16971     ExprResult VisitCallExpr(CallExpr *E);
16972     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
16973 
16974     /// Rebuild an expression which simply semantically wraps another
16975     /// expression which it shares the type and value kind of.
16976     template <class T> ExprResult rebuildSugarExpr(T *E) {
16977       ExprResult SubResult = Visit(E->getSubExpr());
16978       if (SubResult.isInvalid()) return ExprError();
16979       Expr *SubExpr = SubResult.get();
16980       E->setSubExpr(SubExpr);
16981       E->setType(SubExpr->getType());
16982       E->setValueKind(SubExpr->getValueKind());
16983       assert(E->getObjectKind() == OK_Ordinary);
16984       return E;
16985     }
16986 
16987     ExprResult VisitParenExpr(ParenExpr *E) {
16988       return rebuildSugarExpr(E);
16989     }
16990 
16991     ExprResult VisitUnaryExtension(UnaryOperator *E) {
16992       return rebuildSugarExpr(E);
16993     }
16994 
16995     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
16996       const PointerType *Ptr = DestType->getAs<PointerType>();
16997       if (!Ptr) {
16998         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
16999           << E->getSourceRange();
17000         return ExprError();
17001       }
17002 
17003       if (isa<CallExpr>(E->getSubExpr())) {
17004         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
17005           << E->getSourceRange();
17006         return ExprError();
17007       }
17008 
17009       assert(E->getValueKind() == VK_RValue);
17010       assert(E->getObjectKind() == OK_Ordinary);
17011       E->setType(DestType);
17012 
17013       // Build the sub-expression as if it were an object of the pointee type.
17014       DestType = Ptr->getPointeeType();
17015       ExprResult SubResult = Visit(E->getSubExpr());
17016       if (SubResult.isInvalid()) return ExprError();
17017       E->setSubExpr(SubResult.get());
17018       return E;
17019     }
17020 
17021     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
17022 
17023     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
17024 
17025     ExprResult VisitMemberExpr(MemberExpr *E) {
17026       return resolveDecl(E, E->getMemberDecl());
17027     }
17028 
17029     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
17030       return resolveDecl(E, E->getDecl());
17031     }
17032   };
17033 }
17034 
17035 /// Rebuilds a call expression which yielded __unknown_anytype.
17036 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
17037   Expr *CalleeExpr = E->getCallee();
17038 
17039   enum FnKind {
17040     FK_MemberFunction,
17041     FK_FunctionPointer,
17042     FK_BlockPointer
17043   };
17044 
17045   FnKind Kind;
17046   QualType CalleeType = CalleeExpr->getType();
17047   if (CalleeType == S.Context.BoundMemberTy) {
17048     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
17049     Kind = FK_MemberFunction;
17050     CalleeType = Expr::findBoundMemberType(CalleeExpr);
17051   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
17052     CalleeType = Ptr->getPointeeType();
17053     Kind = FK_FunctionPointer;
17054   } else {
17055     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
17056     Kind = FK_BlockPointer;
17057   }
17058   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
17059 
17060   // Verify that this is a legal result type of a function.
17061   if (DestType->isArrayType() || DestType->isFunctionType()) {
17062     unsigned diagID = diag::err_func_returning_array_function;
17063     if (Kind == FK_BlockPointer)
17064       diagID = diag::err_block_returning_array_function;
17065 
17066     S.Diag(E->getExprLoc(), diagID)
17067       << DestType->isFunctionType() << DestType;
17068     return ExprError();
17069   }
17070 
17071   // Otherwise, go ahead and set DestType as the call's result.
17072   E->setType(DestType.getNonLValueExprType(S.Context));
17073   E->setValueKind(Expr::getValueKindForType(DestType));
17074   assert(E->getObjectKind() == OK_Ordinary);
17075 
17076   // Rebuild the function type, replacing the result type with DestType.
17077   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
17078   if (Proto) {
17079     // __unknown_anytype(...) is a special case used by the debugger when
17080     // it has no idea what a function's signature is.
17081     //
17082     // We want to build this call essentially under the K&R
17083     // unprototyped rules, but making a FunctionNoProtoType in C++
17084     // would foul up all sorts of assumptions.  However, we cannot
17085     // simply pass all arguments as variadic arguments, nor can we
17086     // portably just call the function under a non-variadic type; see
17087     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
17088     // However, it turns out that in practice it is generally safe to
17089     // call a function declared as "A foo(B,C,D);" under the prototype
17090     // "A foo(B,C,D,...);".  The only known exception is with the
17091     // Windows ABI, where any variadic function is implicitly cdecl
17092     // regardless of its normal CC.  Therefore we change the parameter
17093     // types to match the types of the arguments.
17094     //
17095     // This is a hack, but it is far superior to moving the
17096     // corresponding target-specific code from IR-gen to Sema/AST.
17097 
17098     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
17099     SmallVector<QualType, 8> ArgTypes;
17100     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
17101       ArgTypes.reserve(E->getNumArgs());
17102       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
17103         Expr *Arg = E->getArg(i);
17104         QualType ArgType = Arg->getType();
17105         if (E->isLValue()) {
17106           ArgType = S.Context.getLValueReferenceType(ArgType);
17107         } else if (E->isXValue()) {
17108           ArgType = S.Context.getRValueReferenceType(ArgType);
17109         }
17110         ArgTypes.push_back(ArgType);
17111       }
17112       ParamTypes = ArgTypes;
17113     }
17114     DestType = S.Context.getFunctionType(DestType, ParamTypes,
17115                                          Proto->getExtProtoInfo());
17116   } else {
17117     DestType = S.Context.getFunctionNoProtoType(DestType,
17118                                                 FnType->getExtInfo());
17119   }
17120 
17121   // Rebuild the appropriate pointer-to-function type.
17122   switch (Kind) {
17123   case FK_MemberFunction:
17124     // Nothing to do.
17125     break;
17126 
17127   case FK_FunctionPointer:
17128     DestType = S.Context.getPointerType(DestType);
17129     break;
17130 
17131   case FK_BlockPointer:
17132     DestType = S.Context.getBlockPointerType(DestType);
17133     break;
17134   }
17135 
17136   // Finally, we can recurse.
17137   ExprResult CalleeResult = Visit(CalleeExpr);
17138   if (!CalleeResult.isUsable()) return ExprError();
17139   E->setCallee(CalleeResult.get());
17140 
17141   // Bind a temporary if necessary.
17142   return S.MaybeBindToTemporary(E);
17143 }
17144 
17145 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
17146   // Verify that this is a legal result type of a call.
17147   if (DestType->isArrayType() || DestType->isFunctionType()) {
17148     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
17149       << DestType->isFunctionType() << DestType;
17150     return ExprError();
17151   }
17152 
17153   // Rewrite the method result type if available.
17154   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
17155     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
17156     Method->setReturnType(DestType);
17157   }
17158 
17159   // Change the type of the message.
17160   E->setType(DestType.getNonReferenceType());
17161   E->setValueKind(Expr::getValueKindForType(DestType));
17162 
17163   return S.MaybeBindToTemporary(E);
17164 }
17165 
17166 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
17167   // The only case we should ever see here is a function-to-pointer decay.
17168   if (E->getCastKind() == CK_FunctionToPointerDecay) {
17169     assert(E->getValueKind() == VK_RValue);
17170     assert(E->getObjectKind() == OK_Ordinary);
17171 
17172     E->setType(DestType);
17173 
17174     // Rebuild the sub-expression as the pointee (function) type.
17175     DestType = DestType->castAs<PointerType>()->getPointeeType();
17176 
17177     ExprResult Result = Visit(E->getSubExpr());
17178     if (!Result.isUsable()) return ExprError();
17179 
17180     E->setSubExpr(Result.get());
17181     return E;
17182   } else if (E->getCastKind() == CK_LValueToRValue) {
17183     assert(E->getValueKind() == VK_RValue);
17184     assert(E->getObjectKind() == OK_Ordinary);
17185 
17186     assert(isa<BlockPointerType>(E->getType()));
17187 
17188     E->setType(DestType);
17189 
17190     // The sub-expression has to be a lvalue reference, so rebuild it as such.
17191     DestType = S.Context.getLValueReferenceType(DestType);
17192 
17193     ExprResult Result = Visit(E->getSubExpr());
17194     if (!Result.isUsable()) return ExprError();
17195 
17196     E->setSubExpr(Result.get());
17197     return E;
17198   } else {
17199     llvm_unreachable("Unhandled cast type!");
17200   }
17201 }
17202 
17203 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
17204   ExprValueKind ValueKind = VK_LValue;
17205   QualType Type = DestType;
17206 
17207   // We know how to make this work for certain kinds of decls:
17208 
17209   //  - functions
17210   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
17211     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
17212       DestType = Ptr->getPointeeType();
17213       ExprResult Result = resolveDecl(E, VD);
17214       if (Result.isInvalid()) return ExprError();
17215       return S.ImpCastExprToType(Result.get(), Type,
17216                                  CK_FunctionToPointerDecay, VK_RValue);
17217     }
17218 
17219     if (!Type->isFunctionType()) {
17220       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
17221         << VD << E->getSourceRange();
17222       return ExprError();
17223     }
17224     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
17225       // We must match the FunctionDecl's type to the hack introduced in
17226       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
17227       // type. See the lengthy commentary in that routine.
17228       QualType FDT = FD->getType();
17229       const FunctionType *FnType = FDT->castAs<FunctionType>();
17230       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
17231       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
17232       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
17233         SourceLocation Loc = FD->getLocation();
17234         FunctionDecl *NewFD = FunctionDecl::Create(
17235             S.Context, FD->getDeclContext(), Loc, Loc,
17236             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
17237             SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
17238             /*ConstexprKind*/ CSK_unspecified);
17239 
17240         if (FD->getQualifier())
17241           NewFD->setQualifierInfo(FD->getQualifierLoc());
17242 
17243         SmallVector<ParmVarDecl*, 16> Params;
17244         for (const auto &AI : FT->param_types()) {
17245           ParmVarDecl *Param =
17246             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
17247           Param->setScopeInfo(0, Params.size());
17248           Params.push_back(Param);
17249         }
17250         NewFD->setParams(Params);
17251         DRE->setDecl(NewFD);
17252         VD = DRE->getDecl();
17253       }
17254     }
17255 
17256     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
17257       if (MD->isInstance()) {
17258         ValueKind = VK_RValue;
17259         Type = S.Context.BoundMemberTy;
17260       }
17261 
17262     // Function references aren't l-values in C.
17263     if (!S.getLangOpts().CPlusPlus)
17264       ValueKind = VK_RValue;
17265 
17266   //  - variables
17267   } else if (isa<VarDecl>(VD)) {
17268     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
17269       Type = RefTy->getPointeeType();
17270     } else if (Type->isFunctionType()) {
17271       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
17272         << VD << E->getSourceRange();
17273       return ExprError();
17274     }
17275 
17276   //  - nothing else
17277   } else {
17278     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
17279       << VD << E->getSourceRange();
17280     return ExprError();
17281   }
17282 
17283   // Modifying the declaration like this is friendly to IR-gen but
17284   // also really dangerous.
17285   VD->setType(DestType);
17286   E->setType(Type);
17287   E->setValueKind(ValueKind);
17288   return E;
17289 }
17290 
17291 /// Check a cast of an unknown-any type.  We intentionally only
17292 /// trigger this for C-style casts.
17293 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
17294                                      Expr *CastExpr, CastKind &CastKind,
17295                                      ExprValueKind &VK, CXXCastPath &Path) {
17296   // The type we're casting to must be either void or complete.
17297   if (!CastType->isVoidType() &&
17298       RequireCompleteType(TypeRange.getBegin(), CastType,
17299                           diag::err_typecheck_cast_to_incomplete))
17300     return ExprError();
17301 
17302   // Rewrite the casted expression from scratch.
17303   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
17304   if (!result.isUsable()) return ExprError();
17305 
17306   CastExpr = result.get();
17307   VK = CastExpr->getValueKind();
17308   CastKind = CK_NoOp;
17309 
17310   return CastExpr;
17311 }
17312 
17313 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
17314   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
17315 }
17316 
17317 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
17318                                     Expr *arg, QualType &paramType) {
17319   // If the syntactic form of the argument is not an explicit cast of
17320   // any sort, just do default argument promotion.
17321   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
17322   if (!castArg) {
17323     ExprResult result = DefaultArgumentPromotion(arg);
17324     if (result.isInvalid()) return ExprError();
17325     paramType = result.get()->getType();
17326     return result;
17327   }
17328 
17329   // Otherwise, use the type that was written in the explicit cast.
17330   assert(!arg->hasPlaceholderType());
17331   paramType = castArg->getTypeAsWritten();
17332 
17333   // Copy-initialize a parameter of that type.
17334   InitializedEntity entity =
17335     InitializedEntity::InitializeParameter(Context, paramType,
17336                                            /*consumed*/ false);
17337   return PerformCopyInitialization(entity, callLoc, arg);
17338 }
17339 
17340 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
17341   Expr *orig = E;
17342   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
17343   while (true) {
17344     E = E->IgnoreParenImpCasts();
17345     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
17346       E = call->getCallee();
17347       diagID = diag::err_uncasted_call_of_unknown_any;
17348     } else {
17349       break;
17350     }
17351   }
17352 
17353   SourceLocation loc;
17354   NamedDecl *d;
17355   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
17356     loc = ref->getLocation();
17357     d = ref->getDecl();
17358   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
17359     loc = mem->getMemberLoc();
17360     d = mem->getMemberDecl();
17361   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
17362     diagID = diag::err_uncasted_call_of_unknown_any;
17363     loc = msg->getSelectorStartLoc();
17364     d = msg->getMethodDecl();
17365     if (!d) {
17366       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
17367         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
17368         << orig->getSourceRange();
17369       return ExprError();
17370     }
17371   } else {
17372     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
17373       << E->getSourceRange();
17374     return ExprError();
17375   }
17376 
17377   S.Diag(loc, diagID) << d << orig->getSourceRange();
17378 
17379   // Never recoverable.
17380   return ExprError();
17381 }
17382 
17383 /// Check for operands with placeholder types and complain if found.
17384 /// Returns ExprError() if there was an error and no recovery was possible.
17385 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
17386   if (!getLangOpts().CPlusPlus) {
17387     // C cannot handle TypoExpr nodes on either side of a binop because it
17388     // doesn't handle dependent types properly, so make sure any TypoExprs have
17389     // been dealt with before checking the operands.
17390     ExprResult Result = CorrectDelayedTyposInExpr(E);
17391     if (!Result.isUsable()) return ExprError();
17392     E = Result.get();
17393   }
17394 
17395   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
17396   if (!placeholderType) return E;
17397 
17398   switch (placeholderType->getKind()) {
17399 
17400   // Overloaded expressions.
17401   case BuiltinType::Overload: {
17402     // Try to resolve a single function template specialization.
17403     // This is obligatory.
17404     ExprResult Result = E;
17405     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
17406       return Result;
17407 
17408     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
17409     // leaves Result unchanged on failure.
17410     Result = E;
17411     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
17412       return Result;
17413 
17414     // If that failed, try to recover with a call.
17415     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
17416                          /*complain*/ true);
17417     return Result;
17418   }
17419 
17420   // Bound member functions.
17421   case BuiltinType::BoundMember: {
17422     ExprResult result = E;
17423     const Expr *BME = E->IgnoreParens();
17424     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
17425     // Try to give a nicer diagnostic if it is a bound member that we recognize.
17426     if (isa<CXXPseudoDestructorExpr>(BME)) {
17427       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
17428     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
17429       if (ME->getMemberNameInfo().getName().getNameKind() ==
17430           DeclarationName::CXXDestructorName)
17431         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
17432     }
17433     tryToRecoverWithCall(result, PD,
17434                          /*complain*/ true);
17435     return result;
17436   }
17437 
17438   // ARC unbridged casts.
17439   case BuiltinType::ARCUnbridgedCast: {
17440     Expr *realCast = stripARCUnbridgedCast(E);
17441     diagnoseARCUnbridgedCast(realCast);
17442     return realCast;
17443   }
17444 
17445   // Expressions of unknown type.
17446   case BuiltinType::UnknownAny:
17447     return diagnoseUnknownAnyExpr(*this, E);
17448 
17449   // Pseudo-objects.
17450   case BuiltinType::PseudoObject:
17451     return checkPseudoObjectRValue(E);
17452 
17453   case BuiltinType::BuiltinFn: {
17454     // Accept __noop without parens by implicitly converting it to a call expr.
17455     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
17456     if (DRE) {
17457       auto *FD = cast<FunctionDecl>(DRE->getDecl());
17458       if (FD->getBuiltinID() == Builtin::BI__noop) {
17459         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
17460                               CK_BuiltinFnToFnPtr)
17461                 .get();
17462         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
17463                                 VK_RValue, SourceLocation());
17464       }
17465     }
17466 
17467     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
17468     return ExprError();
17469   }
17470 
17471   // Expressions of unknown type.
17472   case BuiltinType::OMPArraySection:
17473     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
17474     return ExprError();
17475 
17476   // Everything else should be impossible.
17477 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
17478   case BuiltinType::Id:
17479 #include "clang/Basic/OpenCLImageTypes.def"
17480 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
17481   case BuiltinType::Id:
17482 #include "clang/Basic/OpenCLExtensionTypes.def"
17483 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
17484 #define PLACEHOLDER_TYPE(Id, SingletonId)
17485 #include "clang/AST/BuiltinTypes.def"
17486     break;
17487   }
17488 
17489   llvm_unreachable("invalid placeholder type!");
17490 }
17491 
17492 bool Sema::CheckCaseExpression(Expr *E) {
17493   if (E->isTypeDependent())
17494     return true;
17495   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
17496     return E->getType()->isIntegralOrEnumerationType();
17497   return false;
17498 }
17499 
17500 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
17501 ExprResult
17502 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
17503   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
17504          "Unknown Objective-C Boolean value!");
17505   QualType BoolT = Context.ObjCBuiltinBoolTy;
17506   if (!Context.getBOOLDecl()) {
17507     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
17508                         Sema::LookupOrdinaryName);
17509     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
17510       NamedDecl *ND = Result.getFoundDecl();
17511       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
17512         Context.setBOOLDecl(TD);
17513     }
17514   }
17515   if (Context.getBOOLDecl())
17516     BoolT = Context.getBOOLType();
17517   return new (Context)
17518       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
17519 }
17520 
17521 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
17522     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
17523     SourceLocation RParen) {
17524 
17525   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
17526 
17527   auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
17528     return Spec.getPlatform() == Platform;
17529   });
17530 
17531   VersionTuple Version;
17532   if (Spec != AvailSpecs.end())
17533     Version = Spec->getVersion();
17534 
17535   // The use of `@available` in the enclosing function should be analyzed to
17536   // warn when it's used inappropriately (i.e. not if(@available)).
17537   if (getCurFunctionOrMethodDecl())
17538     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
17539   else if (getCurBlock() || getCurLambda())
17540     getCurFunction()->HasPotentialAvailabilityViolations = true;
17541 
17542   return new (Context)
17543       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
17544 }
17545