1*67e74705SXin Li //===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2*67e74705SXin Li //
3*67e74705SXin Li // The LLVM Compiler Infrastructure
4*67e74705SXin Li //
5*67e74705SXin Li // This file is distributed under the University of Illinois Open Source
6*67e74705SXin Li // License. See LICENSE.TXT for details.
7*67e74705SXin Li //
8*67e74705SXin Li //===----------------------------------------------------------------------===//
9*67e74705SXin Li ///
10*67e74705SXin Li /// \file
11*67e74705SXin Li /// \brief Implements semantic analysis for C++ expressions.
12*67e74705SXin Li ///
13*67e74705SXin Li //===----------------------------------------------------------------------===//
14*67e74705SXin Li
15*67e74705SXin Li #include "clang/Sema/SemaInternal.h"
16*67e74705SXin Li #include "TreeTransform.h"
17*67e74705SXin Li #include "TypeLocBuilder.h"
18*67e74705SXin Li #include "clang/AST/ASTContext.h"
19*67e74705SXin Li #include "clang/AST/ASTLambda.h"
20*67e74705SXin Li #include "clang/AST/CXXInheritance.h"
21*67e74705SXin Li #include "clang/AST/CharUnits.h"
22*67e74705SXin Li #include "clang/AST/DeclObjC.h"
23*67e74705SXin Li #include "clang/AST/ExprCXX.h"
24*67e74705SXin Li #include "clang/AST/ExprObjC.h"
25*67e74705SXin Li #include "clang/AST/RecursiveASTVisitor.h"
26*67e74705SXin Li #include "clang/AST/TypeLoc.h"
27*67e74705SXin Li #include "clang/Basic/PartialDiagnostic.h"
28*67e74705SXin Li #include "clang/Basic/TargetInfo.h"
29*67e74705SXin Li #include "clang/Lex/Preprocessor.h"
30*67e74705SXin Li #include "clang/Sema/DeclSpec.h"
31*67e74705SXin Li #include "clang/Sema/Initialization.h"
32*67e74705SXin Li #include "clang/Sema/Lookup.h"
33*67e74705SXin Li #include "clang/Sema/ParsedTemplate.h"
34*67e74705SXin Li #include "clang/Sema/Scope.h"
35*67e74705SXin Li #include "clang/Sema/ScopeInfo.h"
36*67e74705SXin Li #include "clang/Sema/SemaLambda.h"
37*67e74705SXin Li #include "clang/Sema/TemplateDeduction.h"
38*67e74705SXin Li #include "llvm/ADT/APInt.h"
39*67e74705SXin Li #include "llvm/ADT/STLExtras.h"
40*67e74705SXin Li #include "llvm/Support/ErrorHandling.h"
41*67e74705SXin Li using namespace clang;
42*67e74705SXin Li using namespace sema;
43*67e74705SXin Li
44*67e74705SXin Li /// \brief Handle the result of the special case name lookup for inheriting
45*67e74705SXin Li /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
46*67e74705SXin Li /// constructor names in member using declarations, even if 'X' is not the
47*67e74705SXin Li /// name of the corresponding type.
getInheritingConstructorName(CXXScopeSpec & SS,SourceLocation NameLoc,IdentifierInfo & Name)48*67e74705SXin Li ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
49*67e74705SXin Li SourceLocation NameLoc,
50*67e74705SXin Li IdentifierInfo &Name) {
51*67e74705SXin Li NestedNameSpecifier *NNS = SS.getScopeRep();
52*67e74705SXin Li
53*67e74705SXin Li // Convert the nested-name-specifier into a type.
54*67e74705SXin Li QualType Type;
55*67e74705SXin Li switch (NNS->getKind()) {
56*67e74705SXin Li case NestedNameSpecifier::TypeSpec:
57*67e74705SXin Li case NestedNameSpecifier::TypeSpecWithTemplate:
58*67e74705SXin Li Type = QualType(NNS->getAsType(), 0);
59*67e74705SXin Li break;
60*67e74705SXin Li
61*67e74705SXin Li case NestedNameSpecifier::Identifier:
62*67e74705SXin Li // Strip off the last layer of the nested-name-specifier and build a
63*67e74705SXin Li // typename type for it.
64*67e74705SXin Li assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
65*67e74705SXin Li Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
66*67e74705SXin Li NNS->getAsIdentifier());
67*67e74705SXin Li break;
68*67e74705SXin Li
69*67e74705SXin Li case NestedNameSpecifier::Global:
70*67e74705SXin Li case NestedNameSpecifier::Super:
71*67e74705SXin Li case NestedNameSpecifier::Namespace:
72*67e74705SXin Li case NestedNameSpecifier::NamespaceAlias:
73*67e74705SXin Li llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
74*67e74705SXin Li }
75*67e74705SXin Li
76*67e74705SXin Li // This reference to the type is located entirely at the location of the
77*67e74705SXin Li // final identifier in the qualified-id.
78*67e74705SXin Li return CreateParsedType(Type,
79*67e74705SXin Li Context.getTrivialTypeSourceInfo(Type, NameLoc));
80*67e74705SXin Li }
81*67e74705SXin Li
getDestructorName(SourceLocation TildeLoc,IdentifierInfo & II,SourceLocation NameLoc,Scope * S,CXXScopeSpec & SS,ParsedType ObjectTypePtr,bool EnteringContext)82*67e74705SXin Li ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
83*67e74705SXin Li IdentifierInfo &II,
84*67e74705SXin Li SourceLocation NameLoc,
85*67e74705SXin Li Scope *S, CXXScopeSpec &SS,
86*67e74705SXin Li ParsedType ObjectTypePtr,
87*67e74705SXin Li bool EnteringContext) {
88*67e74705SXin Li // Determine where to perform name lookup.
89*67e74705SXin Li
90*67e74705SXin Li // FIXME: This area of the standard is very messy, and the current
91*67e74705SXin Li // wording is rather unclear about which scopes we search for the
92*67e74705SXin Li // destructor name; see core issues 399 and 555. Issue 399 in
93*67e74705SXin Li // particular shows where the current description of destructor name
94*67e74705SXin Li // lookup is completely out of line with existing practice, e.g.,
95*67e74705SXin Li // this appears to be ill-formed:
96*67e74705SXin Li //
97*67e74705SXin Li // namespace N {
98*67e74705SXin Li // template <typename T> struct S {
99*67e74705SXin Li // ~S();
100*67e74705SXin Li // };
101*67e74705SXin Li // }
102*67e74705SXin Li //
103*67e74705SXin Li // void f(N::S<int>* s) {
104*67e74705SXin Li // s->N::S<int>::~S();
105*67e74705SXin Li // }
106*67e74705SXin Li //
107*67e74705SXin Li // See also PR6358 and PR6359.
108*67e74705SXin Li // For this reason, we're currently only doing the C++03 version of this
109*67e74705SXin Li // code; the C++0x version has to wait until we get a proper spec.
110*67e74705SXin Li QualType SearchType;
111*67e74705SXin Li DeclContext *LookupCtx = nullptr;
112*67e74705SXin Li bool isDependent = false;
113*67e74705SXin Li bool LookInScope = false;
114*67e74705SXin Li
115*67e74705SXin Li if (SS.isInvalid())
116*67e74705SXin Li return nullptr;
117*67e74705SXin Li
118*67e74705SXin Li // If we have an object type, it's because we are in a
119*67e74705SXin Li // pseudo-destructor-expression or a member access expression, and
120*67e74705SXin Li // we know what type we're looking for.
121*67e74705SXin Li if (ObjectTypePtr)
122*67e74705SXin Li SearchType = GetTypeFromParser(ObjectTypePtr);
123*67e74705SXin Li
124*67e74705SXin Li if (SS.isSet()) {
125*67e74705SXin Li NestedNameSpecifier *NNS = SS.getScopeRep();
126*67e74705SXin Li
127*67e74705SXin Li bool AlreadySearched = false;
128*67e74705SXin Li bool LookAtPrefix = true;
129*67e74705SXin Li // C++11 [basic.lookup.qual]p6:
130*67e74705SXin Li // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
131*67e74705SXin Li // the type-names are looked up as types in the scope designated by the
132*67e74705SXin Li // nested-name-specifier. Similarly, in a qualified-id of the form:
133*67e74705SXin Li //
134*67e74705SXin Li // nested-name-specifier[opt] class-name :: ~ class-name
135*67e74705SXin Li //
136*67e74705SXin Li // the second class-name is looked up in the same scope as the first.
137*67e74705SXin Li //
138*67e74705SXin Li // Here, we determine whether the code below is permitted to look at the
139*67e74705SXin Li // prefix of the nested-name-specifier.
140*67e74705SXin Li DeclContext *DC = computeDeclContext(SS, EnteringContext);
141*67e74705SXin Li if (DC && DC->isFileContext()) {
142*67e74705SXin Li AlreadySearched = true;
143*67e74705SXin Li LookupCtx = DC;
144*67e74705SXin Li isDependent = false;
145*67e74705SXin Li } else if (DC && isa<CXXRecordDecl>(DC)) {
146*67e74705SXin Li LookAtPrefix = false;
147*67e74705SXin Li LookInScope = true;
148*67e74705SXin Li }
149*67e74705SXin Li
150*67e74705SXin Li // The second case from the C++03 rules quoted further above.
151*67e74705SXin Li NestedNameSpecifier *Prefix = nullptr;
152*67e74705SXin Li if (AlreadySearched) {
153*67e74705SXin Li // Nothing left to do.
154*67e74705SXin Li } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
155*67e74705SXin Li CXXScopeSpec PrefixSS;
156*67e74705SXin Li PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
157*67e74705SXin Li LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
158*67e74705SXin Li isDependent = isDependentScopeSpecifier(PrefixSS);
159*67e74705SXin Li } else if (ObjectTypePtr) {
160*67e74705SXin Li LookupCtx = computeDeclContext(SearchType);
161*67e74705SXin Li isDependent = SearchType->isDependentType();
162*67e74705SXin Li } else {
163*67e74705SXin Li LookupCtx = computeDeclContext(SS, EnteringContext);
164*67e74705SXin Li isDependent = LookupCtx && LookupCtx->isDependentContext();
165*67e74705SXin Li }
166*67e74705SXin Li } else if (ObjectTypePtr) {
167*67e74705SXin Li // C++ [basic.lookup.classref]p3:
168*67e74705SXin Li // If the unqualified-id is ~type-name, the type-name is looked up
169*67e74705SXin Li // in the context of the entire postfix-expression. If the type T
170*67e74705SXin Li // of the object expression is of a class type C, the type-name is
171*67e74705SXin Li // also looked up in the scope of class C. At least one of the
172*67e74705SXin Li // lookups shall find a name that refers to (possibly
173*67e74705SXin Li // cv-qualified) T.
174*67e74705SXin Li LookupCtx = computeDeclContext(SearchType);
175*67e74705SXin Li isDependent = SearchType->isDependentType();
176*67e74705SXin Li assert((isDependent || !SearchType->isIncompleteType()) &&
177*67e74705SXin Li "Caller should have completed object type");
178*67e74705SXin Li
179*67e74705SXin Li LookInScope = true;
180*67e74705SXin Li } else {
181*67e74705SXin Li // Perform lookup into the current scope (only).
182*67e74705SXin Li LookInScope = true;
183*67e74705SXin Li }
184*67e74705SXin Li
185*67e74705SXin Li TypeDecl *NonMatchingTypeDecl = nullptr;
186*67e74705SXin Li LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
187*67e74705SXin Li for (unsigned Step = 0; Step != 2; ++Step) {
188*67e74705SXin Li // Look for the name first in the computed lookup context (if we
189*67e74705SXin Li // have one) and, if that fails to find a match, in the scope (if
190*67e74705SXin Li // we're allowed to look there).
191*67e74705SXin Li Found.clear();
192*67e74705SXin Li if (Step == 0 && LookupCtx)
193*67e74705SXin Li LookupQualifiedName(Found, LookupCtx);
194*67e74705SXin Li else if (Step == 1 && LookInScope && S)
195*67e74705SXin Li LookupName(Found, S);
196*67e74705SXin Li else
197*67e74705SXin Li continue;
198*67e74705SXin Li
199*67e74705SXin Li // FIXME: Should we be suppressing ambiguities here?
200*67e74705SXin Li if (Found.isAmbiguous())
201*67e74705SXin Li return nullptr;
202*67e74705SXin Li
203*67e74705SXin Li if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
204*67e74705SXin Li QualType T = Context.getTypeDeclType(Type);
205*67e74705SXin Li MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
206*67e74705SXin Li
207*67e74705SXin Li if (SearchType.isNull() || SearchType->isDependentType() ||
208*67e74705SXin Li Context.hasSameUnqualifiedType(T, SearchType)) {
209*67e74705SXin Li // We found our type!
210*67e74705SXin Li
211*67e74705SXin Li return CreateParsedType(T,
212*67e74705SXin Li Context.getTrivialTypeSourceInfo(T, NameLoc));
213*67e74705SXin Li }
214*67e74705SXin Li
215*67e74705SXin Li if (!SearchType.isNull())
216*67e74705SXin Li NonMatchingTypeDecl = Type;
217*67e74705SXin Li }
218*67e74705SXin Li
219*67e74705SXin Li // If the name that we found is a class template name, and it is
220*67e74705SXin Li // the same name as the template name in the last part of the
221*67e74705SXin Li // nested-name-specifier (if present) or the object type, then
222*67e74705SXin Li // this is the destructor for that class.
223*67e74705SXin Li // FIXME: This is a workaround until we get real drafting for core
224*67e74705SXin Li // issue 399, for which there isn't even an obvious direction.
225*67e74705SXin Li if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
226*67e74705SXin Li QualType MemberOfType;
227*67e74705SXin Li if (SS.isSet()) {
228*67e74705SXin Li if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
229*67e74705SXin Li // Figure out the type of the context, if it has one.
230*67e74705SXin Li if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
231*67e74705SXin Li MemberOfType = Context.getTypeDeclType(Record);
232*67e74705SXin Li }
233*67e74705SXin Li }
234*67e74705SXin Li if (MemberOfType.isNull())
235*67e74705SXin Li MemberOfType = SearchType;
236*67e74705SXin Li
237*67e74705SXin Li if (MemberOfType.isNull())
238*67e74705SXin Li continue;
239*67e74705SXin Li
240*67e74705SXin Li // We're referring into a class template specialization. If the
241*67e74705SXin Li // class template we found is the same as the template being
242*67e74705SXin Li // specialized, we found what we are looking for.
243*67e74705SXin Li if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
244*67e74705SXin Li if (ClassTemplateSpecializationDecl *Spec
245*67e74705SXin Li = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
246*67e74705SXin Li if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
247*67e74705SXin Li Template->getCanonicalDecl())
248*67e74705SXin Li return CreateParsedType(
249*67e74705SXin Li MemberOfType,
250*67e74705SXin Li Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
251*67e74705SXin Li }
252*67e74705SXin Li
253*67e74705SXin Li continue;
254*67e74705SXin Li }
255*67e74705SXin Li
256*67e74705SXin Li // We're referring to an unresolved class template
257*67e74705SXin Li // specialization. Determine whether we class template we found
258*67e74705SXin Li // is the same as the template being specialized or, if we don't
259*67e74705SXin Li // know which template is being specialized, that it at least
260*67e74705SXin Li // has the same name.
261*67e74705SXin Li if (const TemplateSpecializationType *SpecType
262*67e74705SXin Li = MemberOfType->getAs<TemplateSpecializationType>()) {
263*67e74705SXin Li TemplateName SpecName = SpecType->getTemplateName();
264*67e74705SXin Li
265*67e74705SXin Li // The class template we found is the same template being
266*67e74705SXin Li // specialized.
267*67e74705SXin Li if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
268*67e74705SXin Li if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
269*67e74705SXin Li return CreateParsedType(
270*67e74705SXin Li MemberOfType,
271*67e74705SXin Li Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
272*67e74705SXin Li
273*67e74705SXin Li continue;
274*67e74705SXin Li }
275*67e74705SXin Li
276*67e74705SXin Li // The class template we found has the same name as the
277*67e74705SXin Li // (dependent) template name being specialized.
278*67e74705SXin Li if (DependentTemplateName *DepTemplate
279*67e74705SXin Li = SpecName.getAsDependentTemplateName()) {
280*67e74705SXin Li if (DepTemplate->isIdentifier() &&
281*67e74705SXin Li DepTemplate->getIdentifier() == Template->getIdentifier())
282*67e74705SXin Li return CreateParsedType(
283*67e74705SXin Li MemberOfType,
284*67e74705SXin Li Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
285*67e74705SXin Li
286*67e74705SXin Li continue;
287*67e74705SXin Li }
288*67e74705SXin Li }
289*67e74705SXin Li }
290*67e74705SXin Li }
291*67e74705SXin Li
292*67e74705SXin Li if (isDependent) {
293*67e74705SXin Li // We didn't find our type, but that's okay: it's dependent
294*67e74705SXin Li // anyway.
295*67e74705SXin Li
296*67e74705SXin Li // FIXME: What if we have no nested-name-specifier?
297*67e74705SXin Li QualType T = CheckTypenameType(ETK_None, SourceLocation(),
298*67e74705SXin Li SS.getWithLocInContext(Context),
299*67e74705SXin Li II, NameLoc);
300*67e74705SXin Li return ParsedType::make(T);
301*67e74705SXin Li }
302*67e74705SXin Li
303*67e74705SXin Li if (NonMatchingTypeDecl) {
304*67e74705SXin Li QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
305*67e74705SXin Li Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
306*67e74705SXin Li << T << SearchType;
307*67e74705SXin Li Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
308*67e74705SXin Li << T;
309*67e74705SXin Li } else if (ObjectTypePtr)
310*67e74705SXin Li Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
311*67e74705SXin Li << &II;
312*67e74705SXin Li else {
313*67e74705SXin Li SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
314*67e74705SXin Li diag::err_destructor_class_name);
315*67e74705SXin Li if (S) {
316*67e74705SXin Li const DeclContext *Ctx = S->getEntity();
317*67e74705SXin Li if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
318*67e74705SXin Li DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
319*67e74705SXin Li Class->getNameAsString());
320*67e74705SXin Li }
321*67e74705SXin Li }
322*67e74705SXin Li
323*67e74705SXin Li return nullptr;
324*67e74705SXin Li }
325*67e74705SXin Li
getDestructorType(const DeclSpec & DS,ParsedType ObjectType)326*67e74705SXin Li ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) {
327*67e74705SXin Li if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType)
328*67e74705SXin Li return nullptr;
329*67e74705SXin Li assert(DS.getTypeSpecType() == DeclSpec::TST_decltype
330*67e74705SXin Li && "only get destructor types from declspecs");
331*67e74705SXin Li QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
332*67e74705SXin Li QualType SearchType = GetTypeFromParser(ObjectType);
333*67e74705SXin Li if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(SearchType, T)) {
334*67e74705SXin Li return ParsedType::make(T);
335*67e74705SXin Li }
336*67e74705SXin Li
337*67e74705SXin Li Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
338*67e74705SXin Li << T << SearchType;
339*67e74705SXin Li return nullptr;
340*67e74705SXin Li }
341*67e74705SXin Li
checkLiteralOperatorId(const CXXScopeSpec & SS,const UnqualifiedId & Name)342*67e74705SXin Li bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
343*67e74705SXin Li const UnqualifiedId &Name) {
344*67e74705SXin Li assert(Name.getKind() == UnqualifiedId::IK_LiteralOperatorId);
345*67e74705SXin Li
346*67e74705SXin Li if (!SS.isValid())
347*67e74705SXin Li return false;
348*67e74705SXin Li
349*67e74705SXin Li switch (SS.getScopeRep()->getKind()) {
350*67e74705SXin Li case NestedNameSpecifier::Identifier:
351*67e74705SXin Li case NestedNameSpecifier::TypeSpec:
352*67e74705SXin Li case NestedNameSpecifier::TypeSpecWithTemplate:
353*67e74705SXin Li // Per C++11 [over.literal]p2, literal operators can only be declared at
354*67e74705SXin Li // namespace scope. Therefore, this unqualified-id cannot name anything.
355*67e74705SXin Li // Reject it early, because we have no AST representation for this in the
356*67e74705SXin Li // case where the scope is dependent.
357*67e74705SXin Li Diag(Name.getLocStart(), diag::err_literal_operator_id_outside_namespace)
358*67e74705SXin Li << SS.getScopeRep();
359*67e74705SXin Li return true;
360*67e74705SXin Li
361*67e74705SXin Li case NestedNameSpecifier::Global:
362*67e74705SXin Li case NestedNameSpecifier::Super:
363*67e74705SXin Li case NestedNameSpecifier::Namespace:
364*67e74705SXin Li case NestedNameSpecifier::NamespaceAlias:
365*67e74705SXin Li return false;
366*67e74705SXin Li }
367*67e74705SXin Li
368*67e74705SXin Li llvm_unreachable("unknown nested name specifier kind");
369*67e74705SXin Li }
370*67e74705SXin Li
371*67e74705SXin Li /// \brief Build a C++ typeid expression with a type operand.
BuildCXXTypeId(QualType TypeInfoType,SourceLocation TypeidLoc,TypeSourceInfo * Operand,SourceLocation RParenLoc)372*67e74705SXin Li ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
373*67e74705SXin Li SourceLocation TypeidLoc,
374*67e74705SXin Li TypeSourceInfo *Operand,
375*67e74705SXin Li SourceLocation RParenLoc) {
376*67e74705SXin Li // C++ [expr.typeid]p4:
377*67e74705SXin Li // The top-level cv-qualifiers of the lvalue expression or the type-id
378*67e74705SXin Li // that is the operand of typeid are always ignored.
379*67e74705SXin Li // If the type of the type-id is a class type or a reference to a class
380*67e74705SXin Li // type, the class shall be completely-defined.
381*67e74705SXin Li Qualifiers Quals;
382*67e74705SXin Li QualType T
383*67e74705SXin Li = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
384*67e74705SXin Li Quals);
385*67e74705SXin Li if (T->getAs<RecordType>() &&
386*67e74705SXin Li RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
387*67e74705SXin Li return ExprError();
388*67e74705SXin Li
389*67e74705SXin Li if (T->isVariablyModifiedType())
390*67e74705SXin Li return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
391*67e74705SXin Li
392*67e74705SXin Li return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
393*67e74705SXin Li SourceRange(TypeidLoc, RParenLoc));
394*67e74705SXin Li }
395*67e74705SXin Li
396*67e74705SXin Li /// \brief Build a C++ typeid expression with an expression operand.
BuildCXXTypeId(QualType TypeInfoType,SourceLocation TypeidLoc,Expr * E,SourceLocation RParenLoc)397*67e74705SXin Li ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
398*67e74705SXin Li SourceLocation TypeidLoc,
399*67e74705SXin Li Expr *E,
400*67e74705SXin Li SourceLocation RParenLoc) {
401*67e74705SXin Li bool WasEvaluated = false;
402*67e74705SXin Li if (E && !E->isTypeDependent()) {
403*67e74705SXin Li if (E->getType()->isPlaceholderType()) {
404*67e74705SXin Li ExprResult result = CheckPlaceholderExpr(E);
405*67e74705SXin Li if (result.isInvalid()) return ExprError();
406*67e74705SXin Li E = result.get();
407*67e74705SXin Li }
408*67e74705SXin Li
409*67e74705SXin Li QualType T = E->getType();
410*67e74705SXin Li if (const RecordType *RecordT = T->getAs<RecordType>()) {
411*67e74705SXin Li CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
412*67e74705SXin Li // C++ [expr.typeid]p3:
413*67e74705SXin Li // [...] If the type of the expression is a class type, the class
414*67e74705SXin Li // shall be completely-defined.
415*67e74705SXin Li if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
416*67e74705SXin Li return ExprError();
417*67e74705SXin Li
418*67e74705SXin Li // C++ [expr.typeid]p3:
419*67e74705SXin Li // When typeid is applied to an expression other than an glvalue of a
420*67e74705SXin Li // polymorphic class type [...] [the] expression is an unevaluated
421*67e74705SXin Li // operand. [...]
422*67e74705SXin Li if (RecordD->isPolymorphic() && E->isGLValue()) {
423*67e74705SXin Li // The subexpression is potentially evaluated; switch the context
424*67e74705SXin Li // and recheck the subexpression.
425*67e74705SXin Li ExprResult Result = TransformToPotentiallyEvaluated(E);
426*67e74705SXin Li if (Result.isInvalid()) return ExprError();
427*67e74705SXin Li E = Result.get();
428*67e74705SXin Li
429*67e74705SXin Li // We require a vtable to query the type at run time.
430*67e74705SXin Li MarkVTableUsed(TypeidLoc, RecordD);
431*67e74705SXin Li WasEvaluated = true;
432*67e74705SXin Li }
433*67e74705SXin Li }
434*67e74705SXin Li
435*67e74705SXin Li // C++ [expr.typeid]p4:
436*67e74705SXin Li // [...] If the type of the type-id is a reference to a possibly
437*67e74705SXin Li // cv-qualified type, the result of the typeid expression refers to a
438*67e74705SXin Li // std::type_info object representing the cv-unqualified referenced
439*67e74705SXin Li // type.
440*67e74705SXin Li Qualifiers Quals;
441*67e74705SXin Li QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
442*67e74705SXin Li if (!Context.hasSameType(T, UnqualT)) {
443*67e74705SXin Li T = UnqualT;
444*67e74705SXin Li E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
445*67e74705SXin Li }
446*67e74705SXin Li }
447*67e74705SXin Li
448*67e74705SXin Li if (E->getType()->isVariablyModifiedType())
449*67e74705SXin Li return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
450*67e74705SXin Li << E->getType());
451*67e74705SXin Li else if (ActiveTemplateInstantiations.empty() &&
452*67e74705SXin Li E->HasSideEffects(Context, WasEvaluated)) {
453*67e74705SXin Li // The expression operand for typeid is in an unevaluated expression
454*67e74705SXin Li // context, so side effects could result in unintended consequences.
455*67e74705SXin Li Diag(E->getExprLoc(), WasEvaluated
456*67e74705SXin Li ? diag::warn_side_effects_typeid
457*67e74705SXin Li : diag::warn_side_effects_unevaluated_context);
458*67e74705SXin Li }
459*67e74705SXin Li
460*67e74705SXin Li return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
461*67e74705SXin Li SourceRange(TypeidLoc, RParenLoc));
462*67e74705SXin Li }
463*67e74705SXin Li
464*67e74705SXin Li /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
465*67e74705SXin Li ExprResult
ActOnCXXTypeid(SourceLocation OpLoc,SourceLocation LParenLoc,bool isType,void * TyOrExpr,SourceLocation RParenLoc)466*67e74705SXin Li Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
467*67e74705SXin Li bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
468*67e74705SXin Li // Find the std::type_info type.
469*67e74705SXin Li if (!getStdNamespace())
470*67e74705SXin Li return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
471*67e74705SXin Li
472*67e74705SXin Li if (!CXXTypeInfoDecl) {
473*67e74705SXin Li IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
474*67e74705SXin Li LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
475*67e74705SXin Li LookupQualifiedName(R, getStdNamespace());
476*67e74705SXin Li CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
477*67e74705SXin Li // Microsoft's typeinfo doesn't have type_info in std but in the global
478*67e74705SXin Li // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
479*67e74705SXin Li if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
480*67e74705SXin Li LookupQualifiedName(R, Context.getTranslationUnitDecl());
481*67e74705SXin Li CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
482*67e74705SXin Li }
483*67e74705SXin Li if (!CXXTypeInfoDecl)
484*67e74705SXin Li return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
485*67e74705SXin Li }
486*67e74705SXin Li
487*67e74705SXin Li if (!getLangOpts().RTTI) {
488*67e74705SXin Li return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
489*67e74705SXin Li }
490*67e74705SXin Li
491*67e74705SXin Li QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
492*67e74705SXin Li
493*67e74705SXin Li if (isType) {
494*67e74705SXin Li // The operand is a type; handle it as such.
495*67e74705SXin Li TypeSourceInfo *TInfo = nullptr;
496*67e74705SXin Li QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
497*67e74705SXin Li &TInfo);
498*67e74705SXin Li if (T.isNull())
499*67e74705SXin Li return ExprError();
500*67e74705SXin Li
501*67e74705SXin Li if (!TInfo)
502*67e74705SXin Li TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
503*67e74705SXin Li
504*67e74705SXin Li return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
505*67e74705SXin Li }
506*67e74705SXin Li
507*67e74705SXin Li // The operand is an expression.
508*67e74705SXin Li return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
509*67e74705SXin Li }
510*67e74705SXin Li
511*67e74705SXin Li /// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
512*67e74705SXin Li /// a single GUID.
513*67e74705SXin Li static void
getUuidAttrOfType(Sema & SemaRef,QualType QT,llvm::SmallSetVector<const UuidAttr *,1> & UuidAttrs)514*67e74705SXin Li getUuidAttrOfType(Sema &SemaRef, QualType QT,
515*67e74705SXin Li llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
516*67e74705SXin Li // Optionally remove one level of pointer, reference or array indirection.
517*67e74705SXin Li const Type *Ty = QT.getTypePtr();
518*67e74705SXin Li if (QT->isPointerType() || QT->isReferenceType())
519*67e74705SXin Li Ty = QT->getPointeeType().getTypePtr();
520*67e74705SXin Li else if (QT->isArrayType())
521*67e74705SXin Li Ty = Ty->getBaseElementTypeUnsafe();
522*67e74705SXin Li
523*67e74705SXin Li const auto *RD = Ty->getAsCXXRecordDecl();
524*67e74705SXin Li if (!RD)
525*67e74705SXin Li return;
526*67e74705SXin Li
527*67e74705SXin Li if (const auto *Uuid = RD->getMostRecentDecl()->getAttr<UuidAttr>()) {
528*67e74705SXin Li UuidAttrs.insert(Uuid);
529*67e74705SXin Li return;
530*67e74705SXin Li }
531*67e74705SXin Li
532*67e74705SXin Li // __uuidof can grab UUIDs from template arguments.
533*67e74705SXin Li if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
534*67e74705SXin Li const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
535*67e74705SXin Li for (const TemplateArgument &TA : TAL.asArray()) {
536*67e74705SXin Li const UuidAttr *UuidForTA = nullptr;
537*67e74705SXin Li if (TA.getKind() == TemplateArgument::Type)
538*67e74705SXin Li getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
539*67e74705SXin Li else if (TA.getKind() == TemplateArgument::Declaration)
540*67e74705SXin Li getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
541*67e74705SXin Li
542*67e74705SXin Li if (UuidForTA)
543*67e74705SXin Li UuidAttrs.insert(UuidForTA);
544*67e74705SXin Li }
545*67e74705SXin Li }
546*67e74705SXin Li }
547*67e74705SXin Li
548*67e74705SXin Li /// \brief Build a Microsoft __uuidof expression with a type operand.
BuildCXXUuidof(QualType TypeInfoType,SourceLocation TypeidLoc,TypeSourceInfo * Operand,SourceLocation RParenLoc)549*67e74705SXin Li ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
550*67e74705SXin Li SourceLocation TypeidLoc,
551*67e74705SXin Li TypeSourceInfo *Operand,
552*67e74705SXin Li SourceLocation RParenLoc) {
553*67e74705SXin Li StringRef UuidStr;
554*67e74705SXin Li if (!Operand->getType()->isDependentType()) {
555*67e74705SXin Li llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
556*67e74705SXin Li getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
557*67e74705SXin Li if (UuidAttrs.empty())
558*67e74705SXin Li return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
559*67e74705SXin Li if (UuidAttrs.size() > 1)
560*67e74705SXin Li return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
561*67e74705SXin Li UuidStr = UuidAttrs.back()->getGuid();
562*67e74705SXin Li }
563*67e74705SXin Li
564*67e74705SXin Li return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr,
565*67e74705SXin Li SourceRange(TypeidLoc, RParenLoc));
566*67e74705SXin Li }
567*67e74705SXin Li
568*67e74705SXin Li /// \brief Build a Microsoft __uuidof expression with an expression operand.
BuildCXXUuidof(QualType TypeInfoType,SourceLocation TypeidLoc,Expr * E,SourceLocation RParenLoc)569*67e74705SXin Li ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
570*67e74705SXin Li SourceLocation TypeidLoc,
571*67e74705SXin Li Expr *E,
572*67e74705SXin Li SourceLocation RParenLoc) {
573*67e74705SXin Li StringRef UuidStr;
574*67e74705SXin Li if (!E->getType()->isDependentType()) {
575*67e74705SXin Li if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
576*67e74705SXin Li UuidStr = "00000000-0000-0000-0000-000000000000";
577*67e74705SXin Li } else {
578*67e74705SXin Li llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
579*67e74705SXin Li getUuidAttrOfType(*this, E->getType(), UuidAttrs);
580*67e74705SXin Li if (UuidAttrs.empty())
581*67e74705SXin Li return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
582*67e74705SXin Li if (UuidAttrs.size() > 1)
583*67e74705SXin Li return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
584*67e74705SXin Li UuidStr = UuidAttrs.back()->getGuid();
585*67e74705SXin Li }
586*67e74705SXin Li }
587*67e74705SXin Li
588*67e74705SXin Li return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr,
589*67e74705SXin Li SourceRange(TypeidLoc, RParenLoc));
590*67e74705SXin Li }
591*67e74705SXin Li
592*67e74705SXin Li /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
593*67e74705SXin Li ExprResult
ActOnCXXUuidof(SourceLocation OpLoc,SourceLocation LParenLoc,bool isType,void * TyOrExpr,SourceLocation RParenLoc)594*67e74705SXin Li Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
595*67e74705SXin Li bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
596*67e74705SXin Li // If MSVCGuidDecl has not been cached, do the lookup.
597*67e74705SXin Li if (!MSVCGuidDecl) {
598*67e74705SXin Li IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
599*67e74705SXin Li LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
600*67e74705SXin Li LookupQualifiedName(R, Context.getTranslationUnitDecl());
601*67e74705SXin Li MSVCGuidDecl = R.getAsSingle<RecordDecl>();
602*67e74705SXin Li if (!MSVCGuidDecl)
603*67e74705SXin Li return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
604*67e74705SXin Li }
605*67e74705SXin Li
606*67e74705SXin Li QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
607*67e74705SXin Li
608*67e74705SXin Li if (isType) {
609*67e74705SXin Li // The operand is a type; handle it as such.
610*67e74705SXin Li TypeSourceInfo *TInfo = nullptr;
611*67e74705SXin Li QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
612*67e74705SXin Li &TInfo);
613*67e74705SXin Li if (T.isNull())
614*67e74705SXin Li return ExprError();
615*67e74705SXin Li
616*67e74705SXin Li if (!TInfo)
617*67e74705SXin Li TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
618*67e74705SXin Li
619*67e74705SXin Li return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
620*67e74705SXin Li }
621*67e74705SXin Li
622*67e74705SXin Li // The operand is an expression.
623*67e74705SXin Li return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
624*67e74705SXin Li }
625*67e74705SXin Li
626*67e74705SXin Li /// ActOnCXXBoolLiteral - Parse {true,false} literals.
627*67e74705SXin Li ExprResult
ActOnCXXBoolLiteral(SourceLocation OpLoc,tok::TokenKind Kind)628*67e74705SXin Li Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
629*67e74705SXin Li assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
630*67e74705SXin Li "Unknown C++ Boolean value!");
631*67e74705SXin Li return new (Context)
632*67e74705SXin Li CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
633*67e74705SXin Li }
634*67e74705SXin Li
635*67e74705SXin Li /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
636*67e74705SXin Li ExprResult
ActOnCXXNullPtrLiteral(SourceLocation Loc)637*67e74705SXin Li Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
638*67e74705SXin Li return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
639*67e74705SXin Li }
640*67e74705SXin Li
641*67e74705SXin Li /// ActOnCXXThrow - Parse throw expressions.
642*67e74705SXin Li ExprResult
ActOnCXXThrow(Scope * S,SourceLocation OpLoc,Expr * Ex)643*67e74705SXin Li Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
644*67e74705SXin Li bool IsThrownVarInScope = false;
645*67e74705SXin Li if (Ex) {
646*67e74705SXin Li // C++0x [class.copymove]p31:
647*67e74705SXin Li // When certain criteria are met, an implementation is allowed to omit the
648*67e74705SXin Li // copy/move construction of a class object [...]
649*67e74705SXin Li //
650*67e74705SXin Li // - in a throw-expression, when the operand is the name of a
651*67e74705SXin Li // non-volatile automatic object (other than a function or catch-
652*67e74705SXin Li // clause parameter) whose scope does not extend beyond the end of the
653*67e74705SXin Li // innermost enclosing try-block (if there is one), the copy/move
654*67e74705SXin Li // operation from the operand to the exception object (15.1) can be
655*67e74705SXin Li // omitted by constructing the automatic object directly into the
656*67e74705SXin Li // exception object
657*67e74705SXin Li if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
658*67e74705SXin Li if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
659*67e74705SXin Li if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
660*67e74705SXin Li for( ; S; S = S->getParent()) {
661*67e74705SXin Li if (S->isDeclScope(Var)) {
662*67e74705SXin Li IsThrownVarInScope = true;
663*67e74705SXin Li break;
664*67e74705SXin Li }
665*67e74705SXin Li
666*67e74705SXin Li if (S->getFlags() &
667*67e74705SXin Li (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
668*67e74705SXin Li Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
669*67e74705SXin Li Scope::TryScope))
670*67e74705SXin Li break;
671*67e74705SXin Li }
672*67e74705SXin Li }
673*67e74705SXin Li }
674*67e74705SXin Li }
675*67e74705SXin Li
676*67e74705SXin Li return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
677*67e74705SXin Li }
678*67e74705SXin Li
BuildCXXThrow(SourceLocation OpLoc,Expr * Ex,bool IsThrownVarInScope)679*67e74705SXin Li ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
680*67e74705SXin Li bool IsThrownVarInScope) {
681*67e74705SXin Li // Don't report an error if 'throw' is used in system headers.
682*67e74705SXin Li if (!getLangOpts().CXXExceptions &&
683*67e74705SXin Li !getSourceManager().isInSystemHeader(OpLoc))
684*67e74705SXin Li Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
685*67e74705SXin Li
686*67e74705SXin Li if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
687*67e74705SXin Li Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
688*67e74705SXin Li
689*67e74705SXin Li if (Ex && !Ex->isTypeDependent()) {
690*67e74705SXin Li QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
691*67e74705SXin Li if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
692*67e74705SXin Li return ExprError();
693*67e74705SXin Li
694*67e74705SXin Li // Initialize the exception result. This implicitly weeds out
695*67e74705SXin Li // abstract types or types with inaccessible copy constructors.
696*67e74705SXin Li
697*67e74705SXin Li // C++0x [class.copymove]p31:
698*67e74705SXin Li // When certain criteria are met, an implementation is allowed to omit the
699*67e74705SXin Li // copy/move construction of a class object [...]
700*67e74705SXin Li //
701*67e74705SXin Li // - in a throw-expression, when the operand is the name of a
702*67e74705SXin Li // non-volatile automatic object (other than a function or
703*67e74705SXin Li // catch-clause
704*67e74705SXin Li // parameter) whose scope does not extend beyond the end of the
705*67e74705SXin Li // innermost enclosing try-block (if there is one), the copy/move
706*67e74705SXin Li // operation from the operand to the exception object (15.1) can be
707*67e74705SXin Li // omitted by constructing the automatic object directly into the
708*67e74705SXin Li // exception object
709*67e74705SXin Li const VarDecl *NRVOVariable = nullptr;
710*67e74705SXin Li if (IsThrownVarInScope)
711*67e74705SXin Li NRVOVariable = getCopyElisionCandidate(QualType(), Ex, false);
712*67e74705SXin Li
713*67e74705SXin Li InitializedEntity Entity = InitializedEntity::InitializeException(
714*67e74705SXin Li OpLoc, ExceptionObjectTy,
715*67e74705SXin Li /*NRVO=*/NRVOVariable != nullptr);
716*67e74705SXin Li ExprResult Res = PerformMoveOrCopyInitialization(
717*67e74705SXin Li Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
718*67e74705SXin Li if (Res.isInvalid())
719*67e74705SXin Li return ExprError();
720*67e74705SXin Li Ex = Res.get();
721*67e74705SXin Li }
722*67e74705SXin Li
723*67e74705SXin Li return new (Context)
724*67e74705SXin Li CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
725*67e74705SXin Li }
726*67e74705SXin Li
727*67e74705SXin Li static void
collectPublicBases(CXXRecordDecl * RD,llvm::DenseMap<CXXRecordDecl *,unsigned> & SubobjectsSeen,llvm::SmallPtrSetImpl<CXXRecordDecl * > & VBases,llvm::SetVector<CXXRecordDecl * > & PublicSubobjectsSeen,bool ParentIsPublic)728*67e74705SXin Li collectPublicBases(CXXRecordDecl *RD,
729*67e74705SXin Li llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
730*67e74705SXin Li llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
731*67e74705SXin Li llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
732*67e74705SXin Li bool ParentIsPublic) {
733*67e74705SXin Li for (const CXXBaseSpecifier &BS : RD->bases()) {
734*67e74705SXin Li CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
735*67e74705SXin Li bool NewSubobject;
736*67e74705SXin Li // Virtual bases constitute the same subobject. Non-virtual bases are
737*67e74705SXin Li // always distinct subobjects.
738*67e74705SXin Li if (BS.isVirtual())
739*67e74705SXin Li NewSubobject = VBases.insert(BaseDecl).second;
740*67e74705SXin Li else
741*67e74705SXin Li NewSubobject = true;
742*67e74705SXin Li
743*67e74705SXin Li if (NewSubobject)
744*67e74705SXin Li ++SubobjectsSeen[BaseDecl];
745*67e74705SXin Li
746*67e74705SXin Li // Only add subobjects which have public access throughout the entire chain.
747*67e74705SXin Li bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
748*67e74705SXin Li if (PublicPath)
749*67e74705SXin Li PublicSubobjectsSeen.insert(BaseDecl);
750*67e74705SXin Li
751*67e74705SXin Li // Recurse on to each base subobject.
752*67e74705SXin Li collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
753*67e74705SXin Li PublicPath);
754*67e74705SXin Li }
755*67e74705SXin Li }
756*67e74705SXin Li
getUnambiguousPublicSubobjects(CXXRecordDecl * RD,llvm::SmallVectorImpl<CXXRecordDecl * > & Objects)757*67e74705SXin Li static void getUnambiguousPublicSubobjects(
758*67e74705SXin Li CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
759*67e74705SXin Li llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
760*67e74705SXin Li llvm::SmallSet<CXXRecordDecl *, 2> VBases;
761*67e74705SXin Li llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
762*67e74705SXin Li SubobjectsSeen[RD] = 1;
763*67e74705SXin Li PublicSubobjectsSeen.insert(RD);
764*67e74705SXin Li collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
765*67e74705SXin Li /*ParentIsPublic=*/true);
766*67e74705SXin Li
767*67e74705SXin Li for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
768*67e74705SXin Li // Skip ambiguous objects.
769*67e74705SXin Li if (SubobjectsSeen[PublicSubobject] > 1)
770*67e74705SXin Li continue;
771*67e74705SXin Li
772*67e74705SXin Li Objects.push_back(PublicSubobject);
773*67e74705SXin Li }
774*67e74705SXin Li }
775*67e74705SXin Li
776*67e74705SXin Li /// CheckCXXThrowOperand - Validate the operand of a throw.
CheckCXXThrowOperand(SourceLocation ThrowLoc,QualType ExceptionObjectTy,Expr * E)777*67e74705SXin Li bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
778*67e74705SXin Li QualType ExceptionObjectTy, Expr *E) {
779*67e74705SXin Li // If the type of the exception would be an incomplete type or a pointer
780*67e74705SXin Li // to an incomplete type other than (cv) void the program is ill-formed.
781*67e74705SXin Li QualType Ty = ExceptionObjectTy;
782*67e74705SXin Li bool isPointer = false;
783*67e74705SXin Li if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
784*67e74705SXin Li Ty = Ptr->getPointeeType();
785*67e74705SXin Li isPointer = true;
786*67e74705SXin Li }
787*67e74705SXin Li if (!isPointer || !Ty->isVoidType()) {
788*67e74705SXin Li if (RequireCompleteType(ThrowLoc, Ty,
789*67e74705SXin Li isPointer ? diag::err_throw_incomplete_ptr
790*67e74705SXin Li : diag::err_throw_incomplete,
791*67e74705SXin Li E->getSourceRange()))
792*67e74705SXin Li return true;
793*67e74705SXin Li
794*67e74705SXin Li if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
795*67e74705SXin Li diag::err_throw_abstract_type, E))
796*67e74705SXin Li return true;
797*67e74705SXin Li }
798*67e74705SXin Li
799*67e74705SXin Li // If the exception has class type, we need additional handling.
800*67e74705SXin Li CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
801*67e74705SXin Li if (!RD)
802*67e74705SXin Li return false;
803*67e74705SXin Li
804*67e74705SXin Li // If we are throwing a polymorphic class type or pointer thereof,
805*67e74705SXin Li // exception handling will make use of the vtable.
806*67e74705SXin Li MarkVTableUsed(ThrowLoc, RD);
807*67e74705SXin Li
808*67e74705SXin Li // If a pointer is thrown, the referenced object will not be destroyed.
809*67e74705SXin Li if (isPointer)
810*67e74705SXin Li return false;
811*67e74705SXin Li
812*67e74705SXin Li // If the class has a destructor, we must be able to call it.
813*67e74705SXin Li if (!RD->hasIrrelevantDestructor()) {
814*67e74705SXin Li if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
815*67e74705SXin Li MarkFunctionReferenced(E->getExprLoc(), Destructor);
816*67e74705SXin Li CheckDestructorAccess(E->getExprLoc(), Destructor,
817*67e74705SXin Li PDiag(diag::err_access_dtor_exception) << Ty);
818*67e74705SXin Li if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
819*67e74705SXin Li return true;
820*67e74705SXin Li }
821*67e74705SXin Li }
822*67e74705SXin Li
823*67e74705SXin Li // The MSVC ABI creates a list of all types which can catch the exception
824*67e74705SXin Li // object. This list also references the appropriate copy constructor to call
825*67e74705SXin Li // if the object is caught by value and has a non-trivial copy constructor.
826*67e74705SXin Li if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
827*67e74705SXin Li // We are only interested in the public, unambiguous bases contained within
828*67e74705SXin Li // the exception object. Bases which are ambiguous or otherwise
829*67e74705SXin Li // inaccessible are not catchable types.
830*67e74705SXin Li llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
831*67e74705SXin Li getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
832*67e74705SXin Li
833*67e74705SXin Li for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
834*67e74705SXin Li // Attempt to lookup the copy constructor. Various pieces of machinery
835*67e74705SXin Li // will spring into action, like template instantiation, which means this
836*67e74705SXin Li // cannot be a simple walk of the class's decls. Instead, we must perform
837*67e74705SXin Li // lookup and overload resolution.
838*67e74705SXin Li CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
839*67e74705SXin Li if (!CD)
840*67e74705SXin Li continue;
841*67e74705SXin Li
842*67e74705SXin Li // Mark the constructor referenced as it is used by this throw expression.
843*67e74705SXin Li MarkFunctionReferenced(E->getExprLoc(), CD);
844*67e74705SXin Li
845*67e74705SXin Li // Skip this copy constructor if it is trivial, we don't need to record it
846*67e74705SXin Li // in the catchable type data.
847*67e74705SXin Li if (CD->isTrivial())
848*67e74705SXin Li continue;
849*67e74705SXin Li
850*67e74705SXin Li // The copy constructor is non-trivial, create a mapping from this class
851*67e74705SXin Li // type to this constructor.
852*67e74705SXin Li // N.B. The selection of copy constructor is not sensitive to this
853*67e74705SXin Li // particular throw-site. Lookup will be performed at the catch-site to
854*67e74705SXin Li // ensure that the copy constructor is, in fact, accessible (via
855*67e74705SXin Li // friendship or any other means).
856*67e74705SXin Li Context.addCopyConstructorForExceptionObject(Subobject, CD);
857*67e74705SXin Li
858*67e74705SXin Li // We don't keep the instantiated default argument expressions around so
859*67e74705SXin Li // we must rebuild them here.
860*67e74705SXin Li for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
861*67e74705SXin Li // Skip any default arguments that we've already instantiated.
862*67e74705SXin Li if (Context.getDefaultArgExprForConstructor(CD, I))
863*67e74705SXin Li continue;
864*67e74705SXin Li
865*67e74705SXin Li Expr *DefaultArg =
866*67e74705SXin Li BuildCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)).get();
867*67e74705SXin Li Context.addDefaultArgExprForConstructor(CD, I, DefaultArg);
868*67e74705SXin Li }
869*67e74705SXin Li }
870*67e74705SXin Li }
871*67e74705SXin Li
872*67e74705SXin Li return false;
873*67e74705SXin Li }
874*67e74705SXin Li
adjustCVQualifiersForCXXThisWithinLambda(ArrayRef<FunctionScopeInfo * > FunctionScopes,QualType ThisTy,DeclContext * CurSemaContext,ASTContext & ASTCtx)875*67e74705SXin Li static QualType adjustCVQualifiersForCXXThisWithinLambda(
876*67e74705SXin Li ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
877*67e74705SXin Li DeclContext *CurSemaContext, ASTContext &ASTCtx) {
878*67e74705SXin Li
879*67e74705SXin Li QualType ClassType = ThisTy->getPointeeType();
880*67e74705SXin Li LambdaScopeInfo *CurLSI = nullptr;
881*67e74705SXin Li DeclContext *CurDC = CurSemaContext;
882*67e74705SXin Li
883*67e74705SXin Li // Iterate through the stack of lambdas starting from the innermost lambda to
884*67e74705SXin Li // the outermost lambda, checking if '*this' is ever captured by copy - since
885*67e74705SXin Li // that could change the cv-qualifiers of the '*this' object.
886*67e74705SXin Li // The object referred to by '*this' starts out with the cv-qualifiers of its
887*67e74705SXin Li // member function. We then start with the innermost lambda and iterate
888*67e74705SXin Li // outward checking to see if any lambda performs a by-copy capture of '*this'
889*67e74705SXin Li // - and if so, any nested lambda must respect the 'constness' of that
890*67e74705SXin Li // capturing lamdbda's call operator.
891*67e74705SXin Li //
892*67e74705SXin Li
893*67e74705SXin Li // The issue is that we cannot rely entirely on the FunctionScopeInfo stack
894*67e74705SXin Li // since ScopeInfos are pushed on during parsing and treetransforming. But
895*67e74705SXin Li // since a generic lambda's call operator can be instantiated anywhere (even
896*67e74705SXin Li // end of the TU) we need to be able to examine its enclosing lambdas and so
897*67e74705SXin Li // we use the DeclContext to get a hold of the closure-class and query it for
898*67e74705SXin Li // capture information. The reason we don't just resort to always using the
899*67e74705SXin Li // DeclContext chain is that it is only mature for lambda expressions
900*67e74705SXin Li // enclosing generic lambda's call operators that are being instantiated.
901*67e74705SXin Li
902*67e74705SXin Li for (int I = FunctionScopes.size();
903*67e74705SXin Li I-- && isa<LambdaScopeInfo>(FunctionScopes[I]);
904*67e74705SXin Li CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
905*67e74705SXin Li CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
906*67e74705SXin Li
907*67e74705SXin Li if (!CurLSI->isCXXThisCaptured())
908*67e74705SXin Li continue;
909*67e74705SXin Li
910*67e74705SXin Li auto C = CurLSI->getCXXThisCapture();
911*67e74705SXin Li
912*67e74705SXin Li if (C.isCopyCapture()) {
913*67e74705SXin Li ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
914*67e74705SXin Li if (CurLSI->CallOperator->isConst())
915*67e74705SXin Li ClassType.addConst();
916*67e74705SXin Li return ASTCtx.getPointerType(ClassType);
917*67e74705SXin Li }
918*67e74705SXin Li }
919*67e74705SXin Li // We've run out of ScopeInfos but check if CurDC is a lambda (which can
920*67e74705SXin Li // happen during instantiation of generic lambdas)
921*67e74705SXin Li if (isLambdaCallOperator(CurDC)) {
922*67e74705SXin Li assert(CurLSI);
923*67e74705SXin Li assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator));
924*67e74705SXin Li assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
925*67e74705SXin Li
926*67e74705SXin Li auto IsThisCaptured =
927*67e74705SXin Li [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
928*67e74705SXin Li IsConst = false;
929*67e74705SXin Li IsByCopy = false;
930*67e74705SXin Li for (auto &&C : Closure->captures()) {
931*67e74705SXin Li if (C.capturesThis()) {
932*67e74705SXin Li if (C.getCaptureKind() == LCK_StarThis)
933*67e74705SXin Li IsByCopy = true;
934*67e74705SXin Li if (Closure->getLambdaCallOperator()->isConst())
935*67e74705SXin Li IsConst = true;
936*67e74705SXin Li return true;
937*67e74705SXin Li }
938*67e74705SXin Li }
939*67e74705SXin Li return false;
940*67e74705SXin Li };
941*67e74705SXin Li
942*67e74705SXin Li bool IsByCopyCapture = false;
943*67e74705SXin Li bool IsConstCapture = false;
944*67e74705SXin Li CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
945*67e74705SXin Li while (Closure &&
946*67e74705SXin Li IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
947*67e74705SXin Li if (IsByCopyCapture) {
948*67e74705SXin Li ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
949*67e74705SXin Li if (IsConstCapture)
950*67e74705SXin Li ClassType.addConst();
951*67e74705SXin Li return ASTCtx.getPointerType(ClassType);
952*67e74705SXin Li }
953*67e74705SXin Li Closure = isLambdaCallOperator(Closure->getParent())
954*67e74705SXin Li ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
955*67e74705SXin Li : nullptr;
956*67e74705SXin Li }
957*67e74705SXin Li }
958*67e74705SXin Li return ASTCtx.getPointerType(ClassType);
959*67e74705SXin Li }
960*67e74705SXin Li
getCurrentThisType()961*67e74705SXin Li QualType Sema::getCurrentThisType() {
962*67e74705SXin Li DeclContext *DC = getFunctionLevelDeclContext();
963*67e74705SXin Li QualType ThisTy = CXXThisTypeOverride;
964*67e74705SXin Li if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
965*67e74705SXin Li if (method && method->isInstance())
966*67e74705SXin Li ThisTy = method->getThisType(Context);
967*67e74705SXin Li }
968*67e74705SXin Li if (ThisTy.isNull()) {
969*67e74705SXin Li if (isGenericLambdaCallOperatorSpecialization(CurContext) &&
970*67e74705SXin Li CurContext->getParent()->getParent()->isRecord()) {
971*67e74705SXin Li // This is a generic lambda call operator that is being instantiated
972*67e74705SXin Li // within a default initializer - so use the enclosing class as 'this'.
973*67e74705SXin Li // There is no enclosing member function to retrieve the 'this' pointer
974*67e74705SXin Li // from.
975*67e74705SXin Li
976*67e74705SXin Li // FIXME: This looks wrong. If we're in a lambda within a lambda within a
977*67e74705SXin Li // default member initializer, we need to recurse up more parents to find
978*67e74705SXin Li // the right context. Looks like we should be walking up to the parent of
979*67e74705SXin Li // the closure type, checking whether that is itself a lambda, and if so,
980*67e74705SXin Li // recursing, until we reach a class or a function that isn't a lambda
981*67e74705SXin Li // call operator. And we should accumulate the constness of *this on the
982*67e74705SXin Li // way.
983*67e74705SXin Li
984*67e74705SXin Li QualType ClassTy = Context.getTypeDeclType(
985*67e74705SXin Li cast<CXXRecordDecl>(CurContext->getParent()->getParent()));
986*67e74705SXin Li // There are no cv-qualifiers for 'this' within default initializers,
987*67e74705SXin Li // per [expr.prim.general]p4.
988*67e74705SXin Li ThisTy = Context.getPointerType(ClassTy);
989*67e74705SXin Li }
990*67e74705SXin Li }
991*67e74705SXin Li
992*67e74705SXin Li // If we are within a lambda's call operator, the cv-qualifiers of 'this'
993*67e74705SXin Li // might need to be adjusted if the lambda or any of its enclosing lambda's
994*67e74705SXin Li // captures '*this' by copy.
995*67e74705SXin Li if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
996*67e74705SXin Li return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
997*67e74705SXin Li CurContext, Context);
998*67e74705SXin Li return ThisTy;
999*67e74705SXin Li }
1000*67e74705SXin Li
CXXThisScopeRAII(Sema & S,Decl * ContextDecl,unsigned CXXThisTypeQuals,bool Enabled)1001*67e74705SXin Li Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
1002*67e74705SXin Li Decl *ContextDecl,
1003*67e74705SXin Li unsigned CXXThisTypeQuals,
1004*67e74705SXin Li bool Enabled)
1005*67e74705SXin Li : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1006*67e74705SXin Li {
1007*67e74705SXin Li if (!Enabled || !ContextDecl)
1008*67e74705SXin Li return;
1009*67e74705SXin Li
1010*67e74705SXin Li CXXRecordDecl *Record = nullptr;
1011*67e74705SXin Li if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1012*67e74705SXin Li Record = Template->getTemplatedDecl();
1013*67e74705SXin Li else
1014*67e74705SXin Li Record = cast<CXXRecordDecl>(ContextDecl);
1015*67e74705SXin Li
1016*67e74705SXin Li // We care only for CVR qualifiers here, so cut everything else.
1017*67e74705SXin Li CXXThisTypeQuals &= Qualifiers::FastMask;
1018*67e74705SXin Li S.CXXThisTypeOverride
1019*67e74705SXin Li = S.Context.getPointerType(
1020*67e74705SXin Li S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
1021*67e74705SXin Li
1022*67e74705SXin Li this->Enabled = true;
1023*67e74705SXin Li }
1024*67e74705SXin Li
1025*67e74705SXin Li
~CXXThisScopeRAII()1026*67e74705SXin Li Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1027*67e74705SXin Li if (Enabled) {
1028*67e74705SXin Li S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1029*67e74705SXin Li }
1030*67e74705SXin Li }
1031*67e74705SXin Li
captureThis(Sema & S,ASTContext & Context,RecordDecl * RD,QualType ThisTy,SourceLocation Loc,const bool ByCopy)1032*67e74705SXin Li static Expr *captureThis(Sema &S, ASTContext &Context, RecordDecl *RD,
1033*67e74705SXin Li QualType ThisTy, SourceLocation Loc,
1034*67e74705SXin Li const bool ByCopy) {
1035*67e74705SXin Li
1036*67e74705SXin Li QualType AdjustedThisTy = ThisTy;
1037*67e74705SXin Li // The type of the corresponding data member (not a 'this' pointer if 'by
1038*67e74705SXin Li // copy').
1039*67e74705SXin Li QualType CaptureThisFieldTy = ThisTy;
1040*67e74705SXin Li if (ByCopy) {
1041*67e74705SXin Li // If we are capturing the object referred to by '*this' by copy, ignore any
1042*67e74705SXin Li // cv qualifiers inherited from the type of the member function for the type
1043*67e74705SXin Li // of the closure-type's corresponding data member and any use of 'this'.
1044*67e74705SXin Li CaptureThisFieldTy = ThisTy->getPointeeType();
1045*67e74705SXin Li CaptureThisFieldTy.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1046*67e74705SXin Li AdjustedThisTy = Context.getPointerType(CaptureThisFieldTy);
1047*67e74705SXin Li }
1048*67e74705SXin Li
1049*67e74705SXin Li FieldDecl *Field = FieldDecl::Create(
1050*67e74705SXin Li Context, RD, Loc, Loc, nullptr, CaptureThisFieldTy,
1051*67e74705SXin Li Context.getTrivialTypeSourceInfo(CaptureThisFieldTy, Loc), nullptr, false,
1052*67e74705SXin Li ICIS_NoInit);
1053*67e74705SXin Li
1054*67e74705SXin Li Field->setImplicit(true);
1055*67e74705SXin Li Field->setAccess(AS_private);
1056*67e74705SXin Li RD->addDecl(Field);
1057*67e74705SXin Li Expr *This =
1058*67e74705SXin Li new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/ true);
1059*67e74705SXin Li if (ByCopy) {
1060*67e74705SXin Li Expr *StarThis = S.CreateBuiltinUnaryOp(Loc,
1061*67e74705SXin Li UO_Deref,
1062*67e74705SXin Li This).get();
1063*67e74705SXin Li InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
1064*67e74705SXin Li nullptr, CaptureThisFieldTy, Loc);
1065*67e74705SXin Li InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
1066*67e74705SXin Li InitializationSequence Init(S, Entity, InitKind, StarThis);
1067*67e74705SXin Li ExprResult ER = Init.Perform(S, Entity, InitKind, StarThis);
1068*67e74705SXin Li if (ER.isInvalid()) return nullptr;
1069*67e74705SXin Li return ER.get();
1070*67e74705SXin Li }
1071*67e74705SXin Li return This;
1072*67e74705SXin Li }
1073*67e74705SXin Li
CheckCXXThisCapture(SourceLocation Loc,const bool Explicit,bool BuildAndDiagnose,const unsigned * const FunctionScopeIndexToStopAt,const bool ByCopy)1074*67e74705SXin Li bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
1075*67e74705SXin Li bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1076*67e74705SXin Li const bool ByCopy) {
1077*67e74705SXin Li // We don't need to capture this in an unevaluated context.
1078*67e74705SXin Li if (isUnevaluatedContext() && !Explicit)
1079*67e74705SXin Li return true;
1080*67e74705SXin Li
1081*67e74705SXin Li assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
1082*67e74705SXin Li
1083*67e74705SXin Li const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt ?
1084*67e74705SXin Li *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
1085*67e74705SXin Li
1086*67e74705SXin Li // Check that we can capture the *enclosing object* (referred to by '*this')
1087*67e74705SXin Li // by the capturing-entity/closure (lambda/block/etc) at
1088*67e74705SXin Li // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1089*67e74705SXin Li
1090*67e74705SXin Li // Note: The *enclosing object* can only be captured by-value by a
1091*67e74705SXin Li // closure that is a lambda, using the explicit notation:
1092*67e74705SXin Li // [*this] { ... }.
1093*67e74705SXin Li // Every other capture of the *enclosing object* results in its by-reference
1094*67e74705SXin Li // capture.
1095*67e74705SXin Li
1096*67e74705SXin Li // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1097*67e74705SXin Li // stack), we can capture the *enclosing object* only if:
1098*67e74705SXin Li // - 'L' has an explicit byref or byval capture of the *enclosing object*
1099*67e74705SXin Li // - or, 'L' has an implicit capture.
1100*67e74705SXin Li // AND
1101*67e74705SXin Li // -- there is no enclosing closure
1102*67e74705SXin Li // -- or, there is some enclosing closure 'E' that has already captured the
1103*67e74705SXin Li // *enclosing object*, and every intervening closure (if any) between 'E'
1104*67e74705SXin Li // and 'L' can implicitly capture the *enclosing object*.
1105*67e74705SXin Li // -- or, every enclosing closure can implicitly capture the
1106*67e74705SXin Li // *enclosing object*
1107*67e74705SXin Li
1108*67e74705SXin Li
1109*67e74705SXin Li unsigned NumCapturingClosures = 0;
1110*67e74705SXin Li for (unsigned idx = MaxFunctionScopesIndex; idx != 0; idx--) {
1111*67e74705SXin Li if (CapturingScopeInfo *CSI =
1112*67e74705SXin Li dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1113*67e74705SXin Li if (CSI->CXXThisCaptureIndex != 0) {
1114*67e74705SXin Li // 'this' is already being captured; there isn't anything more to do.
1115*67e74705SXin Li break;
1116*67e74705SXin Li }
1117*67e74705SXin Li LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1118*67e74705SXin Li if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1119*67e74705SXin Li // This context can't implicitly capture 'this'; fail out.
1120*67e74705SXin Li if (BuildAndDiagnose)
1121*67e74705SXin Li Diag(Loc, diag::err_this_capture)
1122*67e74705SXin Li << (Explicit && idx == MaxFunctionScopesIndex);
1123*67e74705SXin Li return true;
1124*67e74705SXin Li }
1125*67e74705SXin Li if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
1126*67e74705SXin Li CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
1127*67e74705SXin Li CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
1128*67e74705SXin Li CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
1129*67e74705SXin Li (Explicit && idx == MaxFunctionScopesIndex)) {
1130*67e74705SXin Li // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1131*67e74705SXin Li // iteration through can be an explicit capture, all enclosing closures,
1132*67e74705SXin Li // if any, must perform implicit captures.
1133*67e74705SXin Li
1134*67e74705SXin Li // This closure can capture 'this'; continue looking upwards.
1135*67e74705SXin Li NumCapturingClosures++;
1136*67e74705SXin Li continue;
1137*67e74705SXin Li }
1138*67e74705SXin Li // This context can't implicitly capture 'this'; fail out.
1139*67e74705SXin Li if (BuildAndDiagnose)
1140*67e74705SXin Li Diag(Loc, diag::err_this_capture)
1141*67e74705SXin Li << (Explicit && idx == MaxFunctionScopesIndex);
1142*67e74705SXin Li return true;
1143*67e74705SXin Li }
1144*67e74705SXin Li break;
1145*67e74705SXin Li }
1146*67e74705SXin Li if (!BuildAndDiagnose) return false;
1147*67e74705SXin Li
1148*67e74705SXin Li // If we got here, then the closure at MaxFunctionScopesIndex on the
1149*67e74705SXin Li // FunctionScopes stack, can capture the *enclosing object*, so capture it
1150*67e74705SXin Li // (including implicit by-reference captures in any enclosing closures).
1151*67e74705SXin Li
1152*67e74705SXin Li // In the loop below, respect the ByCopy flag only for the closure requesting
1153*67e74705SXin Li // the capture (i.e. first iteration through the loop below). Ignore it for
1154*67e74705SXin Li // all enclosing closure's upto NumCapturingClosures (since they must be
1155*67e74705SXin Li // implicitly capturing the *enclosing object* by reference (see loop
1156*67e74705SXin Li // above)).
1157*67e74705SXin Li assert((!ByCopy ||
1158*67e74705SXin Li dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1159*67e74705SXin Li "Only a lambda can capture the enclosing object (referred to by "
1160*67e74705SXin Li "*this) by copy");
1161*67e74705SXin Li // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
1162*67e74705SXin Li // contexts.
1163*67e74705SXin Li QualType ThisTy = getCurrentThisType();
1164*67e74705SXin Li for (unsigned idx = MaxFunctionScopesIndex; NumCapturingClosures;
1165*67e74705SXin Li --idx, --NumCapturingClosures) {
1166*67e74705SXin Li CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
1167*67e74705SXin Li Expr *ThisExpr = nullptr;
1168*67e74705SXin Li
1169*67e74705SXin Li if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
1170*67e74705SXin Li // For lambda expressions, build a field and an initializing expression,
1171*67e74705SXin Li // and capture the *enclosing object* by copy only if this is the first
1172*67e74705SXin Li // iteration.
1173*67e74705SXin Li ThisExpr = captureThis(*this, Context, LSI->Lambda, ThisTy, Loc,
1174*67e74705SXin Li ByCopy && idx == MaxFunctionScopesIndex);
1175*67e74705SXin Li
1176*67e74705SXin Li } else if (CapturedRegionScopeInfo *RSI
1177*67e74705SXin Li = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
1178*67e74705SXin Li ThisExpr =
1179*67e74705SXin Li captureThis(*this, Context, RSI->TheRecordDecl, ThisTy, Loc,
1180*67e74705SXin Li false/*ByCopy*/);
1181*67e74705SXin Li
1182*67e74705SXin Li bool isNested = NumCapturingClosures > 1;
1183*67e74705SXin Li CSI->addThisCapture(isNested, Loc, ThisExpr, ByCopy);
1184*67e74705SXin Li }
1185*67e74705SXin Li return false;
1186*67e74705SXin Li }
1187*67e74705SXin Li
ActOnCXXThis(SourceLocation Loc)1188*67e74705SXin Li ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
1189*67e74705SXin Li /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1190*67e74705SXin Li /// is a non-lvalue expression whose value is the address of the object for
1191*67e74705SXin Li /// which the function is called.
1192*67e74705SXin Li
1193*67e74705SXin Li QualType ThisTy = getCurrentThisType();
1194*67e74705SXin Li if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
1195*67e74705SXin Li
1196*67e74705SXin Li CheckCXXThisCapture(Loc);
1197*67e74705SXin Li return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
1198*67e74705SXin Li }
1199*67e74705SXin Li
isThisOutsideMemberFunctionBody(QualType BaseType)1200*67e74705SXin Li bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1201*67e74705SXin Li // If we're outside the body of a member function, then we'll have a specified
1202*67e74705SXin Li // type for 'this'.
1203*67e74705SXin Li if (CXXThisTypeOverride.isNull())
1204*67e74705SXin Li return false;
1205*67e74705SXin Li
1206*67e74705SXin Li // Determine whether we're looking into a class that's currently being
1207*67e74705SXin Li // defined.
1208*67e74705SXin Li CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1209*67e74705SXin Li return Class && Class->isBeingDefined();
1210*67e74705SXin Li }
1211*67e74705SXin Li
1212*67e74705SXin Li ExprResult
ActOnCXXTypeConstructExpr(ParsedType TypeRep,SourceLocation LParenLoc,MultiExprArg exprs,SourceLocation RParenLoc)1213*67e74705SXin Li Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
1214*67e74705SXin Li SourceLocation LParenLoc,
1215*67e74705SXin Li MultiExprArg exprs,
1216*67e74705SXin Li SourceLocation RParenLoc) {
1217*67e74705SXin Li if (!TypeRep)
1218*67e74705SXin Li return ExprError();
1219*67e74705SXin Li
1220*67e74705SXin Li TypeSourceInfo *TInfo;
1221*67e74705SXin Li QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1222*67e74705SXin Li if (!TInfo)
1223*67e74705SXin Li TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
1224*67e74705SXin Li
1225*67e74705SXin Li auto Result = BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
1226*67e74705SXin Li // Avoid creating a non-type-dependent expression that contains typos.
1227*67e74705SXin Li // Non-type-dependent expressions are liable to be discarded without
1228*67e74705SXin Li // checking for embedded typos.
1229*67e74705SXin Li if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1230*67e74705SXin Li !Result.get()->isTypeDependent())
1231*67e74705SXin Li Result = CorrectDelayedTyposInExpr(Result.get());
1232*67e74705SXin Li return Result;
1233*67e74705SXin Li }
1234*67e74705SXin Li
1235*67e74705SXin Li /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
1236*67e74705SXin Li /// Can be interpreted either as function-style casting ("int(x)")
1237*67e74705SXin Li /// or class type construction ("ClassType(x,y,z)")
1238*67e74705SXin Li /// or creation of a value-initialized type ("int()").
1239*67e74705SXin Li ExprResult
BuildCXXTypeConstructExpr(TypeSourceInfo * TInfo,SourceLocation LParenLoc,MultiExprArg Exprs,SourceLocation RParenLoc)1240*67e74705SXin Li Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
1241*67e74705SXin Li SourceLocation LParenLoc,
1242*67e74705SXin Li MultiExprArg Exprs,
1243*67e74705SXin Li SourceLocation RParenLoc) {
1244*67e74705SXin Li QualType Ty = TInfo->getType();
1245*67e74705SXin Li SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
1246*67e74705SXin Li
1247*67e74705SXin Li if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
1248*67e74705SXin Li return CXXUnresolvedConstructExpr::Create(Context, TInfo, LParenLoc, Exprs,
1249*67e74705SXin Li RParenLoc);
1250*67e74705SXin Li }
1251*67e74705SXin Li
1252*67e74705SXin Li bool ListInitialization = LParenLoc.isInvalid();
1253*67e74705SXin Li assert((!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0])))
1254*67e74705SXin Li && "List initialization must have initializer list as expression.");
1255*67e74705SXin Li SourceRange FullRange = SourceRange(TyBeginLoc,
1256*67e74705SXin Li ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
1257*67e74705SXin Li
1258*67e74705SXin Li // C++ [expr.type.conv]p1:
1259*67e74705SXin Li // If the expression list is a single expression, the type conversion
1260*67e74705SXin Li // expression is equivalent (in definedness, and if defined in meaning) to the
1261*67e74705SXin Li // corresponding cast expression.
1262*67e74705SXin Li if (Exprs.size() == 1 && !ListInitialization) {
1263*67e74705SXin Li Expr *Arg = Exprs[0];
1264*67e74705SXin Li return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
1265*67e74705SXin Li }
1266*67e74705SXin Li
1267*67e74705SXin Li // C++14 [expr.type.conv]p2: The expression T(), where T is a
1268*67e74705SXin Li // simple-type-specifier or typename-specifier for a non-array complete
1269*67e74705SXin Li // object type or the (possibly cv-qualified) void type, creates a prvalue
1270*67e74705SXin Li // of the specified type, whose value is that produced by value-initializing
1271*67e74705SXin Li // an object of type T.
1272*67e74705SXin Li QualType ElemTy = Ty;
1273*67e74705SXin Li if (Ty->isArrayType()) {
1274*67e74705SXin Li if (!ListInitialization)
1275*67e74705SXin Li return ExprError(Diag(TyBeginLoc,
1276*67e74705SXin Li diag::err_value_init_for_array_type) << FullRange);
1277*67e74705SXin Li ElemTy = Context.getBaseElementType(Ty);
1278*67e74705SXin Li }
1279*67e74705SXin Li
1280*67e74705SXin Li if (!ListInitialization && Ty->isFunctionType())
1281*67e74705SXin Li return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_function_type)
1282*67e74705SXin Li << FullRange);
1283*67e74705SXin Li
1284*67e74705SXin Li if (!Ty->isVoidType() &&
1285*67e74705SXin Li RequireCompleteType(TyBeginLoc, ElemTy,
1286*67e74705SXin Li diag::err_invalid_incomplete_type_use, FullRange))
1287*67e74705SXin Li return ExprError();
1288*67e74705SXin Li
1289*67e74705SXin Li if (RequireNonAbstractType(TyBeginLoc, Ty,
1290*67e74705SXin Li diag::err_allocation_of_abstract_type))
1291*67e74705SXin Li return ExprError();
1292*67e74705SXin Li
1293*67e74705SXin Li InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
1294*67e74705SXin Li InitializationKind Kind =
1295*67e74705SXin Li Exprs.size() ? ListInitialization
1296*67e74705SXin Li ? InitializationKind::CreateDirectList(TyBeginLoc)
1297*67e74705SXin Li : InitializationKind::CreateDirect(TyBeginLoc, LParenLoc, RParenLoc)
1298*67e74705SXin Li : InitializationKind::CreateValue(TyBeginLoc, LParenLoc, RParenLoc);
1299*67e74705SXin Li InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1300*67e74705SXin Li ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
1301*67e74705SXin Li
1302*67e74705SXin Li if (Result.isInvalid() || !ListInitialization)
1303*67e74705SXin Li return Result;
1304*67e74705SXin Li
1305*67e74705SXin Li Expr *Inner = Result.get();
1306*67e74705SXin Li if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1307*67e74705SXin Li Inner = BTE->getSubExpr();
1308*67e74705SXin Li if (!isa<CXXTemporaryObjectExpr>(Inner)) {
1309*67e74705SXin Li // If we created a CXXTemporaryObjectExpr, that node also represents the
1310*67e74705SXin Li // functional cast. Otherwise, create an explicit cast to represent
1311*67e74705SXin Li // the syntactic form of a functional-style cast that was used here.
1312*67e74705SXin Li //
1313*67e74705SXin Li // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1314*67e74705SXin Li // would give a more consistent AST representation than using a
1315*67e74705SXin Li // CXXTemporaryObjectExpr. It's also weird that the functional cast
1316*67e74705SXin Li // is sometimes handled by initialization and sometimes not.
1317*67e74705SXin Li QualType ResultType = Result.get()->getType();
1318*67e74705SXin Li Result = CXXFunctionalCastExpr::Create(
1319*67e74705SXin Li Context, ResultType, Expr::getValueKindForType(TInfo->getType()), TInfo,
1320*67e74705SXin Li CK_NoOp, Result.get(), /*Path=*/nullptr, LParenLoc, RParenLoc);
1321*67e74705SXin Li }
1322*67e74705SXin Li
1323*67e74705SXin Li return Result;
1324*67e74705SXin Li }
1325*67e74705SXin Li
1326*67e74705SXin Li /// doesUsualArrayDeleteWantSize - Answers whether the usual
1327*67e74705SXin Li /// operator delete[] for the given type has a size_t parameter.
doesUsualArrayDeleteWantSize(Sema & S,SourceLocation loc,QualType allocType)1328*67e74705SXin Li static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1329*67e74705SXin Li QualType allocType) {
1330*67e74705SXin Li const RecordType *record =
1331*67e74705SXin Li allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1332*67e74705SXin Li if (!record) return false;
1333*67e74705SXin Li
1334*67e74705SXin Li // Try to find an operator delete[] in class scope.
1335*67e74705SXin Li
1336*67e74705SXin Li DeclarationName deleteName =
1337*67e74705SXin Li S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1338*67e74705SXin Li LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1339*67e74705SXin Li S.LookupQualifiedName(ops, record->getDecl());
1340*67e74705SXin Li
1341*67e74705SXin Li // We're just doing this for information.
1342*67e74705SXin Li ops.suppressDiagnostics();
1343*67e74705SXin Li
1344*67e74705SXin Li // Very likely: there's no operator delete[].
1345*67e74705SXin Li if (ops.empty()) return false;
1346*67e74705SXin Li
1347*67e74705SXin Li // If it's ambiguous, it should be illegal to call operator delete[]
1348*67e74705SXin Li // on this thing, so it doesn't matter if we allocate extra space or not.
1349*67e74705SXin Li if (ops.isAmbiguous()) return false;
1350*67e74705SXin Li
1351*67e74705SXin Li LookupResult::Filter filter = ops.makeFilter();
1352*67e74705SXin Li while (filter.hasNext()) {
1353*67e74705SXin Li NamedDecl *del = filter.next()->getUnderlyingDecl();
1354*67e74705SXin Li
1355*67e74705SXin Li // C++0x [basic.stc.dynamic.deallocation]p2:
1356*67e74705SXin Li // A template instance is never a usual deallocation function,
1357*67e74705SXin Li // regardless of its signature.
1358*67e74705SXin Li if (isa<FunctionTemplateDecl>(del)) {
1359*67e74705SXin Li filter.erase();
1360*67e74705SXin Li continue;
1361*67e74705SXin Li }
1362*67e74705SXin Li
1363*67e74705SXin Li // C++0x [basic.stc.dynamic.deallocation]p2:
1364*67e74705SXin Li // If class T does not declare [an operator delete[] with one
1365*67e74705SXin Li // parameter] but does declare a member deallocation function
1366*67e74705SXin Li // named operator delete[] with exactly two parameters, the
1367*67e74705SXin Li // second of which has type std::size_t, then this function
1368*67e74705SXin Li // is a usual deallocation function.
1369*67e74705SXin Li if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
1370*67e74705SXin Li filter.erase();
1371*67e74705SXin Li continue;
1372*67e74705SXin Li }
1373*67e74705SXin Li }
1374*67e74705SXin Li filter.done();
1375*67e74705SXin Li
1376*67e74705SXin Li if (!ops.isSingleResult()) return false;
1377*67e74705SXin Li
1378*67e74705SXin Li const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
1379*67e74705SXin Li return (del->getNumParams() == 2);
1380*67e74705SXin Li }
1381*67e74705SXin Li
1382*67e74705SXin Li /// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
1383*67e74705SXin Li ///
1384*67e74705SXin Li /// E.g.:
1385*67e74705SXin Li /// @code new (memory) int[size][4] @endcode
1386*67e74705SXin Li /// or
1387*67e74705SXin Li /// @code ::new Foo(23, "hello") @endcode
1388*67e74705SXin Li ///
1389*67e74705SXin Li /// \param StartLoc The first location of the expression.
1390*67e74705SXin Li /// \param UseGlobal True if 'new' was prefixed with '::'.
1391*67e74705SXin Li /// \param PlacementLParen Opening paren of the placement arguments.
1392*67e74705SXin Li /// \param PlacementArgs Placement new arguments.
1393*67e74705SXin Li /// \param PlacementRParen Closing paren of the placement arguments.
1394*67e74705SXin Li /// \param TypeIdParens If the type is in parens, the source range.
1395*67e74705SXin Li /// \param D The type to be allocated, as well as array dimensions.
1396*67e74705SXin Li /// \param Initializer The initializing expression or initializer-list, or null
1397*67e74705SXin Li /// if there is none.
1398*67e74705SXin Li ExprResult
ActOnCXXNew(SourceLocation StartLoc,bool UseGlobal,SourceLocation PlacementLParen,MultiExprArg PlacementArgs,SourceLocation PlacementRParen,SourceRange TypeIdParens,Declarator & D,Expr * Initializer)1399*67e74705SXin Li Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1400*67e74705SXin Li SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1401*67e74705SXin Li SourceLocation PlacementRParen, SourceRange TypeIdParens,
1402*67e74705SXin Li Declarator &D, Expr *Initializer) {
1403*67e74705SXin Li bool TypeContainsAuto = D.getDeclSpec().containsPlaceholderType();
1404*67e74705SXin Li
1405*67e74705SXin Li Expr *ArraySize = nullptr;
1406*67e74705SXin Li // If the specified type is an array, unwrap it and save the expression.
1407*67e74705SXin Li if (D.getNumTypeObjects() > 0 &&
1408*67e74705SXin Li D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
1409*67e74705SXin Li DeclaratorChunk &Chunk = D.getTypeObject(0);
1410*67e74705SXin Li if (TypeContainsAuto)
1411*67e74705SXin Li return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1412*67e74705SXin Li << D.getSourceRange());
1413*67e74705SXin Li if (Chunk.Arr.hasStatic)
1414*67e74705SXin Li return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1415*67e74705SXin Li << D.getSourceRange());
1416*67e74705SXin Li if (!Chunk.Arr.NumElts)
1417*67e74705SXin Li return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1418*67e74705SXin Li << D.getSourceRange());
1419*67e74705SXin Li
1420*67e74705SXin Li ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1421*67e74705SXin Li D.DropFirstTypeObject();
1422*67e74705SXin Li }
1423*67e74705SXin Li
1424*67e74705SXin Li // Every dimension shall be of constant size.
1425*67e74705SXin Li if (ArraySize) {
1426*67e74705SXin Li for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
1427*67e74705SXin Li if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1428*67e74705SXin Li break;
1429*67e74705SXin Li
1430*67e74705SXin Li DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1431*67e74705SXin Li if (Expr *NumElts = (Expr *)Array.NumElts) {
1432*67e74705SXin Li if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1433*67e74705SXin Li if (getLangOpts().CPlusPlus14) {
1434*67e74705SXin Li // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1435*67e74705SXin Li // shall be a converted constant expression (5.19) of type std::size_t
1436*67e74705SXin Li // and shall evaluate to a strictly positive value.
1437*67e74705SXin Li unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1438*67e74705SXin Li assert(IntWidth && "Builtin type of size 0?");
1439*67e74705SXin Li llvm::APSInt Value(IntWidth);
1440*67e74705SXin Li Array.NumElts
1441*67e74705SXin Li = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1442*67e74705SXin Li CCEK_NewExpr)
1443*67e74705SXin Li .get();
1444*67e74705SXin Li } else {
1445*67e74705SXin Li Array.NumElts
1446*67e74705SXin Li = VerifyIntegerConstantExpression(NumElts, nullptr,
1447*67e74705SXin Li diag::err_new_array_nonconst)
1448*67e74705SXin Li .get();
1449*67e74705SXin Li }
1450*67e74705SXin Li if (!Array.NumElts)
1451*67e74705SXin Li return ExprError();
1452*67e74705SXin Li }
1453*67e74705SXin Li }
1454*67e74705SXin Li }
1455*67e74705SXin Li }
1456*67e74705SXin Li
1457*67e74705SXin Li TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
1458*67e74705SXin Li QualType AllocType = TInfo->getType();
1459*67e74705SXin Li if (D.isInvalidType())
1460*67e74705SXin Li return ExprError();
1461*67e74705SXin Li
1462*67e74705SXin Li SourceRange DirectInitRange;
1463*67e74705SXin Li if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1464*67e74705SXin Li DirectInitRange = List->getSourceRange();
1465*67e74705SXin Li
1466*67e74705SXin Li return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
1467*67e74705SXin Li PlacementLParen,
1468*67e74705SXin Li PlacementArgs,
1469*67e74705SXin Li PlacementRParen,
1470*67e74705SXin Li TypeIdParens,
1471*67e74705SXin Li AllocType,
1472*67e74705SXin Li TInfo,
1473*67e74705SXin Li ArraySize,
1474*67e74705SXin Li DirectInitRange,
1475*67e74705SXin Li Initializer,
1476*67e74705SXin Li TypeContainsAuto);
1477*67e74705SXin Li }
1478*67e74705SXin Li
isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,Expr * Init)1479*67e74705SXin Li static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1480*67e74705SXin Li Expr *Init) {
1481*67e74705SXin Li if (!Init)
1482*67e74705SXin Li return true;
1483*67e74705SXin Li if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1484*67e74705SXin Li return PLE->getNumExprs() == 0;
1485*67e74705SXin Li if (isa<ImplicitValueInitExpr>(Init))
1486*67e74705SXin Li return true;
1487*67e74705SXin Li else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1488*67e74705SXin Li return !CCE->isListInitialization() &&
1489*67e74705SXin Li CCE->getConstructor()->isDefaultConstructor();
1490*67e74705SXin Li else if (Style == CXXNewExpr::ListInit) {
1491*67e74705SXin Li assert(isa<InitListExpr>(Init) &&
1492*67e74705SXin Li "Shouldn't create list CXXConstructExprs for arrays.");
1493*67e74705SXin Li return true;
1494*67e74705SXin Li }
1495*67e74705SXin Li return false;
1496*67e74705SXin Li }
1497*67e74705SXin Li
1498*67e74705SXin Li ExprResult
BuildCXXNew(SourceRange Range,bool UseGlobal,SourceLocation PlacementLParen,MultiExprArg PlacementArgs,SourceLocation PlacementRParen,SourceRange TypeIdParens,QualType AllocType,TypeSourceInfo * AllocTypeInfo,Expr * ArraySize,SourceRange DirectInitRange,Expr * Initializer,bool TypeMayContainAuto)1499*67e74705SXin Li Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
1500*67e74705SXin Li SourceLocation PlacementLParen,
1501*67e74705SXin Li MultiExprArg PlacementArgs,
1502*67e74705SXin Li SourceLocation PlacementRParen,
1503*67e74705SXin Li SourceRange TypeIdParens,
1504*67e74705SXin Li QualType AllocType,
1505*67e74705SXin Li TypeSourceInfo *AllocTypeInfo,
1506*67e74705SXin Li Expr *ArraySize,
1507*67e74705SXin Li SourceRange DirectInitRange,
1508*67e74705SXin Li Expr *Initializer,
1509*67e74705SXin Li bool TypeMayContainAuto) {
1510*67e74705SXin Li SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
1511*67e74705SXin Li SourceLocation StartLoc = Range.getBegin();
1512*67e74705SXin Li
1513*67e74705SXin Li CXXNewExpr::InitializationStyle initStyle;
1514*67e74705SXin Li if (DirectInitRange.isValid()) {
1515*67e74705SXin Li assert(Initializer && "Have parens but no initializer.");
1516*67e74705SXin Li initStyle = CXXNewExpr::CallInit;
1517*67e74705SXin Li } else if (Initializer && isa<InitListExpr>(Initializer))
1518*67e74705SXin Li initStyle = CXXNewExpr::ListInit;
1519*67e74705SXin Li else {
1520*67e74705SXin Li assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1521*67e74705SXin Li isa<CXXConstructExpr>(Initializer)) &&
1522*67e74705SXin Li "Initializer expression that cannot have been implicitly created.");
1523*67e74705SXin Li initStyle = CXXNewExpr::NoInit;
1524*67e74705SXin Li }
1525*67e74705SXin Li
1526*67e74705SXin Li Expr **Inits = &Initializer;
1527*67e74705SXin Li unsigned NumInits = Initializer ? 1 : 0;
1528*67e74705SXin Li if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1529*67e74705SXin Li assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1530*67e74705SXin Li Inits = List->getExprs();
1531*67e74705SXin Li NumInits = List->getNumExprs();
1532*67e74705SXin Li }
1533*67e74705SXin Li
1534*67e74705SXin Li // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1535*67e74705SXin Li if (TypeMayContainAuto && AllocType->isUndeducedType()) {
1536*67e74705SXin Li if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
1537*67e74705SXin Li return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1538*67e74705SXin Li << AllocType << TypeRange);
1539*67e74705SXin Li if (initStyle == CXXNewExpr::ListInit ||
1540*67e74705SXin Li (NumInits == 1 && isa<InitListExpr>(Inits[0])))
1541*67e74705SXin Li return ExprError(Diag(Inits[0]->getLocStart(),
1542*67e74705SXin Li diag::err_auto_new_list_init)
1543*67e74705SXin Li << AllocType << TypeRange);
1544*67e74705SXin Li if (NumInits > 1) {
1545*67e74705SXin Li Expr *FirstBad = Inits[1];
1546*67e74705SXin Li return ExprError(Diag(FirstBad->getLocStart(),
1547*67e74705SXin Li diag::err_auto_new_ctor_multiple_expressions)
1548*67e74705SXin Li << AllocType << TypeRange);
1549*67e74705SXin Li }
1550*67e74705SXin Li Expr *Deduce = Inits[0];
1551*67e74705SXin Li QualType DeducedType;
1552*67e74705SXin Li if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
1553*67e74705SXin Li return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
1554*67e74705SXin Li << AllocType << Deduce->getType()
1555*67e74705SXin Li << TypeRange << Deduce->getSourceRange());
1556*67e74705SXin Li if (DeducedType.isNull())
1557*67e74705SXin Li return ExprError();
1558*67e74705SXin Li AllocType = DeducedType;
1559*67e74705SXin Li }
1560*67e74705SXin Li
1561*67e74705SXin Li // Per C++0x [expr.new]p5, the type being constructed may be a
1562*67e74705SXin Li // typedef of an array type.
1563*67e74705SXin Li if (!ArraySize) {
1564*67e74705SXin Li if (const ConstantArrayType *Array
1565*67e74705SXin Li = Context.getAsConstantArrayType(AllocType)) {
1566*67e74705SXin Li ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1567*67e74705SXin Li Context.getSizeType(),
1568*67e74705SXin Li TypeRange.getEnd());
1569*67e74705SXin Li AllocType = Array->getElementType();
1570*67e74705SXin Li }
1571*67e74705SXin Li }
1572*67e74705SXin Li
1573*67e74705SXin Li if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1574*67e74705SXin Li return ExprError();
1575*67e74705SXin Li
1576*67e74705SXin Li if (initStyle == CXXNewExpr::ListInit &&
1577*67e74705SXin Li isStdInitializerList(AllocType, nullptr)) {
1578*67e74705SXin Li Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1579*67e74705SXin Li diag::warn_dangling_std_initializer_list)
1580*67e74705SXin Li << /*at end of FE*/0 << Inits[0]->getSourceRange();
1581*67e74705SXin Li }
1582*67e74705SXin Li
1583*67e74705SXin Li // In ARC, infer 'retaining' for the allocated
1584*67e74705SXin Li if (getLangOpts().ObjCAutoRefCount &&
1585*67e74705SXin Li AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1586*67e74705SXin Li AllocType->isObjCLifetimeType()) {
1587*67e74705SXin Li AllocType = Context.getLifetimeQualifiedType(AllocType,
1588*67e74705SXin Li AllocType->getObjCARCImplicitLifetime());
1589*67e74705SXin Li }
1590*67e74705SXin Li
1591*67e74705SXin Li QualType ResultType = Context.getPointerType(AllocType);
1592*67e74705SXin Li
1593*67e74705SXin Li if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1594*67e74705SXin Li ExprResult result = CheckPlaceholderExpr(ArraySize);
1595*67e74705SXin Li if (result.isInvalid()) return ExprError();
1596*67e74705SXin Li ArraySize = result.get();
1597*67e74705SXin Li }
1598*67e74705SXin Li // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1599*67e74705SXin Li // integral or enumeration type with a non-negative value."
1600*67e74705SXin Li // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1601*67e74705SXin Li // enumeration type, or a class type for which a single non-explicit
1602*67e74705SXin Li // conversion function to integral or unscoped enumeration type exists.
1603*67e74705SXin Li // C++1y [expr.new]p6: The expression [...] is implicitly converted to
1604*67e74705SXin Li // std::size_t.
1605*67e74705SXin Li if (ArraySize && !ArraySize->isTypeDependent()) {
1606*67e74705SXin Li ExprResult ConvertedSize;
1607*67e74705SXin Li if (getLangOpts().CPlusPlus14) {
1608*67e74705SXin Li assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1609*67e74705SXin Li
1610*67e74705SXin Li ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1611*67e74705SXin Li AA_Converting);
1612*67e74705SXin Li
1613*67e74705SXin Li if (!ConvertedSize.isInvalid() &&
1614*67e74705SXin Li ArraySize->getType()->getAs<RecordType>())
1615*67e74705SXin Li // Diagnose the compatibility of this conversion.
1616*67e74705SXin Li Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1617*67e74705SXin Li << ArraySize->getType() << 0 << "'size_t'";
1618*67e74705SXin Li } else {
1619*67e74705SXin Li class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1620*67e74705SXin Li protected:
1621*67e74705SXin Li Expr *ArraySize;
1622*67e74705SXin Li
1623*67e74705SXin Li public:
1624*67e74705SXin Li SizeConvertDiagnoser(Expr *ArraySize)
1625*67e74705SXin Li : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1626*67e74705SXin Li ArraySize(ArraySize) {}
1627*67e74705SXin Li
1628*67e74705SXin Li SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1629*67e74705SXin Li QualType T) override {
1630*67e74705SXin Li return S.Diag(Loc, diag::err_array_size_not_integral)
1631*67e74705SXin Li << S.getLangOpts().CPlusPlus11 << T;
1632*67e74705SXin Li }
1633*67e74705SXin Li
1634*67e74705SXin Li SemaDiagnosticBuilder diagnoseIncomplete(
1635*67e74705SXin Li Sema &S, SourceLocation Loc, QualType T) override {
1636*67e74705SXin Li return S.Diag(Loc, diag::err_array_size_incomplete_type)
1637*67e74705SXin Li << T << ArraySize->getSourceRange();
1638*67e74705SXin Li }
1639*67e74705SXin Li
1640*67e74705SXin Li SemaDiagnosticBuilder diagnoseExplicitConv(
1641*67e74705SXin Li Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
1642*67e74705SXin Li return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1643*67e74705SXin Li }
1644*67e74705SXin Li
1645*67e74705SXin Li SemaDiagnosticBuilder noteExplicitConv(
1646*67e74705SXin Li Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1647*67e74705SXin Li return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1648*67e74705SXin Li << ConvTy->isEnumeralType() << ConvTy;
1649*67e74705SXin Li }
1650*67e74705SXin Li
1651*67e74705SXin Li SemaDiagnosticBuilder diagnoseAmbiguous(
1652*67e74705SXin Li Sema &S, SourceLocation Loc, QualType T) override {
1653*67e74705SXin Li return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1654*67e74705SXin Li }
1655*67e74705SXin Li
1656*67e74705SXin Li SemaDiagnosticBuilder noteAmbiguous(
1657*67e74705SXin Li Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1658*67e74705SXin Li return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1659*67e74705SXin Li << ConvTy->isEnumeralType() << ConvTy;
1660*67e74705SXin Li }
1661*67e74705SXin Li
1662*67e74705SXin Li SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1663*67e74705SXin Li QualType T,
1664*67e74705SXin Li QualType ConvTy) override {
1665*67e74705SXin Li return S.Diag(Loc,
1666*67e74705SXin Li S.getLangOpts().CPlusPlus11
1667*67e74705SXin Li ? diag::warn_cxx98_compat_array_size_conversion
1668*67e74705SXin Li : diag::ext_array_size_conversion)
1669*67e74705SXin Li << T << ConvTy->isEnumeralType() << ConvTy;
1670*67e74705SXin Li }
1671*67e74705SXin Li } SizeDiagnoser(ArraySize);
1672*67e74705SXin Li
1673*67e74705SXin Li ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1674*67e74705SXin Li SizeDiagnoser);
1675*67e74705SXin Li }
1676*67e74705SXin Li if (ConvertedSize.isInvalid())
1677*67e74705SXin Li return ExprError();
1678*67e74705SXin Li
1679*67e74705SXin Li ArraySize = ConvertedSize.get();
1680*67e74705SXin Li QualType SizeType = ArraySize->getType();
1681*67e74705SXin Li
1682*67e74705SXin Li if (!SizeType->isIntegralOrUnscopedEnumerationType())
1683*67e74705SXin Li return ExprError();
1684*67e74705SXin Li
1685*67e74705SXin Li // C++98 [expr.new]p7:
1686*67e74705SXin Li // The expression in a direct-new-declarator shall have integral type
1687*67e74705SXin Li // with a non-negative value.
1688*67e74705SXin Li //
1689*67e74705SXin Li // Let's see if this is a constant < 0. If so, we reject it out of
1690*67e74705SXin Li // hand. Otherwise, if it's not a constant, we must have an unparenthesized
1691*67e74705SXin Li // array type.
1692*67e74705SXin Li //
1693*67e74705SXin Li // Note: such a construct has well-defined semantics in C++11: it throws
1694*67e74705SXin Li // std::bad_array_new_length.
1695*67e74705SXin Li if (!ArraySize->isValueDependent()) {
1696*67e74705SXin Li llvm::APSInt Value;
1697*67e74705SXin Li // We've already performed any required implicit conversion to integer or
1698*67e74705SXin Li // unscoped enumeration type.
1699*67e74705SXin Li if (ArraySize->isIntegerConstantExpr(Value, Context)) {
1700*67e74705SXin Li if (Value < llvm::APSInt(
1701*67e74705SXin Li llvm::APInt::getNullValue(Value.getBitWidth()),
1702*67e74705SXin Li Value.isUnsigned())) {
1703*67e74705SXin Li if (getLangOpts().CPlusPlus11)
1704*67e74705SXin Li Diag(ArraySize->getLocStart(),
1705*67e74705SXin Li diag::warn_typecheck_negative_array_new_size)
1706*67e74705SXin Li << ArraySize->getSourceRange();
1707*67e74705SXin Li else
1708*67e74705SXin Li return ExprError(Diag(ArraySize->getLocStart(),
1709*67e74705SXin Li diag::err_typecheck_negative_array_size)
1710*67e74705SXin Li << ArraySize->getSourceRange());
1711*67e74705SXin Li } else if (!AllocType->isDependentType()) {
1712*67e74705SXin Li unsigned ActiveSizeBits =
1713*67e74705SXin Li ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1714*67e74705SXin Li if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
1715*67e74705SXin Li if (getLangOpts().CPlusPlus11)
1716*67e74705SXin Li Diag(ArraySize->getLocStart(),
1717*67e74705SXin Li diag::warn_array_new_too_large)
1718*67e74705SXin Li << Value.toString(10)
1719*67e74705SXin Li << ArraySize->getSourceRange();
1720*67e74705SXin Li else
1721*67e74705SXin Li return ExprError(Diag(ArraySize->getLocStart(),
1722*67e74705SXin Li diag::err_array_too_large)
1723*67e74705SXin Li << Value.toString(10)
1724*67e74705SXin Li << ArraySize->getSourceRange());
1725*67e74705SXin Li }
1726*67e74705SXin Li }
1727*67e74705SXin Li } else if (TypeIdParens.isValid()) {
1728*67e74705SXin Li // Can't have dynamic array size when the type-id is in parentheses.
1729*67e74705SXin Li Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1730*67e74705SXin Li << ArraySize->getSourceRange()
1731*67e74705SXin Li << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1732*67e74705SXin Li << FixItHint::CreateRemoval(TypeIdParens.getEnd());
1733*67e74705SXin Li
1734*67e74705SXin Li TypeIdParens = SourceRange();
1735*67e74705SXin Li }
1736*67e74705SXin Li }
1737*67e74705SXin Li
1738*67e74705SXin Li // Note that we do *not* convert the argument in any way. It can
1739*67e74705SXin Li // be signed, larger than size_t, whatever.
1740*67e74705SXin Li }
1741*67e74705SXin Li
1742*67e74705SXin Li FunctionDecl *OperatorNew = nullptr;
1743*67e74705SXin Li FunctionDecl *OperatorDelete = nullptr;
1744*67e74705SXin Li
1745*67e74705SXin Li if (!AllocType->isDependentType() &&
1746*67e74705SXin Li !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
1747*67e74705SXin Li FindAllocationFunctions(StartLoc,
1748*67e74705SXin Li SourceRange(PlacementLParen, PlacementRParen),
1749*67e74705SXin Li UseGlobal, AllocType, ArraySize, PlacementArgs,
1750*67e74705SXin Li OperatorNew, OperatorDelete))
1751*67e74705SXin Li return ExprError();
1752*67e74705SXin Li
1753*67e74705SXin Li // If this is an array allocation, compute whether the usual array
1754*67e74705SXin Li // deallocation function for the type has a size_t parameter.
1755*67e74705SXin Li bool UsualArrayDeleteWantsSize = false;
1756*67e74705SXin Li if (ArraySize && !AllocType->isDependentType())
1757*67e74705SXin Li UsualArrayDeleteWantsSize
1758*67e74705SXin Li = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1759*67e74705SXin Li
1760*67e74705SXin Li SmallVector<Expr *, 8> AllPlaceArgs;
1761*67e74705SXin Li if (OperatorNew) {
1762*67e74705SXin Li const FunctionProtoType *Proto =
1763*67e74705SXin Li OperatorNew->getType()->getAs<FunctionProtoType>();
1764*67e74705SXin Li VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
1765*67e74705SXin Li : VariadicDoesNotApply;
1766*67e74705SXin Li
1767*67e74705SXin Li // We've already converted the placement args, just fill in any default
1768*67e74705SXin Li // arguments. Skip the first parameter because we don't have a corresponding
1769*67e74705SXin Li // argument.
1770*67e74705SXin Li if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto, 1,
1771*67e74705SXin Li PlacementArgs, AllPlaceArgs, CallType))
1772*67e74705SXin Li return ExprError();
1773*67e74705SXin Li
1774*67e74705SXin Li if (!AllPlaceArgs.empty())
1775*67e74705SXin Li PlacementArgs = AllPlaceArgs;
1776*67e74705SXin Li
1777*67e74705SXin Li // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
1778*67e74705SXin Li DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
1779*67e74705SXin Li
1780*67e74705SXin Li // FIXME: Missing call to CheckFunctionCall or equivalent
1781*67e74705SXin Li }
1782*67e74705SXin Li
1783*67e74705SXin Li // Warn if the type is over-aligned and is being allocated by global operator
1784*67e74705SXin Li // new.
1785*67e74705SXin Li if (PlacementArgs.empty() && OperatorNew &&
1786*67e74705SXin Li (OperatorNew->isImplicit() ||
1787*67e74705SXin Li (OperatorNew->getLocStart().isValid() &&
1788*67e74705SXin Li getSourceManager().isInSystemHeader(OperatorNew->getLocStart())))) {
1789*67e74705SXin Li if (unsigned Align = Context.getPreferredTypeAlign(AllocType.getTypePtr())){
1790*67e74705SXin Li unsigned SuitableAlign = Context.getTargetInfo().getSuitableAlign();
1791*67e74705SXin Li if (Align > SuitableAlign)
1792*67e74705SXin Li Diag(StartLoc, diag::warn_overaligned_type)
1793*67e74705SXin Li << AllocType
1794*67e74705SXin Li << unsigned(Align / Context.getCharWidth())
1795*67e74705SXin Li << unsigned(SuitableAlign / Context.getCharWidth());
1796*67e74705SXin Li }
1797*67e74705SXin Li }
1798*67e74705SXin Li
1799*67e74705SXin Li QualType InitType = AllocType;
1800*67e74705SXin Li // Array 'new' can't have any initializers except empty parentheses.
1801*67e74705SXin Li // Initializer lists are also allowed, in C++11. Rely on the parser for the
1802*67e74705SXin Li // dialect distinction.
1803*67e74705SXin Li if (ResultType->isArrayType() || ArraySize) {
1804*67e74705SXin Li if (!isLegalArrayNewInitializer(initStyle, Initializer)) {
1805*67e74705SXin Li SourceRange InitRange(Inits[0]->getLocStart(),
1806*67e74705SXin Li Inits[NumInits - 1]->getLocEnd());
1807*67e74705SXin Li Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1808*67e74705SXin Li return ExprError();
1809*67e74705SXin Li }
1810*67e74705SXin Li if (InitListExpr *ILE = dyn_cast_or_null<InitListExpr>(Initializer)) {
1811*67e74705SXin Li // We do the initialization typechecking against the array type
1812*67e74705SXin Li // corresponding to the number of initializers + 1 (to also check
1813*67e74705SXin Li // default-initialization).
1814*67e74705SXin Li unsigned NumElements = ILE->getNumInits() + 1;
1815*67e74705SXin Li InitType = Context.getConstantArrayType(AllocType,
1816*67e74705SXin Li llvm::APInt(Context.getTypeSize(Context.getSizeType()), NumElements),
1817*67e74705SXin Li ArrayType::Normal, 0);
1818*67e74705SXin Li }
1819*67e74705SXin Li }
1820*67e74705SXin Li
1821*67e74705SXin Li // If we can perform the initialization, and we've not already done so,
1822*67e74705SXin Li // do it now.
1823*67e74705SXin Li if (!AllocType->isDependentType() &&
1824*67e74705SXin Li !Expr::hasAnyTypeDependentArguments(
1825*67e74705SXin Li llvm::makeArrayRef(Inits, NumInits))) {
1826*67e74705SXin Li // C++11 [expr.new]p15:
1827*67e74705SXin Li // A new-expression that creates an object of type T initializes that
1828*67e74705SXin Li // object as follows:
1829*67e74705SXin Li InitializationKind Kind
1830*67e74705SXin Li // - If the new-initializer is omitted, the object is default-
1831*67e74705SXin Li // initialized (8.5); if no initialization is performed,
1832*67e74705SXin Li // the object has indeterminate value
1833*67e74705SXin Li = initStyle == CXXNewExpr::NoInit
1834*67e74705SXin Li ? InitializationKind::CreateDefault(TypeRange.getBegin())
1835*67e74705SXin Li // - Otherwise, the new-initializer is interpreted according to the
1836*67e74705SXin Li // initialization rules of 8.5 for direct-initialization.
1837*67e74705SXin Li : initStyle == CXXNewExpr::ListInit
1838*67e74705SXin Li ? InitializationKind::CreateDirectList(TypeRange.getBegin())
1839*67e74705SXin Li : InitializationKind::CreateDirect(TypeRange.getBegin(),
1840*67e74705SXin Li DirectInitRange.getBegin(),
1841*67e74705SXin Li DirectInitRange.getEnd());
1842*67e74705SXin Li
1843*67e74705SXin Li InitializedEntity Entity
1844*67e74705SXin Li = InitializedEntity::InitializeNew(StartLoc, InitType);
1845*67e74705SXin Li InitializationSequence InitSeq(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
1846*67e74705SXin Li ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
1847*67e74705SXin Li MultiExprArg(Inits, NumInits));
1848*67e74705SXin Li if (FullInit.isInvalid())
1849*67e74705SXin Li return ExprError();
1850*67e74705SXin Li
1851*67e74705SXin Li // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
1852*67e74705SXin Li // we don't want the initialized object to be destructed.
1853*67e74705SXin Li if (CXXBindTemporaryExpr *Binder =
1854*67e74705SXin Li dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
1855*67e74705SXin Li FullInit = Binder->getSubExpr();
1856*67e74705SXin Li
1857*67e74705SXin Li Initializer = FullInit.get();
1858*67e74705SXin Li }
1859*67e74705SXin Li
1860*67e74705SXin Li // Mark the new and delete operators as referenced.
1861*67e74705SXin Li if (OperatorNew) {
1862*67e74705SXin Li if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
1863*67e74705SXin Li return ExprError();
1864*67e74705SXin Li MarkFunctionReferenced(StartLoc, OperatorNew);
1865*67e74705SXin Li }
1866*67e74705SXin Li if (OperatorDelete) {
1867*67e74705SXin Li if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
1868*67e74705SXin Li return ExprError();
1869*67e74705SXin Li MarkFunctionReferenced(StartLoc, OperatorDelete);
1870*67e74705SXin Li }
1871*67e74705SXin Li
1872*67e74705SXin Li // C++0x [expr.new]p17:
1873*67e74705SXin Li // If the new expression creates an array of objects of class type,
1874*67e74705SXin Li // access and ambiguity control are done for the destructor.
1875*67e74705SXin Li QualType BaseAllocType = Context.getBaseElementType(AllocType);
1876*67e74705SXin Li if (ArraySize && !BaseAllocType->isDependentType()) {
1877*67e74705SXin Li if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
1878*67e74705SXin Li if (CXXDestructorDecl *dtor = LookupDestructor(
1879*67e74705SXin Li cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
1880*67e74705SXin Li MarkFunctionReferenced(StartLoc, dtor);
1881*67e74705SXin Li CheckDestructorAccess(StartLoc, dtor,
1882*67e74705SXin Li PDiag(diag::err_access_dtor)
1883*67e74705SXin Li << BaseAllocType);
1884*67e74705SXin Li if (DiagnoseUseOfDecl(dtor, StartLoc))
1885*67e74705SXin Li return ExprError();
1886*67e74705SXin Li }
1887*67e74705SXin Li }
1888*67e74705SXin Li }
1889*67e74705SXin Li
1890*67e74705SXin Li return new (Context)
1891*67e74705SXin Li CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete,
1892*67e74705SXin Li UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
1893*67e74705SXin Li ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo,
1894*67e74705SXin Li Range, DirectInitRange);
1895*67e74705SXin Li }
1896*67e74705SXin Li
1897*67e74705SXin Li /// \brief Checks that a type is suitable as the allocated type
1898*67e74705SXin Li /// in a new-expression.
CheckAllocatedType(QualType AllocType,SourceLocation Loc,SourceRange R)1899*67e74705SXin Li bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
1900*67e74705SXin Li SourceRange R) {
1901*67e74705SXin Li // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1902*67e74705SXin Li // abstract class type or array thereof.
1903*67e74705SXin Li if (AllocType->isFunctionType())
1904*67e74705SXin Li return Diag(Loc, diag::err_bad_new_type)
1905*67e74705SXin Li << AllocType << 0 << R;
1906*67e74705SXin Li else if (AllocType->isReferenceType())
1907*67e74705SXin Li return Diag(Loc, diag::err_bad_new_type)
1908*67e74705SXin Li << AllocType << 1 << R;
1909*67e74705SXin Li else if (!AllocType->isDependentType() &&
1910*67e74705SXin Li RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
1911*67e74705SXin Li return true;
1912*67e74705SXin Li else if (RequireNonAbstractType(Loc, AllocType,
1913*67e74705SXin Li diag::err_allocation_of_abstract_type))
1914*67e74705SXin Li return true;
1915*67e74705SXin Li else if (AllocType->isVariablyModifiedType())
1916*67e74705SXin Li return Diag(Loc, diag::err_variably_modified_new_type)
1917*67e74705SXin Li << AllocType;
1918*67e74705SXin Li else if (unsigned AddressSpace = AllocType.getAddressSpace())
1919*67e74705SXin Li return Diag(Loc, diag::err_address_space_qualified_new)
1920*67e74705SXin Li << AllocType.getUnqualifiedType() << AddressSpace;
1921*67e74705SXin Li else if (getLangOpts().ObjCAutoRefCount) {
1922*67e74705SXin Li if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
1923*67e74705SXin Li QualType BaseAllocType = Context.getBaseElementType(AT);
1924*67e74705SXin Li if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1925*67e74705SXin Li BaseAllocType->isObjCLifetimeType())
1926*67e74705SXin Li return Diag(Loc, diag::err_arc_new_array_without_ownership)
1927*67e74705SXin Li << BaseAllocType;
1928*67e74705SXin Li }
1929*67e74705SXin Li }
1930*67e74705SXin Li
1931*67e74705SXin Li return false;
1932*67e74705SXin Li }
1933*67e74705SXin Li
1934*67e74705SXin Li /// \brief Determine whether the given function is a non-placement
1935*67e74705SXin Li /// deallocation function.
isNonPlacementDeallocationFunction(Sema & S,FunctionDecl * FD)1936*67e74705SXin Li static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
1937*67e74705SXin Li if (FD->isInvalidDecl())
1938*67e74705SXin Li return false;
1939*67e74705SXin Li
1940*67e74705SXin Li if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1941*67e74705SXin Li return Method->isUsualDeallocationFunction();
1942*67e74705SXin Li
1943*67e74705SXin Li if (FD->getOverloadedOperator() != OO_Delete &&
1944*67e74705SXin Li FD->getOverloadedOperator() != OO_Array_Delete)
1945*67e74705SXin Li return false;
1946*67e74705SXin Li
1947*67e74705SXin Li if (FD->getNumParams() == 1)
1948*67e74705SXin Li return true;
1949*67e74705SXin Li
1950*67e74705SXin Li return S.getLangOpts().SizedDeallocation && FD->getNumParams() == 2 &&
1951*67e74705SXin Li S.Context.hasSameUnqualifiedType(FD->getParamDecl(1)->getType(),
1952*67e74705SXin Li S.Context.getSizeType());
1953*67e74705SXin Li }
1954*67e74705SXin Li
1955*67e74705SXin Li /// FindAllocationFunctions - Finds the overloads of operator new and delete
1956*67e74705SXin Li /// that are appropriate for the allocation.
FindAllocationFunctions(SourceLocation StartLoc,SourceRange Range,bool UseGlobal,QualType AllocType,bool IsArray,MultiExprArg PlaceArgs,FunctionDecl * & OperatorNew,FunctionDecl * & OperatorDelete)1957*67e74705SXin Li bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1958*67e74705SXin Li bool UseGlobal, QualType AllocType,
1959*67e74705SXin Li bool IsArray, MultiExprArg PlaceArgs,
1960*67e74705SXin Li FunctionDecl *&OperatorNew,
1961*67e74705SXin Li FunctionDecl *&OperatorDelete) {
1962*67e74705SXin Li // --- Choosing an allocation function ---
1963*67e74705SXin Li // C++ 5.3.4p8 - 14 & 18
1964*67e74705SXin Li // 1) If UseGlobal is true, only look in the global scope. Else, also look
1965*67e74705SXin Li // in the scope of the allocated class.
1966*67e74705SXin Li // 2) If an array size is given, look for operator new[], else look for
1967*67e74705SXin Li // operator new.
1968*67e74705SXin Li // 3) The first argument is always size_t. Append the arguments from the
1969*67e74705SXin Li // placement form.
1970*67e74705SXin Li
1971*67e74705SXin Li SmallVector<Expr*, 8> AllocArgs(1 + PlaceArgs.size());
1972*67e74705SXin Li // We don't care about the actual value of this argument.
1973*67e74705SXin Li // FIXME: Should the Sema create the expression and embed it in the syntax
1974*67e74705SXin Li // tree? Or should the consumer just recalculate the value?
1975*67e74705SXin Li IntegerLiteral Size(Context, llvm::APInt::getNullValue(
1976*67e74705SXin Li Context.getTargetInfo().getPointerWidth(0)),
1977*67e74705SXin Li Context.getSizeType(),
1978*67e74705SXin Li SourceLocation());
1979*67e74705SXin Li AllocArgs[0] = &Size;
1980*67e74705SXin Li std::copy(PlaceArgs.begin(), PlaceArgs.end(), AllocArgs.begin() + 1);
1981*67e74705SXin Li
1982*67e74705SXin Li // C++ [expr.new]p8:
1983*67e74705SXin Li // If the allocated type is a non-array type, the allocation
1984*67e74705SXin Li // function's name is operator new and the deallocation function's
1985*67e74705SXin Li // name is operator delete. If the allocated type is an array
1986*67e74705SXin Li // type, the allocation function's name is operator new[] and the
1987*67e74705SXin Li // deallocation function's name is operator delete[].
1988*67e74705SXin Li DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1989*67e74705SXin Li IsArray ? OO_Array_New : OO_New);
1990*67e74705SXin Li DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1991*67e74705SXin Li IsArray ? OO_Array_Delete : OO_Delete);
1992*67e74705SXin Li
1993*67e74705SXin Li QualType AllocElemType = Context.getBaseElementType(AllocType);
1994*67e74705SXin Li
1995*67e74705SXin Li if (AllocElemType->isRecordType() && !UseGlobal) {
1996*67e74705SXin Li CXXRecordDecl *Record
1997*67e74705SXin Li = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
1998*67e74705SXin Li if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, Record,
1999*67e74705SXin Li /*AllowMissing=*/true, OperatorNew))
2000*67e74705SXin Li return true;
2001*67e74705SXin Li }
2002*67e74705SXin Li
2003*67e74705SXin Li if (!OperatorNew) {
2004*67e74705SXin Li // Didn't find a member overload. Look for a global one.
2005*67e74705SXin Li DeclareGlobalNewDelete();
2006*67e74705SXin Li DeclContext *TUDecl = Context.getTranslationUnitDecl();
2007*67e74705SXin Li bool FallbackEnabled = IsArray && Context.getLangOpts().MSVCCompat;
2008*67e74705SXin Li if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, TUDecl,
2009*67e74705SXin Li /*AllowMissing=*/FallbackEnabled, OperatorNew,
2010*67e74705SXin Li /*Diagnose=*/!FallbackEnabled)) {
2011*67e74705SXin Li if (!FallbackEnabled)
2012*67e74705SXin Li return true;
2013*67e74705SXin Li
2014*67e74705SXin Li // MSVC will fall back on trying to find a matching global operator new
2015*67e74705SXin Li // if operator new[] cannot be found. Also, MSVC will leak by not
2016*67e74705SXin Li // generating a call to operator delete or operator delete[], but we
2017*67e74705SXin Li // will not replicate that bug.
2018*67e74705SXin Li NewName = Context.DeclarationNames.getCXXOperatorName(OO_New);
2019*67e74705SXin Li DeleteName = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
2020*67e74705SXin Li if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, TUDecl,
2021*67e74705SXin Li /*AllowMissing=*/false, OperatorNew))
2022*67e74705SXin Li return true;
2023*67e74705SXin Li }
2024*67e74705SXin Li }
2025*67e74705SXin Li
2026*67e74705SXin Li // We don't need an operator delete if we're running under
2027*67e74705SXin Li // -fno-exceptions.
2028*67e74705SXin Li if (!getLangOpts().Exceptions) {
2029*67e74705SXin Li OperatorDelete = nullptr;
2030*67e74705SXin Li return false;
2031*67e74705SXin Li }
2032*67e74705SXin Li
2033*67e74705SXin Li // C++ [expr.new]p19:
2034*67e74705SXin Li //
2035*67e74705SXin Li // If the new-expression begins with a unary :: operator, the
2036*67e74705SXin Li // deallocation function's name is looked up in the global
2037*67e74705SXin Li // scope. Otherwise, if the allocated type is a class type T or an
2038*67e74705SXin Li // array thereof, the deallocation function's name is looked up in
2039*67e74705SXin Li // the scope of T. If this lookup fails to find the name, or if
2040*67e74705SXin Li // the allocated type is not a class type or array thereof, the
2041*67e74705SXin Li // deallocation function's name is looked up in the global scope.
2042*67e74705SXin Li LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
2043*67e74705SXin Li if (AllocElemType->isRecordType() && !UseGlobal) {
2044*67e74705SXin Li CXXRecordDecl *RD
2045*67e74705SXin Li = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
2046*67e74705SXin Li LookupQualifiedName(FoundDelete, RD);
2047*67e74705SXin Li }
2048*67e74705SXin Li if (FoundDelete.isAmbiguous())
2049*67e74705SXin Li return true; // FIXME: clean up expressions?
2050*67e74705SXin Li
2051*67e74705SXin Li if (FoundDelete.empty()) {
2052*67e74705SXin Li DeclareGlobalNewDelete();
2053*67e74705SXin Li LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2054*67e74705SXin Li }
2055*67e74705SXin Li
2056*67e74705SXin Li FoundDelete.suppressDiagnostics();
2057*67e74705SXin Li
2058*67e74705SXin Li SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
2059*67e74705SXin Li
2060*67e74705SXin Li // Whether we're looking for a placement operator delete is dictated
2061*67e74705SXin Li // by whether we selected a placement operator new, not by whether
2062*67e74705SXin Li // we had explicit placement arguments. This matters for things like
2063*67e74705SXin Li // struct A { void *operator new(size_t, int = 0); ... };
2064*67e74705SXin Li // A *a = new A()
2065*67e74705SXin Li bool isPlacementNew = (!PlaceArgs.empty() || OperatorNew->param_size() != 1);
2066*67e74705SXin Li
2067*67e74705SXin Li if (isPlacementNew) {
2068*67e74705SXin Li // C++ [expr.new]p20:
2069*67e74705SXin Li // A declaration of a placement deallocation function matches the
2070*67e74705SXin Li // declaration of a placement allocation function if it has the
2071*67e74705SXin Li // same number of parameters and, after parameter transformations
2072*67e74705SXin Li // (8.3.5), all parameter types except the first are
2073*67e74705SXin Li // identical. [...]
2074*67e74705SXin Li //
2075*67e74705SXin Li // To perform this comparison, we compute the function type that
2076*67e74705SXin Li // the deallocation function should have, and use that type both
2077*67e74705SXin Li // for template argument deduction and for comparison purposes.
2078*67e74705SXin Li //
2079*67e74705SXin Li // FIXME: this comparison should ignore CC and the like.
2080*67e74705SXin Li QualType ExpectedFunctionType;
2081*67e74705SXin Li {
2082*67e74705SXin Li const FunctionProtoType *Proto
2083*67e74705SXin Li = OperatorNew->getType()->getAs<FunctionProtoType>();
2084*67e74705SXin Li
2085*67e74705SXin Li SmallVector<QualType, 4> ArgTypes;
2086*67e74705SXin Li ArgTypes.push_back(Context.VoidPtrTy);
2087*67e74705SXin Li for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2088*67e74705SXin Li ArgTypes.push_back(Proto->getParamType(I));
2089*67e74705SXin Li
2090*67e74705SXin Li FunctionProtoType::ExtProtoInfo EPI;
2091*67e74705SXin Li EPI.Variadic = Proto->isVariadic();
2092*67e74705SXin Li
2093*67e74705SXin Li ExpectedFunctionType
2094*67e74705SXin Li = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
2095*67e74705SXin Li }
2096*67e74705SXin Li
2097*67e74705SXin Li for (LookupResult::iterator D = FoundDelete.begin(),
2098*67e74705SXin Li DEnd = FoundDelete.end();
2099*67e74705SXin Li D != DEnd; ++D) {
2100*67e74705SXin Li FunctionDecl *Fn = nullptr;
2101*67e74705SXin Li if (FunctionTemplateDecl *FnTmpl
2102*67e74705SXin Li = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2103*67e74705SXin Li // Perform template argument deduction to try to match the
2104*67e74705SXin Li // expected function type.
2105*67e74705SXin Li TemplateDeductionInfo Info(StartLoc);
2106*67e74705SXin Li if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2107*67e74705SXin Li Info))
2108*67e74705SXin Li continue;
2109*67e74705SXin Li } else
2110*67e74705SXin Li Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2111*67e74705SXin Li
2112*67e74705SXin Li if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
2113*67e74705SXin Li Matches.push_back(std::make_pair(D.getPair(), Fn));
2114*67e74705SXin Li }
2115*67e74705SXin Li } else {
2116*67e74705SXin Li // C++ [expr.new]p20:
2117*67e74705SXin Li // [...] Any non-placement deallocation function matches a
2118*67e74705SXin Li // non-placement allocation function. [...]
2119*67e74705SXin Li for (LookupResult::iterator D = FoundDelete.begin(),
2120*67e74705SXin Li DEnd = FoundDelete.end();
2121*67e74705SXin Li D != DEnd; ++D) {
2122*67e74705SXin Li if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
2123*67e74705SXin Li if (isNonPlacementDeallocationFunction(*this, Fn))
2124*67e74705SXin Li Matches.push_back(std::make_pair(D.getPair(), Fn));
2125*67e74705SXin Li }
2126*67e74705SXin Li
2127*67e74705SXin Li // C++1y [expr.new]p22:
2128*67e74705SXin Li // For a non-placement allocation function, the normal deallocation
2129*67e74705SXin Li // function lookup is used
2130*67e74705SXin Li // C++1y [expr.delete]p?:
2131*67e74705SXin Li // If [...] deallocation function lookup finds both a usual deallocation
2132*67e74705SXin Li // function with only a pointer parameter and a usual deallocation
2133*67e74705SXin Li // function with both a pointer parameter and a size parameter, then the
2134*67e74705SXin Li // selected deallocation function shall be the one with two parameters.
2135*67e74705SXin Li // Otherwise, the selected deallocation function shall be the function
2136*67e74705SXin Li // with one parameter.
2137*67e74705SXin Li if (getLangOpts().SizedDeallocation && Matches.size() == 2) {
2138*67e74705SXin Li if (Matches[0].second->getNumParams() == 1)
2139*67e74705SXin Li Matches.erase(Matches.begin());
2140*67e74705SXin Li else
2141*67e74705SXin Li Matches.erase(Matches.begin() + 1);
2142*67e74705SXin Li assert(Matches[0].second->getNumParams() == 2 &&
2143*67e74705SXin Li "found an unexpected usual deallocation function");
2144*67e74705SXin Li }
2145*67e74705SXin Li }
2146*67e74705SXin Li
2147*67e74705SXin Li // C++ [expr.new]p20:
2148*67e74705SXin Li // [...] If the lookup finds a single matching deallocation
2149*67e74705SXin Li // function, that function will be called; otherwise, no
2150*67e74705SXin Li // deallocation function will be called.
2151*67e74705SXin Li if (Matches.size() == 1) {
2152*67e74705SXin Li OperatorDelete = Matches[0].second;
2153*67e74705SXin Li
2154*67e74705SXin Li // C++0x [expr.new]p20:
2155*67e74705SXin Li // If the lookup finds the two-parameter form of a usual
2156*67e74705SXin Li // deallocation function (3.7.4.2) and that function, considered
2157*67e74705SXin Li // as a placement deallocation function, would have been
2158*67e74705SXin Li // selected as a match for the allocation function, the program
2159*67e74705SXin Li // is ill-formed.
2160*67e74705SXin Li if (!PlaceArgs.empty() && getLangOpts().CPlusPlus11 &&
2161*67e74705SXin Li isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
2162*67e74705SXin Li Diag(StartLoc, diag::err_placement_new_non_placement_delete)
2163*67e74705SXin Li << SourceRange(PlaceArgs.front()->getLocStart(),
2164*67e74705SXin Li PlaceArgs.back()->getLocEnd());
2165*67e74705SXin Li if (!OperatorDelete->isImplicit())
2166*67e74705SXin Li Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2167*67e74705SXin Li << DeleteName;
2168*67e74705SXin Li } else {
2169*67e74705SXin Li CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2170*67e74705SXin Li Matches[0].first);
2171*67e74705SXin Li }
2172*67e74705SXin Li }
2173*67e74705SXin Li
2174*67e74705SXin Li return false;
2175*67e74705SXin Li }
2176*67e74705SXin Li
2177*67e74705SXin Li /// \brief Find an fitting overload for the allocation function
2178*67e74705SXin Li /// in the specified scope.
2179*67e74705SXin Li ///
2180*67e74705SXin Li /// \param StartLoc The location of the 'new' token.
2181*67e74705SXin Li /// \param Range The range of the placement arguments.
2182*67e74705SXin Li /// \param Name The name of the function ('operator new' or 'operator new[]').
2183*67e74705SXin Li /// \param Args The placement arguments specified.
2184*67e74705SXin Li /// \param Ctx The scope in which we should search; either a class scope or the
2185*67e74705SXin Li /// translation unit.
2186*67e74705SXin Li /// \param AllowMissing If \c true, report an error if we can't find any
2187*67e74705SXin Li /// allocation functions. Otherwise, succeed but don't fill in \p
2188*67e74705SXin Li /// Operator.
2189*67e74705SXin Li /// \param Operator Filled in with the found allocation function. Unchanged if
2190*67e74705SXin Li /// no allocation function was found.
2191*67e74705SXin Li /// \param Diagnose If \c true, issue errors if the allocation function is not
2192*67e74705SXin Li /// usable.
FindAllocationOverload(SourceLocation StartLoc,SourceRange Range,DeclarationName Name,MultiExprArg Args,DeclContext * Ctx,bool AllowMissing,FunctionDecl * & Operator,bool Diagnose)2193*67e74705SXin Li bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
2194*67e74705SXin Li DeclarationName Name, MultiExprArg Args,
2195*67e74705SXin Li DeclContext *Ctx,
2196*67e74705SXin Li bool AllowMissing, FunctionDecl *&Operator,
2197*67e74705SXin Li bool Diagnose) {
2198*67e74705SXin Li LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
2199*67e74705SXin Li LookupQualifiedName(R, Ctx);
2200*67e74705SXin Li if (R.empty()) {
2201*67e74705SXin Li if (AllowMissing || !Diagnose)
2202*67e74705SXin Li return false;
2203*67e74705SXin Li return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
2204*67e74705SXin Li << Name << Range;
2205*67e74705SXin Li }
2206*67e74705SXin Li
2207*67e74705SXin Li if (R.isAmbiguous())
2208*67e74705SXin Li return true;
2209*67e74705SXin Li
2210*67e74705SXin Li R.suppressDiagnostics();
2211*67e74705SXin Li
2212*67e74705SXin Li OverloadCandidateSet Candidates(StartLoc, OverloadCandidateSet::CSK_Normal);
2213*67e74705SXin Li for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2214*67e74705SXin Li Alloc != AllocEnd; ++Alloc) {
2215*67e74705SXin Li // Even member operator new/delete are implicitly treated as
2216*67e74705SXin Li // static, so don't use AddMemberCandidate.
2217*67e74705SXin Li NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2218*67e74705SXin Li
2219*67e74705SXin Li if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2220*67e74705SXin Li AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2221*67e74705SXin Li /*ExplicitTemplateArgs=*/nullptr,
2222*67e74705SXin Li Args, Candidates,
2223*67e74705SXin Li /*SuppressUserConversions=*/false);
2224*67e74705SXin Li continue;
2225*67e74705SXin Li }
2226*67e74705SXin Li
2227*67e74705SXin Li FunctionDecl *Fn = cast<FunctionDecl>(D);
2228*67e74705SXin Li AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2229*67e74705SXin Li /*SuppressUserConversions=*/false);
2230*67e74705SXin Li }
2231*67e74705SXin Li
2232*67e74705SXin Li // Do the resolution.
2233*67e74705SXin Li OverloadCandidateSet::iterator Best;
2234*67e74705SXin Li switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
2235*67e74705SXin Li case OR_Success: {
2236*67e74705SXin Li // Got one!
2237*67e74705SXin Li FunctionDecl *FnDecl = Best->Function;
2238*67e74705SXin Li if (CheckAllocationAccess(StartLoc, Range, R.getNamingClass(),
2239*67e74705SXin Li Best->FoundDecl, Diagnose) == AR_inaccessible)
2240*67e74705SXin Li return true;
2241*67e74705SXin Li
2242*67e74705SXin Li Operator = FnDecl;
2243*67e74705SXin Li return false;
2244*67e74705SXin Li }
2245*67e74705SXin Li
2246*67e74705SXin Li case OR_No_Viable_Function:
2247*67e74705SXin Li if (Diagnose) {
2248*67e74705SXin Li Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
2249*67e74705SXin Li << Name << Range;
2250*67e74705SXin Li Candidates.NoteCandidates(*this, OCD_AllCandidates, Args);
2251*67e74705SXin Li }
2252*67e74705SXin Li return true;
2253*67e74705SXin Li
2254*67e74705SXin Li case OR_Ambiguous:
2255*67e74705SXin Li if (Diagnose) {
2256*67e74705SXin Li Diag(StartLoc, diag::err_ovl_ambiguous_call)
2257*67e74705SXin Li << Name << Range;
2258*67e74705SXin Li Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args);
2259*67e74705SXin Li }
2260*67e74705SXin Li return true;
2261*67e74705SXin Li
2262*67e74705SXin Li case OR_Deleted: {
2263*67e74705SXin Li if (Diagnose) {
2264*67e74705SXin Li Diag(StartLoc, diag::err_ovl_deleted_call)
2265*67e74705SXin Li << Best->Function->isDeleted()
2266*67e74705SXin Li << Name
2267*67e74705SXin Li << getDeletedOrUnavailableSuffix(Best->Function)
2268*67e74705SXin Li << Range;
2269*67e74705SXin Li Candidates.NoteCandidates(*this, OCD_AllCandidates, Args);
2270*67e74705SXin Li }
2271*67e74705SXin Li return true;
2272*67e74705SXin Li }
2273*67e74705SXin Li }
2274*67e74705SXin Li llvm_unreachable("Unreachable, bad result from BestViableFunction");
2275*67e74705SXin Li }
2276*67e74705SXin Li
2277*67e74705SXin Li
2278*67e74705SXin Li /// DeclareGlobalNewDelete - Declare the global forms of operator new and
2279*67e74705SXin Li /// delete. These are:
2280*67e74705SXin Li /// @code
2281*67e74705SXin Li /// // C++03:
2282*67e74705SXin Li /// void* operator new(std::size_t) throw(std::bad_alloc);
2283*67e74705SXin Li /// void* operator new[](std::size_t) throw(std::bad_alloc);
2284*67e74705SXin Li /// void operator delete(void *) throw();
2285*67e74705SXin Li /// void operator delete[](void *) throw();
2286*67e74705SXin Li /// // C++11:
2287*67e74705SXin Li /// void* operator new(std::size_t);
2288*67e74705SXin Li /// void* operator new[](std::size_t);
2289*67e74705SXin Li /// void operator delete(void *) noexcept;
2290*67e74705SXin Li /// void operator delete[](void *) noexcept;
2291*67e74705SXin Li /// // C++1y:
2292*67e74705SXin Li /// void* operator new(std::size_t);
2293*67e74705SXin Li /// void* operator new[](std::size_t);
2294*67e74705SXin Li /// void operator delete(void *) noexcept;
2295*67e74705SXin Li /// void operator delete[](void *) noexcept;
2296*67e74705SXin Li /// void operator delete(void *, std::size_t) noexcept;
2297*67e74705SXin Li /// void operator delete[](void *, std::size_t) noexcept;
2298*67e74705SXin Li /// @endcode
2299*67e74705SXin Li /// Note that the placement and nothrow forms of new are *not* implicitly
2300*67e74705SXin Li /// declared. Their use requires including \<new\>.
DeclareGlobalNewDelete()2301*67e74705SXin Li void Sema::DeclareGlobalNewDelete() {
2302*67e74705SXin Li if (GlobalNewDeleteDeclared)
2303*67e74705SXin Li return;
2304*67e74705SXin Li
2305*67e74705SXin Li // C++ [basic.std.dynamic]p2:
2306*67e74705SXin Li // [...] The following allocation and deallocation functions (18.4) are
2307*67e74705SXin Li // implicitly declared in global scope in each translation unit of a
2308*67e74705SXin Li // program
2309*67e74705SXin Li //
2310*67e74705SXin Li // C++03:
2311*67e74705SXin Li // void* operator new(std::size_t) throw(std::bad_alloc);
2312*67e74705SXin Li // void* operator new[](std::size_t) throw(std::bad_alloc);
2313*67e74705SXin Li // void operator delete(void*) throw();
2314*67e74705SXin Li // void operator delete[](void*) throw();
2315*67e74705SXin Li // C++11:
2316*67e74705SXin Li // void* operator new(std::size_t);
2317*67e74705SXin Li // void* operator new[](std::size_t);
2318*67e74705SXin Li // void operator delete(void*) noexcept;
2319*67e74705SXin Li // void operator delete[](void*) noexcept;
2320*67e74705SXin Li // C++1y:
2321*67e74705SXin Li // void* operator new(std::size_t);
2322*67e74705SXin Li // void* operator new[](std::size_t);
2323*67e74705SXin Li // void operator delete(void*) noexcept;
2324*67e74705SXin Li // void operator delete[](void*) noexcept;
2325*67e74705SXin Li // void operator delete(void*, std::size_t) noexcept;
2326*67e74705SXin Li // void operator delete[](void*, std::size_t) noexcept;
2327*67e74705SXin Li //
2328*67e74705SXin Li // These implicit declarations introduce only the function names operator
2329*67e74705SXin Li // new, operator new[], operator delete, operator delete[].
2330*67e74705SXin Li //
2331*67e74705SXin Li // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2332*67e74705SXin Li // "std" or "bad_alloc" as necessary to form the exception specification.
2333*67e74705SXin Li // However, we do not make these implicit declarations visible to name
2334*67e74705SXin Li // lookup.
2335*67e74705SXin Li if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
2336*67e74705SXin Li // The "std::bad_alloc" class has not yet been declared, so build it
2337*67e74705SXin Li // implicitly.
2338*67e74705SXin Li StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2339*67e74705SXin Li getOrCreateStdNamespace(),
2340*67e74705SXin Li SourceLocation(), SourceLocation(),
2341*67e74705SXin Li &PP.getIdentifierTable().get("bad_alloc"),
2342*67e74705SXin Li nullptr);
2343*67e74705SXin Li getStdBadAlloc()->setImplicit(true);
2344*67e74705SXin Li }
2345*67e74705SXin Li
2346*67e74705SXin Li GlobalNewDeleteDeclared = true;
2347*67e74705SXin Li
2348*67e74705SXin Li QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2349*67e74705SXin Li QualType SizeT = Context.getSizeType();
2350*67e74705SXin Li
2351*67e74705SXin Li DeclareGlobalAllocationFunction(
2352*67e74705SXin Li Context.DeclarationNames.getCXXOperatorName(OO_New),
2353*67e74705SXin Li VoidPtr, SizeT, QualType());
2354*67e74705SXin Li DeclareGlobalAllocationFunction(
2355*67e74705SXin Li Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
2356*67e74705SXin Li VoidPtr, SizeT, QualType());
2357*67e74705SXin Li DeclareGlobalAllocationFunction(
2358*67e74705SXin Li Context.DeclarationNames.getCXXOperatorName(OO_Delete),
2359*67e74705SXin Li Context.VoidTy, VoidPtr);
2360*67e74705SXin Li DeclareGlobalAllocationFunction(
2361*67e74705SXin Li Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
2362*67e74705SXin Li Context.VoidTy, VoidPtr);
2363*67e74705SXin Li if (getLangOpts().SizedDeallocation) {
2364*67e74705SXin Li DeclareGlobalAllocationFunction(
2365*67e74705SXin Li Context.DeclarationNames.getCXXOperatorName(OO_Delete),
2366*67e74705SXin Li Context.VoidTy, VoidPtr, Context.getSizeType());
2367*67e74705SXin Li DeclareGlobalAllocationFunction(
2368*67e74705SXin Li Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
2369*67e74705SXin Li Context.VoidTy, VoidPtr, Context.getSizeType());
2370*67e74705SXin Li }
2371*67e74705SXin Li }
2372*67e74705SXin Li
2373*67e74705SXin Li /// DeclareGlobalAllocationFunction - Declares a single implicit global
2374*67e74705SXin Li /// allocation function if it doesn't already exist.
DeclareGlobalAllocationFunction(DeclarationName Name,QualType Return,QualType Param1,QualType Param2)2375*67e74705SXin Li void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
2376*67e74705SXin Li QualType Return,
2377*67e74705SXin Li QualType Param1, QualType Param2) {
2378*67e74705SXin Li DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2379*67e74705SXin Li unsigned NumParams = Param2.isNull() ? 1 : 2;
2380*67e74705SXin Li
2381*67e74705SXin Li // Check if this function is already declared.
2382*67e74705SXin Li DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2383*67e74705SXin Li for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2384*67e74705SXin Li Alloc != AllocEnd; ++Alloc) {
2385*67e74705SXin Li // Only look at non-template functions, as it is the predefined,
2386*67e74705SXin Li // non-templated allocation function we are trying to declare here.
2387*67e74705SXin Li if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
2388*67e74705SXin Li if (Func->getNumParams() == NumParams) {
2389*67e74705SXin Li QualType InitialParam1Type =
2390*67e74705SXin Li Context.getCanonicalType(Func->getParamDecl(0)
2391*67e74705SXin Li ->getType().getUnqualifiedType());
2392*67e74705SXin Li QualType InitialParam2Type =
2393*67e74705SXin Li NumParams == 2
2394*67e74705SXin Li ? Context.getCanonicalType(Func->getParamDecl(1)
2395*67e74705SXin Li ->getType().getUnqualifiedType())
2396*67e74705SXin Li : QualType();
2397*67e74705SXin Li // FIXME: Do we need to check for default arguments here?
2398*67e74705SXin Li if (InitialParam1Type == Param1 &&
2399*67e74705SXin Li (NumParams == 1 || InitialParam2Type == Param2)) {
2400*67e74705SXin Li // Make the function visible to name lookup, even if we found it in
2401*67e74705SXin Li // an unimported module. It either is an implicitly-declared global
2402*67e74705SXin Li // allocation function, or is suppressing that function.
2403*67e74705SXin Li Func->setHidden(false);
2404*67e74705SXin Li return;
2405*67e74705SXin Li }
2406*67e74705SXin Li }
2407*67e74705SXin Li }
2408*67e74705SXin Li }
2409*67e74705SXin Li
2410*67e74705SXin Li FunctionProtoType::ExtProtoInfo EPI;
2411*67e74705SXin Li
2412*67e74705SXin Li QualType BadAllocType;
2413*67e74705SXin Li bool HasBadAllocExceptionSpec
2414*67e74705SXin Li = (Name.getCXXOverloadedOperator() == OO_New ||
2415*67e74705SXin Li Name.getCXXOverloadedOperator() == OO_Array_New);
2416*67e74705SXin Li if (HasBadAllocExceptionSpec) {
2417*67e74705SXin Li if (!getLangOpts().CPlusPlus11) {
2418*67e74705SXin Li BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
2419*67e74705SXin Li assert(StdBadAlloc && "Must have std::bad_alloc declared");
2420*67e74705SXin Li EPI.ExceptionSpec.Type = EST_Dynamic;
2421*67e74705SXin Li EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
2422*67e74705SXin Li }
2423*67e74705SXin Li } else {
2424*67e74705SXin Li EPI.ExceptionSpec =
2425*67e74705SXin Li getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
2426*67e74705SXin Li }
2427*67e74705SXin Li
2428*67e74705SXin Li QualType Params[] = { Param1, Param2 };
2429*67e74705SXin Li
2430*67e74705SXin Li QualType FnType = Context.getFunctionType(
2431*67e74705SXin Li Return, llvm::makeArrayRef(Params, NumParams), EPI);
2432*67e74705SXin Li FunctionDecl *Alloc =
2433*67e74705SXin Li FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
2434*67e74705SXin Li SourceLocation(), Name,
2435*67e74705SXin Li FnType, /*TInfo=*/nullptr, SC_None, false, true);
2436*67e74705SXin Li Alloc->setImplicit();
2437*67e74705SXin Li
2438*67e74705SXin Li // Implicit sized deallocation functions always have default visibility.
2439*67e74705SXin Li Alloc->addAttr(VisibilityAttr::CreateImplicit(Context,
2440*67e74705SXin Li VisibilityAttr::Default));
2441*67e74705SXin Li
2442*67e74705SXin Li ParmVarDecl *ParamDecls[2];
2443*67e74705SXin Li for (unsigned I = 0; I != NumParams; ++I) {
2444*67e74705SXin Li ParamDecls[I] = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
2445*67e74705SXin Li SourceLocation(), nullptr,
2446*67e74705SXin Li Params[I], /*TInfo=*/nullptr,
2447*67e74705SXin Li SC_None, nullptr);
2448*67e74705SXin Li ParamDecls[I]->setImplicit();
2449*67e74705SXin Li }
2450*67e74705SXin Li Alloc->setParams(llvm::makeArrayRef(ParamDecls, NumParams));
2451*67e74705SXin Li
2452*67e74705SXin Li Context.getTranslationUnitDecl()->addDecl(Alloc);
2453*67e74705SXin Li IdResolver.tryAddTopLevelDecl(Alloc, Name);
2454*67e74705SXin Li }
2455*67e74705SXin Li
FindUsualDeallocationFunction(SourceLocation StartLoc,bool CanProvideSize,DeclarationName Name)2456*67e74705SXin Li FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2457*67e74705SXin Li bool CanProvideSize,
2458*67e74705SXin Li DeclarationName Name) {
2459*67e74705SXin Li DeclareGlobalNewDelete();
2460*67e74705SXin Li
2461*67e74705SXin Li LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2462*67e74705SXin Li LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2463*67e74705SXin Li
2464*67e74705SXin Li // C++ [expr.new]p20:
2465*67e74705SXin Li // [...] Any non-placement deallocation function matches a
2466*67e74705SXin Li // non-placement allocation function. [...]
2467*67e74705SXin Li llvm::SmallVector<FunctionDecl*, 2> Matches;
2468*67e74705SXin Li for (LookupResult::iterator D = FoundDelete.begin(),
2469*67e74705SXin Li DEnd = FoundDelete.end();
2470*67e74705SXin Li D != DEnd; ++D) {
2471*67e74705SXin Li if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*D))
2472*67e74705SXin Li if (isNonPlacementDeallocationFunction(*this, Fn))
2473*67e74705SXin Li Matches.push_back(Fn);
2474*67e74705SXin Li }
2475*67e74705SXin Li
2476*67e74705SXin Li // C++1y [expr.delete]p?:
2477*67e74705SXin Li // If the type is complete and deallocation function lookup finds both a
2478*67e74705SXin Li // usual deallocation function with only a pointer parameter and a usual
2479*67e74705SXin Li // deallocation function with both a pointer parameter and a size
2480*67e74705SXin Li // parameter, then the selected deallocation function shall be the one
2481*67e74705SXin Li // with two parameters. Otherwise, the selected deallocation function
2482*67e74705SXin Li // shall be the function with one parameter.
2483*67e74705SXin Li if (getLangOpts().SizedDeallocation && Matches.size() == 2) {
2484*67e74705SXin Li unsigned NumArgs = CanProvideSize ? 2 : 1;
2485*67e74705SXin Li if (Matches[0]->getNumParams() != NumArgs)
2486*67e74705SXin Li Matches.erase(Matches.begin());
2487*67e74705SXin Li else
2488*67e74705SXin Li Matches.erase(Matches.begin() + 1);
2489*67e74705SXin Li assert(Matches[0]->getNumParams() == NumArgs &&
2490*67e74705SXin Li "found an unexpected usual deallocation function");
2491*67e74705SXin Li }
2492*67e74705SXin Li
2493*67e74705SXin Li if (getLangOpts().CUDA)
2494*67e74705SXin Li EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2495*67e74705SXin Li
2496*67e74705SXin Li assert(Matches.size() == 1 &&
2497*67e74705SXin Li "unexpectedly have multiple usual deallocation functions");
2498*67e74705SXin Li return Matches.front();
2499*67e74705SXin Li }
2500*67e74705SXin Li
FindDeallocationFunction(SourceLocation StartLoc,CXXRecordDecl * RD,DeclarationName Name,FunctionDecl * & Operator,bool Diagnose)2501*67e74705SXin Li bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2502*67e74705SXin Li DeclarationName Name,
2503*67e74705SXin Li FunctionDecl* &Operator, bool Diagnose) {
2504*67e74705SXin Li LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
2505*67e74705SXin Li // Try to find operator delete/operator delete[] in class scope.
2506*67e74705SXin Li LookupQualifiedName(Found, RD);
2507*67e74705SXin Li
2508*67e74705SXin Li if (Found.isAmbiguous())
2509*67e74705SXin Li return true;
2510*67e74705SXin Li
2511*67e74705SXin Li Found.suppressDiagnostics();
2512*67e74705SXin Li
2513*67e74705SXin Li SmallVector<DeclAccessPair,4> Matches;
2514*67e74705SXin Li for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
2515*67e74705SXin Li F != FEnd; ++F) {
2516*67e74705SXin Li NamedDecl *ND = (*F)->getUnderlyingDecl();
2517*67e74705SXin Li
2518*67e74705SXin Li // Ignore template operator delete members from the check for a usual
2519*67e74705SXin Li // deallocation function.
2520*67e74705SXin Li if (isa<FunctionTemplateDecl>(ND))
2521*67e74705SXin Li continue;
2522*67e74705SXin Li
2523*67e74705SXin Li if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
2524*67e74705SXin Li Matches.push_back(F.getPair());
2525*67e74705SXin Li }
2526*67e74705SXin Li
2527*67e74705SXin Li if (getLangOpts().CUDA)
2528*67e74705SXin Li EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2529*67e74705SXin Li
2530*67e74705SXin Li // There's exactly one suitable operator; pick it.
2531*67e74705SXin Li if (Matches.size() == 1) {
2532*67e74705SXin Li Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
2533*67e74705SXin Li
2534*67e74705SXin Li if (Operator->isDeleted()) {
2535*67e74705SXin Li if (Diagnose) {
2536*67e74705SXin Li Diag(StartLoc, diag::err_deleted_function_use);
2537*67e74705SXin Li NoteDeletedFunction(Operator);
2538*67e74705SXin Li }
2539*67e74705SXin Li return true;
2540*67e74705SXin Li }
2541*67e74705SXin Li
2542*67e74705SXin Li if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
2543*67e74705SXin Li Matches[0], Diagnose) == AR_inaccessible)
2544*67e74705SXin Li return true;
2545*67e74705SXin Li
2546*67e74705SXin Li return false;
2547*67e74705SXin Li
2548*67e74705SXin Li // We found multiple suitable operators; complain about the ambiguity.
2549*67e74705SXin Li } else if (!Matches.empty()) {
2550*67e74705SXin Li if (Diagnose) {
2551*67e74705SXin Li Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2552*67e74705SXin Li << Name << RD;
2553*67e74705SXin Li
2554*67e74705SXin Li for (SmallVectorImpl<DeclAccessPair>::iterator
2555*67e74705SXin Li F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
2556*67e74705SXin Li Diag((*F)->getUnderlyingDecl()->getLocation(),
2557*67e74705SXin Li diag::note_member_declared_here) << Name;
2558*67e74705SXin Li }
2559*67e74705SXin Li return true;
2560*67e74705SXin Li }
2561*67e74705SXin Li
2562*67e74705SXin Li // We did find operator delete/operator delete[] declarations, but
2563*67e74705SXin Li // none of them were suitable.
2564*67e74705SXin Li if (!Found.empty()) {
2565*67e74705SXin Li if (Diagnose) {
2566*67e74705SXin Li Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2567*67e74705SXin Li << Name << RD;
2568*67e74705SXin Li
2569*67e74705SXin Li for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
2570*67e74705SXin Li F != FEnd; ++F)
2571*67e74705SXin Li Diag((*F)->getUnderlyingDecl()->getLocation(),
2572*67e74705SXin Li diag::note_member_declared_here) << Name;
2573*67e74705SXin Li }
2574*67e74705SXin Li return true;
2575*67e74705SXin Li }
2576*67e74705SXin Li
2577*67e74705SXin Li Operator = nullptr;
2578*67e74705SXin Li return false;
2579*67e74705SXin Li }
2580*67e74705SXin Li
2581*67e74705SXin Li namespace {
2582*67e74705SXin Li /// \brief Checks whether delete-expression, and new-expression used for
2583*67e74705SXin Li /// initializing deletee have the same array form.
2584*67e74705SXin Li class MismatchingNewDeleteDetector {
2585*67e74705SXin Li public:
2586*67e74705SXin Li enum MismatchResult {
2587*67e74705SXin Li /// Indicates that there is no mismatch or a mismatch cannot be proven.
2588*67e74705SXin Li NoMismatch,
2589*67e74705SXin Li /// Indicates that variable is initialized with mismatching form of \a new.
2590*67e74705SXin Li VarInitMismatches,
2591*67e74705SXin Li /// Indicates that member is initialized with mismatching form of \a new.
2592*67e74705SXin Li MemberInitMismatches,
2593*67e74705SXin Li /// Indicates that 1 or more constructors' definitions could not been
2594*67e74705SXin Li /// analyzed, and they will be checked again at the end of translation unit.
2595*67e74705SXin Li AnalyzeLater
2596*67e74705SXin Li };
2597*67e74705SXin Li
2598*67e74705SXin Li /// \param EndOfTU True, if this is the final analysis at the end of
2599*67e74705SXin Li /// translation unit. False, if this is the initial analysis at the point
2600*67e74705SXin Li /// delete-expression was encountered.
MismatchingNewDeleteDetector(bool EndOfTU)2601*67e74705SXin Li explicit MismatchingNewDeleteDetector(bool EndOfTU)
2602*67e74705SXin Li : IsArrayForm(false), Field(nullptr), EndOfTU(EndOfTU),
2603*67e74705SXin Li HasUndefinedConstructors(false) {}
2604*67e74705SXin Li
2605*67e74705SXin Li /// \brief Checks whether pointee of a delete-expression is initialized with
2606*67e74705SXin Li /// matching form of new-expression.
2607*67e74705SXin Li ///
2608*67e74705SXin Li /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2609*67e74705SXin Li /// point where delete-expression is encountered, then a warning will be
2610*67e74705SXin Li /// issued immediately. If return value is \c AnalyzeLater at the point where
2611*67e74705SXin Li /// delete-expression is seen, then member will be analyzed at the end of
2612*67e74705SXin Li /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2613*67e74705SXin Li /// couldn't be analyzed. If at least one constructor initializes the member
2614*67e74705SXin Li /// with matching type of new, the return value is \c NoMismatch.
2615*67e74705SXin Li MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
2616*67e74705SXin Li /// \brief Analyzes a class member.
2617*67e74705SXin Li /// \param Field Class member to analyze.
2618*67e74705SXin Li /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
2619*67e74705SXin Li /// for deleting the \p Field.
2620*67e74705SXin Li MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
2621*67e74705SXin Li /// List of mismatching new-expressions used for initialization of the pointee
2622*67e74705SXin Li llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
2623*67e74705SXin Li /// Indicates whether delete-expression was in array form.
2624*67e74705SXin Li bool IsArrayForm;
2625*67e74705SXin Li FieldDecl *Field;
2626*67e74705SXin Li
2627*67e74705SXin Li private:
2628*67e74705SXin Li const bool EndOfTU;
2629*67e74705SXin Li /// \brief Indicates that there is at least one constructor without body.
2630*67e74705SXin Li bool HasUndefinedConstructors;
2631*67e74705SXin Li /// \brief Returns \c CXXNewExpr from given initialization expression.
2632*67e74705SXin Li /// \param E Expression used for initializing pointee in delete-expression.
2633*67e74705SXin Li /// E can be a single-element \c InitListExpr consisting of new-expression.
2634*67e74705SXin Li const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
2635*67e74705SXin Li /// \brief Returns whether member is initialized with mismatching form of
2636*67e74705SXin Li /// \c new either by the member initializer or in-class initialization.
2637*67e74705SXin Li ///
2638*67e74705SXin Li /// If bodies of all constructors are not visible at the end of translation
2639*67e74705SXin Li /// unit or at least one constructor initializes member with the matching
2640*67e74705SXin Li /// form of \c new, mismatch cannot be proven, and this function will return
2641*67e74705SXin Li /// \c NoMismatch.
2642*67e74705SXin Li MismatchResult analyzeMemberExpr(const MemberExpr *ME);
2643*67e74705SXin Li /// \brief Returns whether variable is initialized with mismatching form of
2644*67e74705SXin Li /// \c new.
2645*67e74705SXin Li ///
2646*67e74705SXin Li /// If variable is initialized with matching form of \c new or variable is not
2647*67e74705SXin Li /// initialized with a \c new expression, this function will return true.
2648*67e74705SXin Li /// If variable is initialized with mismatching form of \c new, returns false.
2649*67e74705SXin Li /// \param D Variable to analyze.
2650*67e74705SXin Li bool hasMatchingVarInit(const DeclRefExpr *D);
2651*67e74705SXin Li /// \brief Checks whether the constructor initializes pointee with mismatching
2652*67e74705SXin Li /// form of \c new.
2653*67e74705SXin Li ///
2654*67e74705SXin Li /// Returns true, if member is initialized with matching form of \c new in
2655*67e74705SXin Li /// member initializer list. Returns false, if member is initialized with the
2656*67e74705SXin Li /// matching form of \c new in this constructor's initializer or given
2657*67e74705SXin Li /// constructor isn't defined at the point where delete-expression is seen, or
2658*67e74705SXin Li /// member isn't initialized by the constructor.
2659*67e74705SXin Li bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
2660*67e74705SXin Li /// \brief Checks whether member is initialized with matching form of
2661*67e74705SXin Li /// \c new in member initializer list.
2662*67e74705SXin Li bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
2663*67e74705SXin Li /// Checks whether member is initialized with mismatching form of \c new by
2664*67e74705SXin Li /// in-class initializer.
2665*67e74705SXin Li MismatchResult analyzeInClassInitializer();
2666*67e74705SXin Li };
2667*67e74705SXin Li }
2668*67e74705SXin Li
2669*67e74705SXin Li MismatchingNewDeleteDetector::MismatchResult
analyzeDeleteExpr(const CXXDeleteExpr * DE)2670*67e74705SXin Li MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
2671*67e74705SXin Li NewExprs.clear();
2672*67e74705SXin Li assert(DE && "Expected delete-expression");
2673*67e74705SXin Li IsArrayForm = DE->isArrayForm();
2674*67e74705SXin Li const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
2675*67e74705SXin Li if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
2676*67e74705SXin Li return analyzeMemberExpr(ME);
2677*67e74705SXin Li } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
2678*67e74705SXin Li if (!hasMatchingVarInit(D))
2679*67e74705SXin Li return VarInitMismatches;
2680*67e74705SXin Li }
2681*67e74705SXin Li return NoMismatch;
2682*67e74705SXin Li }
2683*67e74705SXin Li
2684*67e74705SXin Li const CXXNewExpr *
getNewExprFromInitListOrExpr(const Expr * E)2685*67e74705SXin Li MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
2686*67e74705SXin Li assert(E != nullptr && "Expected a valid initializer expression");
2687*67e74705SXin Li E = E->IgnoreParenImpCasts();
2688*67e74705SXin Li if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
2689*67e74705SXin Li if (ILE->getNumInits() == 1)
2690*67e74705SXin Li E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
2691*67e74705SXin Li }
2692*67e74705SXin Li
2693*67e74705SXin Li return dyn_cast_or_null<const CXXNewExpr>(E);
2694*67e74705SXin Li }
2695*67e74705SXin Li
hasMatchingNewInCtorInit(const CXXCtorInitializer * CI)2696*67e74705SXin Li bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
2697*67e74705SXin Li const CXXCtorInitializer *CI) {
2698*67e74705SXin Li const CXXNewExpr *NE = nullptr;
2699*67e74705SXin Li if (Field == CI->getMember() &&
2700*67e74705SXin Li (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
2701*67e74705SXin Li if (NE->isArray() == IsArrayForm)
2702*67e74705SXin Li return true;
2703*67e74705SXin Li else
2704*67e74705SXin Li NewExprs.push_back(NE);
2705*67e74705SXin Li }
2706*67e74705SXin Li return false;
2707*67e74705SXin Li }
2708*67e74705SXin Li
hasMatchingNewInCtor(const CXXConstructorDecl * CD)2709*67e74705SXin Li bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
2710*67e74705SXin Li const CXXConstructorDecl *CD) {
2711*67e74705SXin Li if (CD->isImplicit())
2712*67e74705SXin Li return false;
2713*67e74705SXin Li const FunctionDecl *Definition = CD;
2714*67e74705SXin Li if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
2715*67e74705SXin Li HasUndefinedConstructors = true;
2716*67e74705SXin Li return EndOfTU;
2717*67e74705SXin Li }
2718*67e74705SXin Li for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
2719*67e74705SXin Li if (hasMatchingNewInCtorInit(CI))
2720*67e74705SXin Li return true;
2721*67e74705SXin Li }
2722*67e74705SXin Li return false;
2723*67e74705SXin Li }
2724*67e74705SXin Li
2725*67e74705SXin Li MismatchingNewDeleteDetector::MismatchResult
analyzeInClassInitializer()2726*67e74705SXin Li MismatchingNewDeleteDetector::analyzeInClassInitializer() {
2727*67e74705SXin Li assert(Field != nullptr && "This should be called only for members");
2728*67e74705SXin Li const Expr *InitExpr = Field->getInClassInitializer();
2729*67e74705SXin Li if (!InitExpr)
2730*67e74705SXin Li return EndOfTU ? NoMismatch : AnalyzeLater;
2731*67e74705SXin Li if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
2732*67e74705SXin Li if (NE->isArray() != IsArrayForm) {
2733*67e74705SXin Li NewExprs.push_back(NE);
2734*67e74705SXin Li return MemberInitMismatches;
2735*67e74705SXin Li }
2736*67e74705SXin Li }
2737*67e74705SXin Li return NoMismatch;
2738*67e74705SXin Li }
2739*67e74705SXin Li
2740*67e74705SXin Li MismatchingNewDeleteDetector::MismatchResult
analyzeField(FieldDecl * Field,bool DeleteWasArrayForm)2741*67e74705SXin Li MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
2742*67e74705SXin Li bool DeleteWasArrayForm) {
2743*67e74705SXin Li assert(Field != nullptr && "Analysis requires a valid class member.");
2744*67e74705SXin Li this->Field = Field;
2745*67e74705SXin Li IsArrayForm = DeleteWasArrayForm;
2746*67e74705SXin Li const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
2747*67e74705SXin Li for (const auto *CD : RD->ctors()) {
2748*67e74705SXin Li if (hasMatchingNewInCtor(CD))
2749*67e74705SXin Li return NoMismatch;
2750*67e74705SXin Li }
2751*67e74705SXin Li if (HasUndefinedConstructors)
2752*67e74705SXin Li return EndOfTU ? NoMismatch : AnalyzeLater;
2753*67e74705SXin Li if (!NewExprs.empty())
2754*67e74705SXin Li return MemberInitMismatches;
2755*67e74705SXin Li return Field->hasInClassInitializer() ? analyzeInClassInitializer()
2756*67e74705SXin Li : NoMismatch;
2757*67e74705SXin Li }
2758*67e74705SXin Li
2759*67e74705SXin Li MismatchingNewDeleteDetector::MismatchResult
analyzeMemberExpr(const MemberExpr * ME)2760*67e74705SXin Li MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
2761*67e74705SXin Li assert(ME != nullptr && "Expected a member expression");
2762*67e74705SXin Li if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2763*67e74705SXin Li return analyzeField(F, IsArrayForm);
2764*67e74705SXin Li return NoMismatch;
2765*67e74705SXin Li }
2766*67e74705SXin Li
hasMatchingVarInit(const DeclRefExpr * D)2767*67e74705SXin Li bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
2768*67e74705SXin Li const CXXNewExpr *NE = nullptr;
2769*67e74705SXin Li if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
2770*67e74705SXin Li if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
2771*67e74705SXin Li NE->isArray() != IsArrayForm) {
2772*67e74705SXin Li NewExprs.push_back(NE);
2773*67e74705SXin Li }
2774*67e74705SXin Li }
2775*67e74705SXin Li return NewExprs.empty();
2776*67e74705SXin Li }
2777*67e74705SXin Li
2778*67e74705SXin Li static void
DiagnoseMismatchedNewDelete(Sema & SemaRef,SourceLocation DeleteLoc,const MismatchingNewDeleteDetector & Detector)2779*67e74705SXin Li DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
2780*67e74705SXin Li const MismatchingNewDeleteDetector &Detector) {
2781*67e74705SXin Li SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
2782*67e74705SXin Li FixItHint H;
2783*67e74705SXin Li if (!Detector.IsArrayForm)
2784*67e74705SXin Li H = FixItHint::CreateInsertion(EndOfDelete, "[]");
2785*67e74705SXin Li else {
2786*67e74705SXin Li SourceLocation RSquare = Lexer::findLocationAfterToken(
2787*67e74705SXin Li DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
2788*67e74705SXin Li SemaRef.getLangOpts(), true);
2789*67e74705SXin Li if (RSquare.isValid())
2790*67e74705SXin Li H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
2791*67e74705SXin Li }
2792*67e74705SXin Li SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
2793*67e74705SXin Li << Detector.IsArrayForm << H;
2794*67e74705SXin Li
2795*67e74705SXin Li for (const auto *NE : Detector.NewExprs)
2796*67e74705SXin Li SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
2797*67e74705SXin Li << Detector.IsArrayForm;
2798*67e74705SXin Li }
2799*67e74705SXin Li
AnalyzeDeleteExprMismatch(const CXXDeleteExpr * DE)2800*67e74705SXin Li void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
2801*67e74705SXin Li if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
2802*67e74705SXin Li return;
2803*67e74705SXin Li MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
2804*67e74705SXin Li switch (Detector.analyzeDeleteExpr(DE)) {
2805*67e74705SXin Li case MismatchingNewDeleteDetector::VarInitMismatches:
2806*67e74705SXin Li case MismatchingNewDeleteDetector::MemberInitMismatches: {
2807*67e74705SXin Li DiagnoseMismatchedNewDelete(*this, DE->getLocStart(), Detector);
2808*67e74705SXin Li break;
2809*67e74705SXin Li }
2810*67e74705SXin Li case MismatchingNewDeleteDetector::AnalyzeLater: {
2811*67e74705SXin Li DeleteExprs[Detector.Field].push_back(
2812*67e74705SXin Li std::make_pair(DE->getLocStart(), DE->isArrayForm()));
2813*67e74705SXin Li break;
2814*67e74705SXin Li }
2815*67e74705SXin Li case MismatchingNewDeleteDetector::NoMismatch:
2816*67e74705SXin Li break;
2817*67e74705SXin Li }
2818*67e74705SXin Li }
2819*67e74705SXin Li
AnalyzeDeleteExprMismatch(FieldDecl * Field,SourceLocation DeleteLoc,bool DeleteWasArrayForm)2820*67e74705SXin Li void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
2821*67e74705SXin Li bool DeleteWasArrayForm) {
2822*67e74705SXin Li MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
2823*67e74705SXin Li switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
2824*67e74705SXin Li case MismatchingNewDeleteDetector::VarInitMismatches:
2825*67e74705SXin Li llvm_unreachable("This analysis should have been done for class members.");
2826*67e74705SXin Li case MismatchingNewDeleteDetector::AnalyzeLater:
2827*67e74705SXin Li llvm_unreachable("Analysis cannot be postponed any point beyond end of "
2828*67e74705SXin Li "translation unit.");
2829*67e74705SXin Li case MismatchingNewDeleteDetector::MemberInitMismatches:
2830*67e74705SXin Li DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
2831*67e74705SXin Li break;
2832*67e74705SXin Li case MismatchingNewDeleteDetector::NoMismatch:
2833*67e74705SXin Li break;
2834*67e74705SXin Li }
2835*67e74705SXin Li }
2836*67e74705SXin Li
2837*67e74705SXin Li /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
2838*67e74705SXin Li /// @code ::delete ptr; @endcode
2839*67e74705SXin Li /// or
2840*67e74705SXin Li /// @code delete [] ptr; @endcode
2841*67e74705SXin Li ExprResult
ActOnCXXDelete(SourceLocation StartLoc,bool UseGlobal,bool ArrayForm,Expr * ExE)2842*67e74705SXin Li Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
2843*67e74705SXin Li bool ArrayForm, Expr *ExE) {
2844*67e74705SXin Li // C++ [expr.delete]p1:
2845*67e74705SXin Li // The operand shall have a pointer type, or a class type having a single
2846*67e74705SXin Li // non-explicit conversion function to a pointer type. The result has type
2847*67e74705SXin Li // void.
2848*67e74705SXin Li //
2849*67e74705SXin Li // DR599 amends "pointer type" to "pointer to object type" in both cases.
2850*67e74705SXin Li
2851*67e74705SXin Li ExprResult Ex = ExE;
2852*67e74705SXin Li FunctionDecl *OperatorDelete = nullptr;
2853*67e74705SXin Li bool ArrayFormAsWritten = ArrayForm;
2854*67e74705SXin Li bool UsualArrayDeleteWantsSize = false;
2855*67e74705SXin Li
2856*67e74705SXin Li if (!Ex.get()->isTypeDependent()) {
2857*67e74705SXin Li // Perform lvalue-to-rvalue cast, if needed.
2858*67e74705SXin Li Ex = DefaultLvalueConversion(Ex.get());
2859*67e74705SXin Li if (Ex.isInvalid())
2860*67e74705SXin Li return ExprError();
2861*67e74705SXin Li
2862*67e74705SXin Li QualType Type = Ex.get()->getType();
2863*67e74705SXin Li
2864*67e74705SXin Li class DeleteConverter : public ContextualImplicitConverter {
2865*67e74705SXin Li public:
2866*67e74705SXin Li DeleteConverter() : ContextualImplicitConverter(false, true) {}
2867*67e74705SXin Li
2868*67e74705SXin Li bool match(QualType ConvType) override {
2869*67e74705SXin Li // FIXME: If we have an operator T* and an operator void*, we must pick
2870*67e74705SXin Li // the operator T*.
2871*67e74705SXin Li if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
2872*67e74705SXin Li if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
2873*67e74705SXin Li return true;
2874*67e74705SXin Li return false;
2875*67e74705SXin Li }
2876*67e74705SXin Li
2877*67e74705SXin Li SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
2878*67e74705SXin Li QualType T) override {
2879*67e74705SXin Li return S.Diag(Loc, diag::err_delete_operand) << T;
2880*67e74705SXin Li }
2881*67e74705SXin Li
2882*67e74705SXin Li SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
2883*67e74705SXin Li QualType T) override {
2884*67e74705SXin Li return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
2885*67e74705SXin Li }
2886*67e74705SXin Li
2887*67e74705SXin Li SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
2888*67e74705SXin Li QualType T,
2889*67e74705SXin Li QualType ConvTy) override {
2890*67e74705SXin Li return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
2891*67e74705SXin Li }
2892*67e74705SXin Li
2893*67e74705SXin Li SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
2894*67e74705SXin Li QualType ConvTy) override {
2895*67e74705SXin Li return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
2896*67e74705SXin Li << ConvTy;
2897*67e74705SXin Li }
2898*67e74705SXin Li
2899*67e74705SXin Li SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
2900*67e74705SXin Li QualType T) override {
2901*67e74705SXin Li return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
2902*67e74705SXin Li }
2903*67e74705SXin Li
2904*67e74705SXin Li SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
2905*67e74705SXin Li QualType ConvTy) override {
2906*67e74705SXin Li return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
2907*67e74705SXin Li << ConvTy;
2908*67e74705SXin Li }
2909*67e74705SXin Li
2910*67e74705SXin Li SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2911*67e74705SXin Li QualType T,
2912*67e74705SXin Li QualType ConvTy) override {
2913*67e74705SXin Li llvm_unreachable("conversion functions are permitted");
2914*67e74705SXin Li }
2915*67e74705SXin Li } Converter;
2916*67e74705SXin Li
2917*67e74705SXin Li Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
2918*67e74705SXin Li if (Ex.isInvalid())
2919*67e74705SXin Li return ExprError();
2920*67e74705SXin Li Type = Ex.get()->getType();
2921*67e74705SXin Li if (!Converter.match(Type))
2922*67e74705SXin Li // FIXME: PerformContextualImplicitConversion should return ExprError
2923*67e74705SXin Li // itself in this case.
2924*67e74705SXin Li return ExprError();
2925*67e74705SXin Li
2926*67e74705SXin Li QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
2927*67e74705SXin Li QualType PointeeElem = Context.getBaseElementType(Pointee);
2928*67e74705SXin Li
2929*67e74705SXin Li if (unsigned AddressSpace = Pointee.getAddressSpace())
2930*67e74705SXin Li return Diag(Ex.get()->getLocStart(),
2931*67e74705SXin Li diag::err_address_space_qualified_delete)
2932*67e74705SXin Li << Pointee.getUnqualifiedType() << AddressSpace;
2933*67e74705SXin Li
2934*67e74705SXin Li CXXRecordDecl *PointeeRD = nullptr;
2935*67e74705SXin Li if (Pointee->isVoidType() && !isSFINAEContext()) {
2936*67e74705SXin Li // The C++ standard bans deleting a pointer to a non-object type, which
2937*67e74705SXin Li // effectively bans deletion of "void*". However, most compilers support
2938*67e74705SXin Li // this, so we treat it as a warning unless we're in a SFINAE context.
2939*67e74705SXin Li Diag(StartLoc, diag::ext_delete_void_ptr_operand)
2940*67e74705SXin Li << Type << Ex.get()->getSourceRange();
2941*67e74705SXin Li } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
2942*67e74705SXin Li return ExprError(Diag(StartLoc, diag::err_delete_operand)
2943*67e74705SXin Li << Type << Ex.get()->getSourceRange());
2944*67e74705SXin Li } else if (!Pointee->isDependentType()) {
2945*67e74705SXin Li // FIXME: This can result in errors if the definition was imported from a
2946*67e74705SXin Li // module but is hidden.
2947*67e74705SXin Li if (!RequireCompleteType(StartLoc, Pointee,
2948*67e74705SXin Li diag::warn_delete_incomplete, Ex.get())) {
2949*67e74705SXin Li if (const RecordType *RT = PointeeElem->getAs<RecordType>())
2950*67e74705SXin Li PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
2951*67e74705SXin Li }
2952*67e74705SXin Li }
2953*67e74705SXin Li
2954*67e74705SXin Li if (Pointee->isArrayType() && !ArrayForm) {
2955*67e74705SXin Li Diag(StartLoc, diag::warn_delete_array_type)
2956*67e74705SXin Li << Type << Ex.get()->getSourceRange()
2957*67e74705SXin Li << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
2958*67e74705SXin Li ArrayForm = true;
2959*67e74705SXin Li }
2960*67e74705SXin Li
2961*67e74705SXin Li DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2962*67e74705SXin Li ArrayForm ? OO_Array_Delete : OO_Delete);
2963*67e74705SXin Li
2964*67e74705SXin Li if (PointeeRD) {
2965*67e74705SXin Li if (!UseGlobal &&
2966*67e74705SXin Li FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
2967*67e74705SXin Li OperatorDelete))
2968*67e74705SXin Li return ExprError();
2969*67e74705SXin Li
2970*67e74705SXin Li // If we're allocating an array of records, check whether the
2971*67e74705SXin Li // usual operator delete[] has a size_t parameter.
2972*67e74705SXin Li if (ArrayForm) {
2973*67e74705SXin Li // If the user specifically asked to use the global allocator,
2974*67e74705SXin Li // we'll need to do the lookup into the class.
2975*67e74705SXin Li if (UseGlobal)
2976*67e74705SXin Li UsualArrayDeleteWantsSize =
2977*67e74705SXin Li doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
2978*67e74705SXin Li
2979*67e74705SXin Li // Otherwise, the usual operator delete[] should be the
2980*67e74705SXin Li // function we just found.
2981*67e74705SXin Li else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
2982*67e74705SXin Li UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
2983*67e74705SXin Li }
2984*67e74705SXin Li
2985*67e74705SXin Li if (!PointeeRD->hasIrrelevantDestructor())
2986*67e74705SXin Li if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
2987*67e74705SXin Li MarkFunctionReferenced(StartLoc,
2988*67e74705SXin Li const_cast<CXXDestructorDecl*>(Dtor));
2989*67e74705SXin Li if (DiagnoseUseOfDecl(Dtor, StartLoc))
2990*67e74705SXin Li return ExprError();
2991*67e74705SXin Li }
2992*67e74705SXin Li
2993*67e74705SXin Li CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
2994*67e74705SXin Li /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
2995*67e74705SXin Li /*WarnOnNonAbstractTypes=*/!ArrayForm,
2996*67e74705SXin Li SourceLocation());
2997*67e74705SXin Li }
2998*67e74705SXin Li
2999*67e74705SXin Li if (!OperatorDelete)
3000*67e74705SXin Li // Look for a global declaration.
3001*67e74705SXin Li OperatorDelete = FindUsualDeallocationFunction(
3002*67e74705SXin Li StartLoc, isCompleteType(StartLoc, Pointee) &&
3003*67e74705SXin Li (!ArrayForm || UsualArrayDeleteWantsSize ||
3004*67e74705SXin Li Pointee.isDestructedType()),
3005*67e74705SXin Li DeleteName);
3006*67e74705SXin Li
3007*67e74705SXin Li MarkFunctionReferenced(StartLoc, OperatorDelete);
3008*67e74705SXin Li
3009*67e74705SXin Li // Check access and ambiguity of operator delete and destructor.
3010*67e74705SXin Li if (PointeeRD) {
3011*67e74705SXin Li if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3012*67e74705SXin Li CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3013*67e74705SXin Li PDiag(diag::err_access_dtor) << PointeeElem);
3014*67e74705SXin Li }
3015*67e74705SXin Li }
3016*67e74705SXin Li }
3017*67e74705SXin Li
3018*67e74705SXin Li CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
3019*67e74705SXin Li Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3020*67e74705SXin Li UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
3021*67e74705SXin Li AnalyzeDeleteExprMismatch(Result);
3022*67e74705SXin Li return Result;
3023*67e74705SXin Li }
3024*67e74705SXin Li
CheckVirtualDtorCall(CXXDestructorDecl * dtor,SourceLocation Loc,bool IsDelete,bool CallCanBeVirtual,bool WarnOnNonAbstractTypes,SourceLocation DtorLoc)3025*67e74705SXin Li void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3026*67e74705SXin Li bool IsDelete, bool CallCanBeVirtual,
3027*67e74705SXin Li bool WarnOnNonAbstractTypes,
3028*67e74705SXin Li SourceLocation DtorLoc) {
3029*67e74705SXin Li if (!dtor || dtor->isVirtual() || !CallCanBeVirtual)
3030*67e74705SXin Li return;
3031*67e74705SXin Li
3032*67e74705SXin Li // C++ [expr.delete]p3:
3033*67e74705SXin Li // In the first alternative (delete object), if the static type of the
3034*67e74705SXin Li // object to be deleted is different from its dynamic type, the static
3035*67e74705SXin Li // type shall be a base class of the dynamic type of the object to be
3036*67e74705SXin Li // deleted and the static type shall have a virtual destructor or the
3037*67e74705SXin Li // behavior is undefined.
3038*67e74705SXin Li //
3039*67e74705SXin Li const CXXRecordDecl *PointeeRD = dtor->getParent();
3040*67e74705SXin Li // Note: a final class cannot be derived from, no issue there
3041*67e74705SXin Li if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3042*67e74705SXin Li return;
3043*67e74705SXin Li
3044*67e74705SXin Li QualType ClassType = dtor->getThisType(Context)->getPointeeType();
3045*67e74705SXin Li if (PointeeRD->isAbstract()) {
3046*67e74705SXin Li // If the class is abstract, we warn by default, because we're
3047*67e74705SXin Li // sure the code has undefined behavior.
3048*67e74705SXin Li Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3049*67e74705SXin Li << ClassType;
3050*67e74705SXin Li } else if (WarnOnNonAbstractTypes) {
3051*67e74705SXin Li // Otherwise, if this is not an array delete, it's a bit suspect,
3052*67e74705SXin Li // but not necessarily wrong.
3053*67e74705SXin Li Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3054*67e74705SXin Li << ClassType;
3055*67e74705SXin Li }
3056*67e74705SXin Li if (!IsDelete) {
3057*67e74705SXin Li std::string TypeStr;
3058*67e74705SXin Li ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3059*67e74705SXin Li Diag(DtorLoc, diag::note_delete_non_virtual)
3060*67e74705SXin Li << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3061*67e74705SXin Li }
3062*67e74705SXin Li }
3063*67e74705SXin Li
ActOnConditionVariable(Decl * ConditionVar,SourceLocation StmtLoc,ConditionKind CK)3064*67e74705SXin Li Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3065*67e74705SXin Li SourceLocation StmtLoc,
3066*67e74705SXin Li ConditionKind CK) {
3067*67e74705SXin Li ExprResult E =
3068*67e74705SXin Li CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3069*67e74705SXin Li if (E.isInvalid())
3070*67e74705SXin Li return ConditionError();
3071*67e74705SXin Li return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3072*67e74705SXin Li CK == ConditionKind::ConstexprIf);
3073*67e74705SXin Li }
3074*67e74705SXin Li
3075*67e74705SXin Li /// \brief Check the use of the given variable as a C++ condition in an if,
3076*67e74705SXin Li /// while, do-while, or switch statement.
CheckConditionVariable(VarDecl * ConditionVar,SourceLocation StmtLoc,ConditionKind CK)3077*67e74705SXin Li ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
3078*67e74705SXin Li SourceLocation StmtLoc,
3079*67e74705SXin Li ConditionKind CK) {
3080*67e74705SXin Li if (ConditionVar->isInvalidDecl())
3081*67e74705SXin Li return ExprError();
3082*67e74705SXin Li
3083*67e74705SXin Li QualType T = ConditionVar->getType();
3084*67e74705SXin Li
3085*67e74705SXin Li // C++ [stmt.select]p2:
3086*67e74705SXin Li // The declarator shall not specify a function or an array.
3087*67e74705SXin Li if (T->isFunctionType())
3088*67e74705SXin Li return ExprError(Diag(ConditionVar->getLocation(),
3089*67e74705SXin Li diag::err_invalid_use_of_function_type)
3090*67e74705SXin Li << ConditionVar->getSourceRange());
3091*67e74705SXin Li else if (T->isArrayType())
3092*67e74705SXin Li return ExprError(Diag(ConditionVar->getLocation(),
3093*67e74705SXin Li diag::err_invalid_use_of_array_type)
3094*67e74705SXin Li << ConditionVar->getSourceRange());
3095*67e74705SXin Li
3096*67e74705SXin Li ExprResult Condition = DeclRefExpr::Create(
3097*67e74705SXin Li Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
3098*67e74705SXin Li /*enclosing*/ false, ConditionVar->getLocation(),
3099*67e74705SXin Li ConditionVar->getType().getNonReferenceType(), VK_LValue);
3100*67e74705SXin Li
3101*67e74705SXin Li MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
3102*67e74705SXin Li
3103*67e74705SXin Li switch (CK) {
3104*67e74705SXin Li case ConditionKind::Boolean:
3105*67e74705SXin Li return CheckBooleanCondition(StmtLoc, Condition.get());
3106*67e74705SXin Li
3107*67e74705SXin Li case ConditionKind::ConstexprIf:
3108*67e74705SXin Li return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3109*67e74705SXin Li
3110*67e74705SXin Li case ConditionKind::Switch:
3111*67e74705SXin Li return CheckSwitchCondition(StmtLoc, Condition.get());
3112*67e74705SXin Li }
3113*67e74705SXin Li
3114*67e74705SXin Li llvm_unreachable("unexpected condition kind");
3115*67e74705SXin Li }
3116*67e74705SXin Li
3117*67e74705SXin Li /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
CheckCXXBooleanCondition(Expr * CondExpr,bool IsConstexpr)3118*67e74705SXin Li ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
3119*67e74705SXin Li // C++ 6.4p4:
3120*67e74705SXin Li // The value of a condition that is an initialized declaration in a statement
3121*67e74705SXin Li // other than a switch statement is the value of the declared variable
3122*67e74705SXin Li // implicitly converted to type bool. If that conversion is ill-formed, the
3123*67e74705SXin Li // program is ill-formed.
3124*67e74705SXin Li // The value of a condition that is an expression is the value of the
3125*67e74705SXin Li // expression, implicitly converted to bool.
3126*67e74705SXin Li //
3127*67e74705SXin Li // FIXME: Return this value to the caller so they don't need to recompute it.
3128*67e74705SXin Li llvm::APSInt Value(/*BitWidth*/1);
3129*67e74705SXin Li return (IsConstexpr && !CondExpr->isValueDependent())
3130*67e74705SXin Li ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3131*67e74705SXin Li CCEK_ConstexprIf)
3132*67e74705SXin Li : PerformContextuallyConvertToBool(CondExpr);
3133*67e74705SXin Li }
3134*67e74705SXin Li
3135*67e74705SXin Li /// Helper function to determine whether this is the (deprecated) C++
3136*67e74705SXin Li /// conversion from a string literal to a pointer to non-const char or
3137*67e74705SXin Li /// non-const wchar_t (for narrow and wide string literals,
3138*67e74705SXin Li /// respectively).
3139*67e74705SXin Li bool
IsStringLiteralToNonConstPointerConversion(Expr * From,QualType ToType)3140*67e74705SXin Li Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3141*67e74705SXin Li // Look inside the implicit cast, if it exists.
3142*67e74705SXin Li if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3143*67e74705SXin Li From = Cast->getSubExpr();
3144*67e74705SXin Li
3145*67e74705SXin Li // A string literal (2.13.4) that is not a wide string literal can
3146*67e74705SXin Li // be converted to an rvalue of type "pointer to char"; a wide
3147*67e74705SXin Li // string literal can be converted to an rvalue of type "pointer
3148*67e74705SXin Li // to wchar_t" (C++ 4.2p2).
3149*67e74705SXin Li if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
3150*67e74705SXin Li if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
3151*67e74705SXin Li if (const BuiltinType *ToPointeeType
3152*67e74705SXin Li = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
3153*67e74705SXin Li // This conversion is considered only when there is an
3154*67e74705SXin Li // explicit appropriate pointer target type (C++ 4.2p2).
3155*67e74705SXin Li if (!ToPtrType->getPointeeType().hasQualifiers()) {
3156*67e74705SXin Li switch (StrLit->getKind()) {
3157*67e74705SXin Li case StringLiteral::UTF8:
3158*67e74705SXin Li case StringLiteral::UTF16:
3159*67e74705SXin Li case StringLiteral::UTF32:
3160*67e74705SXin Li // We don't allow UTF literals to be implicitly converted
3161*67e74705SXin Li break;
3162*67e74705SXin Li case StringLiteral::Ascii:
3163*67e74705SXin Li return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3164*67e74705SXin Li ToPointeeType->getKind() == BuiltinType::Char_S);
3165*67e74705SXin Li case StringLiteral::Wide:
3166*67e74705SXin Li return Context.typesAreCompatible(Context.getWideCharType(),
3167*67e74705SXin Li QualType(ToPointeeType, 0));
3168*67e74705SXin Li }
3169*67e74705SXin Li }
3170*67e74705SXin Li }
3171*67e74705SXin Li
3172*67e74705SXin Li return false;
3173*67e74705SXin Li }
3174*67e74705SXin Li
BuildCXXCastArgument(Sema & S,SourceLocation CastLoc,QualType Ty,CastKind Kind,CXXMethodDecl * Method,DeclAccessPair FoundDecl,bool HadMultipleCandidates,Expr * From)3175*67e74705SXin Li static ExprResult BuildCXXCastArgument(Sema &S,
3176*67e74705SXin Li SourceLocation CastLoc,
3177*67e74705SXin Li QualType Ty,
3178*67e74705SXin Li CastKind Kind,
3179*67e74705SXin Li CXXMethodDecl *Method,
3180*67e74705SXin Li DeclAccessPair FoundDecl,
3181*67e74705SXin Li bool HadMultipleCandidates,
3182*67e74705SXin Li Expr *From) {
3183*67e74705SXin Li switch (Kind) {
3184*67e74705SXin Li default: llvm_unreachable("Unhandled cast kind!");
3185*67e74705SXin Li case CK_ConstructorConversion: {
3186*67e74705SXin Li CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
3187*67e74705SXin Li SmallVector<Expr*, 8> ConstructorArgs;
3188*67e74705SXin Li
3189*67e74705SXin Li if (S.RequireNonAbstractType(CastLoc, Ty,
3190*67e74705SXin Li diag::err_allocation_of_abstract_type))
3191*67e74705SXin Li return ExprError();
3192*67e74705SXin Li
3193*67e74705SXin Li if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
3194*67e74705SXin Li return ExprError();
3195*67e74705SXin Li
3196*67e74705SXin Li S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3197*67e74705SXin Li InitializedEntity::InitializeTemporary(Ty));
3198*67e74705SXin Li if (S.DiagnoseUseOfDecl(Method, CastLoc))
3199*67e74705SXin Li return ExprError();
3200*67e74705SXin Li
3201*67e74705SXin Li ExprResult Result = S.BuildCXXConstructExpr(
3202*67e74705SXin Li CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
3203*67e74705SXin Li ConstructorArgs, HadMultipleCandidates,
3204*67e74705SXin Li /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3205*67e74705SXin Li CXXConstructExpr::CK_Complete, SourceRange());
3206*67e74705SXin Li if (Result.isInvalid())
3207*67e74705SXin Li return ExprError();
3208*67e74705SXin Li
3209*67e74705SXin Li return S.MaybeBindToTemporary(Result.getAs<Expr>());
3210*67e74705SXin Li }
3211*67e74705SXin Li
3212*67e74705SXin Li case CK_UserDefinedConversion: {
3213*67e74705SXin Li assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
3214*67e74705SXin Li
3215*67e74705SXin Li S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
3216*67e74705SXin Li if (S.DiagnoseUseOfDecl(Method, CastLoc))
3217*67e74705SXin Li return ExprError();
3218*67e74705SXin Li
3219*67e74705SXin Li // Create an implicit call expr that calls it.
3220*67e74705SXin Li CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3221*67e74705SXin Li ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
3222*67e74705SXin Li HadMultipleCandidates);
3223*67e74705SXin Li if (Result.isInvalid())
3224*67e74705SXin Li return ExprError();
3225*67e74705SXin Li // Record usage of conversion in an implicit cast.
3226*67e74705SXin Li Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3227*67e74705SXin Li CK_UserDefinedConversion, Result.get(),
3228*67e74705SXin Li nullptr, Result.get()->getValueKind());
3229*67e74705SXin Li
3230*67e74705SXin Li return S.MaybeBindToTemporary(Result.get());
3231*67e74705SXin Li }
3232*67e74705SXin Li }
3233*67e74705SXin Li }
3234*67e74705SXin Li
3235*67e74705SXin Li /// PerformImplicitConversion - Perform an implicit conversion of the
3236*67e74705SXin Li /// expression From to the type ToType using the pre-computed implicit
3237*67e74705SXin Li /// conversion sequence ICS. Returns the converted
3238*67e74705SXin Li /// expression. Action is the kind of conversion we're performing,
3239*67e74705SXin Li /// used in the error message.
3240*67e74705SXin Li ExprResult
PerformImplicitConversion(Expr * From,QualType ToType,const ImplicitConversionSequence & ICS,AssignmentAction Action,CheckedConversionKind CCK)3241*67e74705SXin Li Sema::PerformImplicitConversion(Expr *From, QualType ToType,
3242*67e74705SXin Li const ImplicitConversionSequence &ICS,
3243*67e74705SXin Li AssignmentAction Action,
3244*67e74705SXin Li CheckedConversionKind CCK) {
3245*67e74705SXin Li switch (ICS.getKind()) {
3246*67e74705SXin Li case ImplicitConversionSequence::StandardConversion: {
3247*67e74705SXin Li ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3248*67e74705SXin Li Action, CCK);
3249*67e74705SXin Li if (Res.isInvalid())
3250*67e74705SXin Li return ExprError();
3251*67e74705SXin Li From = Res.get();
3252*67e74705SXin Li break;
3253*67e74705SXin Li }
3254*67e74705SXin Li
3255*67e74705SXin Li case ImplicitConversionSequence::UserDefinedConversion: {
3256*67e74705SXin Li
3257*67e74705SXin Li FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
3258*67e74705SXin Li CastKind CastKind;
3259*67e74705SXin Li QualType BeforeToType;
3260*67e74705SXin Li assert(FD && "no conversion function for user-defined conversion seq");
3261*67e74705SXin Li if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
3262*67e74705SXin Li CastKind = CK_UserDefinedConversion;
3263*67e74705SXin Li
3264*67e74705SXin Li // If the user-defined conversion is specified by a conversion function,
3265*67e74705SXin Li // the initial standard conversion sequence converts the source type to
3266*67e74705SXin Li // the implicit object parameter of the conversion function.
3267*67e74705SXin Li BeforeToType = Context.getTagDeclType(Conv->getParent());
3268*67e74705SXin Li } else {
3269*67e74705SXin Li const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
3270*67e74705SXin Li CastKind = CK_ConstructorConversion;
3271*67e74705SXin Li // Do no conversion if dealing with ... for the first conversion.
3272*67e74705SXin Li if (!ICS.UserDefined.EllipsisConversion) {
3273*67e74705SXin Li // If the user-defined conversion is specified by a constructor, the
3274*67e74705SXin Li // initial standard conversion sequence converts the source type to
3275*67e74705SXin Li // the type required by the argument of the constructor
3276*67e74705SXin Li BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3277*67e74705SXin Li }
3278*67e74705SXin Li }
3279*67e74705SXin Li // Watch out for ellipsis conversion.
3280*67e74705SXin Li if (!ICS.UserDefined.EllipsisConversion) {
3281*67e74705SXin Li ExprResult Res =
3282*67e74705SXin Li PerformImplicitConversion(From, BeforeToType,
3283*67e74705SXin Li ICS.UserDefined.Before, AA_Converting,
3284*67e74705SXin Li CCK);
3285*67e74705SXin Li if (Res.isInvalid())
3286*67e74705SXin Li return ExprError();
3287*67e74705SXin Li From = Res.get();
3288*67e74705SXin Li }
3289*67e74705SXin Li
3290*67e74705SXin Li ExprResult CastArg
3291*67e74705SXin Li = BuildCXXCastArgument(*this,
3292*67e74705SXin Li From->getLocStart(),
3293*67e74705SXin Li ToType.getNonReferenceType(),
3294*67e74705SXin Li CastKind, cast<CXXMethodDecl>(FD),
3295*67e74705SXin Li ICS.UserDefined.FoundConversionFunction,
3296*67e74705SXin Li ICS.UserDefined.HadMultipleCandidates,
3297*67e74705SXin Li From);
3298*67e74705SXin Li
3299*67e74705SXin Li if (CastArg.isInvalid())
3300*67e74705SXin Li return ExprError();
3301*67e74705SXin Li
3302*67e74705SXin Li From = CastArg.get();
3303*67e74705SXin Li
3304*67e74705SXin Li return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3305*67e74705SXin Li AA_Converting, CCK);
3306*67e74705SXin Li }
3307*67e74705SXin Li
3308*67e74705SXin Li case ImplicitConversionSequence::AmbiguousConversion:
3309*67e74705SXin Li ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
3310*67e74705SXin Li PDiag(diag::err_typecheck_ambiguous_condition)
3311*67e74705SXin Li << From->getSourceRange());
3312*67e74705SXin Li return ExprError();
3313*67e74705SXin Li
3314*67e74705SXin Li case ImplicitConversionSequence::EllipsisConversion:
3315*67e74705SXin Li llvm_unreachable("Cannot perform an ellipsis conversion");
3316*67e74705SXin Li
3317*67e74705SXin Li case ImplicitConversionSequence::BadConversion:
3318*67e74705SXin Li return ExprError();
3319*67e74705SXin Li }
3320*67e74705SXin Li
3321*67e74705SXin Li // Everything went well.
3322*67e74705SXin Li return From;
3323*67e74705SXin Li }
3324*67e74705SXin Li
3325*67e74705SXin Li /// PerformImplicitConversion - Perform an implicit conversion of the
3326*67e74705SXin Li /// expression From to the type ToType by following the standard
3327*67e74705SXin Li /// conversion sequence SCS. Returns the converted
3328*67e74705SXin Li /// expression. Flavor is the context in which we're performing this
3329*67e74705SXin Li /// conversion, for use in error messages.
3330*67e74705SXin Li ExprResult
PerformImplicitConversion(Expr * From,QualType ToType,const StandardConversionSequence & SCS,AssignmentAction Action,CheckedConversionKind CCK)3331*67e74705SXin Li Sema::PerformImplicitConversion(Expr *From, QualType ToType,
3332*67e74705SXin Li const StandardConversionSequence& SCS,
3333*67e74705SXin Li AssignmentAction Action,
3334*67e74705SXin Li CheckedConversionKind CCK) {
3335*67e74705SXin Li bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
3336*67e74705SXin Li
3337*67e74705SXin Li // Overall FIXME: we are recomputing too many types here and doing far too
3338*67e74705SXin Li // much extra work. What this means is that we need to keep track of more
3339*67e74705SXin Li // information that is computed when we try the implicit conversion initially,
3340*67e74705SXin Li // so that we don't need to recompute anything here.
3341*67e74705SXin Li QualType FromType = From->getType();
3342*67e74705SXin Li
3343*67e74705SXin Li if (SCS.CopyConstructor) {
3344*67e74705SXin Li // FIXME: When can ToType be a reference type?
3345*67e74705SXin Li assert(!ToType->isReferenceType());
3346*67e74705SXin Li if (SCS.Second == ICK_Derived_To_Base) {
3347*67e74705SXin Li SmallVector<Expr*, 8> ConstructorArgs;
3348*67e74705SXin Li if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
3349*67e74705SXin Li From, /*FIXME:ConstructLoc*/SourceLocation(),
3350*67e74705SXin Li ConstructorArgs))
3351*67e74705SXin Li return ExprError();
3352*67e74705SXin Li return BuildCXXConstructExpr(
3353*67e74705SXin Li /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3354*67e74705SXin Li SCS.FoundCopyConstructor, SCS.CopyConstructor,
3355*67e74705SXin Li ConstructorArgs, /*HadMultipleCandidates*/ false,
3356*67e74705SXin Li /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3357*67e74705SXin Li CXXConstructExpr::CK_Complete, SourceRange());
3358*67e74705SXin Li }
3359*67e74705SXin Li return BuildCXXConstructExpr(
3360*67e74705SXin Li /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3361*67e74705SXin Li SCS.FoundCopyConstructor, SCS.CopyConstructor,
3362*67e74705SXin Li From, /*HadMultipleCandidates*/ false,
3363*67e74705SXin Li /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3364*67e74705SXin Li CXXConstructExpr::CK_Complete, SourceRange());
3365*67e74705SXin Li }
3366*67e74705SXin Li
3367*67e74705SXin Li // Resolve overloaded function references.
3368*67e74705SXin Li if (Context.hasSameType(FromType, Context.OverloadTy)) {
3369*67e74705SXin Li DeclAccessPair Found;
3370*67e74705SXin Li FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
3371*67e74705SXin Li true, Found);
3372*67e74705SXin Li if (!Fn)
3373*67e74705SXin Li return ExprError();
3374*67e74705SXin Li
3375*67e74705SXin Li if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
3376*67e74705SXin Li return ExprError();
3377*67e74705SXin Li
3378*67e74705SXin Li From = FixOverloadedFunctionReference(From, Found, Fn);
3379*67e74705SXin Li FromType = From->getType();
3380*67e74705SXin Li }
3381*67e74705SXin Li
3382*67e74705SXin Li // If we're converting to an atomic type, first convert to the corresponding
3383*67e74705SXin Li // non-atomic type.
3384*67e74705SXin Li QualType ToAtomicType;
3385*67e74705SXin Li if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3386*67e74705SXin Li ToAtomicType = ToType;
3387*67e74705SXin Li ToType = ToAtomic->getValueType();
3388*67e74705SXin Li }
3389*67e74705SXin Li
3390*67e74705SXin Li QualType InitialFromType = FromType;
3391*67e74705SXin Li // Perform the first implicit conversion.
3392*67e74705SXin Li switch (SCS.First) {
3393*67e74705SXin Li case ICK_Identity:
3394*67e74705SXin Li if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3395*67e74705SXin Li FromType = FromAtomic->getValueType().getUnqualifiedType();
3396*67e74705SXin Li From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3397*67e74705SXin Li From, /*BasePath=*/nullptr, VK_RValue);
3398*67e74705SXin Li }
3399*67e74705SXin Li break;
3400*67e74705SXin Li
3401*67e74705SXin Li case ICK_Lvalue_To_Rvalue: {
3402*67e74705SXin Li assert(From->getObjectKind() != OK_ObjCProperty);
3403*67e74705SXin Li ExprResult FromRes = DefaultLvalueConversion(From);
3404*67e74705SXin Li assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
3405*67e74705SXin Li From = FromRes.get();
3406*67e74705SXin Li FromType = From->getType();
3407*67e74705SXin Li break;
3408*67e74705SXin Li }
3409*67e74705SXin Li
3410*67e74705SXin Li case ICK_Array_To_Pointer:
3411*67e74705SXin Li FromType = Context.getArrayDecayedType(FromType);
3412*67e74705SXin Li From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
3413*67e74705SXin Li VK_RValue, /*BasePath=*/nullptr, CCK).get();
3414*67e74705SXin Li break;
3415*67e74705SXin Li
3416*67e74705SXin Li case ICK_Function_To_Pointer:
3417*67e74705SXin Li FromType = Context.getPointerType(FromType);
3418*67e74705SXin Li From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
3419*67e74705SXin Li VK_RValue, /*BasePath=*/nullptr, CCK).get();
3420*67e74705SXin Li break;
3421*67e74705SXin Li
3422*67e74705SXin Li default:
3423*67e74705SXin Li llvm_unreachable("Improper first standard conversion");
3424*67e74705SXin Li }
3425*67e74705SXin Li
3426*67e74705SXin Li // Perform the second implicit conversion
3427*67e74705SXin Li switch (SCS.Second) {
3428*67e74705SXin Li case ICK_Identity:
3429*67e74705SXin Li // C++ [except.spec]p5:
3430*67e74705SXin Li // [For] assignment to and initialization of pointers to functions,
3431*67e74705SXin Li // pointers to member functions, and references to functions: the
3432*67e74705SXin Li // target entity shall allow at least the exceptions allowed by the
3433*67e74705SXin Li // source value in the assignment or initialization.
3434*67e74705SXin Li switch (Action) {
3435*67e74705SXin Li case AA_Assigning:
3436*67e74705SXin Li case AA_Initializing:
3437*67e74705SXin Li // Note, function argument passing and returning are initialization.
3438*67e74705SXin Li case AA_Passing:
3439*67e74705SXin Li case AA_Returning:
3440*67e74705SXin Li case AA_Sending:
3441*67e74705SXin Li case AA_Passing_CFAudited:
3442*67e74705SXin Li if (CheckExceptionSpecCompatibility(From, ToType))
3443*67e74705SXin Li return ExprError();
3444*67e74705SXin Li break;
3445*67e74705SXin Li
3446*67e74705SXin Li case AA_Casting:
3447*67e74705SXin Li case AA_Converting:
3448*67e74705SXin Li // Casts and implicit conversions are not initialization, so are not
3449*67e74705SXin Li // checked for exception specification mismatches.
3450*67e74705SXin Li break;
3451*67e74705SXin Li }
3452*67e74705SXin Li // Nothing else to do.
3453*67e74705SXin Li break;
3454*67e74705SXin Li
3455*67e74705SXin Li case ICK_NoReturn_Adjustment:
3456*67e74705SXin Li // If both sides are functions (or pointers/references to them), there could
3457*67e74705SXin Li // be incompatible exception declarations.
3458*67e74705SXin Li if (CheckExceptionSpecCompatibility(From, ToType))
3459*67e74705SXin Li return ExprError();
3460*67e74705SXin Li
3461*67e74705SXin Li From = ImpCastExprToType(From, ToType, CK_NoOp,
3462*67e74705SXin Li VK_RValue, /*BasePath=*/nullptr, CCK).get();
3463*67e74705SXin Li break;
3464*67e74705SXin Li
3465*67e74705SXin Li case ICK_Integral_Promotion:
3466*67e74705SXin Li case ICK_Integral_Conversion:
3467*67e74705SXin Li if (ToType->isBooleanType()) {
3468*67e74705SXin Li assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
3469*67e74705SXin Li SCS.Second == ICK_Integral_Promotion &&
3470*67e74705SXin Li "only enums with fixed underlying type can promote to bool");
3471*67e74705SXin Li From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
3472*67e74705SXin Li VK_RValue, /*BasePath=*/nullptr, CCK).get();
3473*67e74705SXin Li } else {
3474*67e74705SXin Li From = ImpCastExprToType(From, ToType, CK_IntegralCast,
3475*67e74705SXin Li VK_RValue, /*BasePath=*/nullptr, CCK).get();
3476*67e74705SXin Li }
3477*67e74705SXin Li break;
3478*67e74705SXin Li
3479*67e74705SXin Li case ICK_Floating_Promotion:
3480*67e74705SXin Li case ICK_Floating_Conversion:
3481*67e74705SXin Li From = ImpCastExprToType(From, ToType, CK_FloatingCast,
3482*67e74705SXin Li VK_RValue, /*BasePath=*/nullptr, CCK).get();
3483*67e74705SXin Li break;
3484*67e74705SXin Li
3485*67e74705SXin Li case ICK_Complex_Promotion:
3486*67e74705SXin Li case ICK_Complex_Conversion: {
3487*67e74705SXin Li QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
3488*67e74705SXin Li QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
3489*67e74705SXin Li CastKind CK;
3490*67e74705SXin Li if (FromEl->isRealFloatingType()) {
3491*67e74705SXin Li if (ToEl->isRealFloatingType())
3492*67e74705SXin Li CK = CK_FloatingComplexCast;
3493*67e74705SXin Li else
3494*67e74705SXin Li CK = CK_FloatingComplexToIntegralComplex;
3495*67e74705SXin Li } else if (ToEl->isRealFloatingType()) {
3496*67e74705SXin Li CK = CK_IntegralComplexToFloatingComplex;
3497*67e74705SXin Li } else {
3498*67e74705SXin Li CK = CK_IntegralComplexCast;
3499*67e74705SXin Li }
3500*67e74705SXin Li From = ImpCastExprToType(From, ToType, CK,
3501*67e74705SXin Li VK_RValue, /*BasePath=*/nullptr, CCK).get();
3502*67e74705SXin Li break;
3503*67e74705SXin Li }
3504*67e74705SXin Li
3505*67e74705SXin Li case ICK_Floating_Integral:
3506*67e74705SXin Li if (ToType->isRealFloatingType())
3507*67e74705SXin Li From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
3508*67e74705SXin Li VK_RValue, /*BasePath=*/nullptr, CCK).get();
3509*67e74705SXin Li else
3510*67e74705SXin Li From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
3511*67e74705SXin Li VK_RValue, /*BasePath=*/nullptr, CCK).get();
3512*67e74705SXin Li break;
3513*67e74705SXin Li
3514*67e74705SXin Li case ICK_Compatible_Conversion:
3515*67e74705SXin Li From = ImpCastExprToType(From, ToType, CK_NoOp,
3516*67e74705SXin Li VK_RValue, /*BasePath=*/nullptr, CCK).get();
3517*67e74705SXin Li break;
3518*67e74705SXin Li
3519*67e74705SXin Li case ICK_Writeback_Conversion:
3520*67e74705SXin Li case ICK_Pointer_Conversion: {
3521*67e74705SXin Li if (SCS.IncompatibleObjC && Action != AA_Casting) {
3522*67e74705SXin Li // Diagnose incompatible Objective-C conversions
3523*67e74705SXin Li if (Action == AA_Initializing || Action == AA_Assigning)
3524*67e74705SXin Li Diag(From->getLocStart(),
3525*67e74705SXin Li diag::ext_typecheck_convert_incompatible_pointer)
3526*67e74705SXin Li << ToType << From->getType() << Action
3527*67e74705SXin Li << From->getSourceRange() << 0;
3528*67e74705SXin Li else
3529*67e74705SXin Li Diag(From->getLocStart(),
3530*67e74705SXin Li diag::ext_typecheck_convert_incompatible_pointer)
3531*67e74705SXin Li << From->getType() << ToType << Action
3532*67e74705SXin Li << From->getSourceRange() << 0;
3533*67e74705SXin Li
3534*67e74705SXin Li if (From->getType()->isObjCObjectPointerType() &&
3535*67e74705SXin Li ToType->isObjCObjectPointerType())
3536*67e74705SXin Li EmitRelatedResultTypeNote(From);
3537*67e74705SXin Li }
3538*67e74705SXin Li else if (getLangOpts().ObjCAutoRefCount &&
3539*67e74705SXin Li !CheckObjCARCUnavailableWeakConversion(ToType,
3540*67e74705SXin Li From->getType())) {
3541*67e74705SXin Li if (Action == AA_Initializing)
3542*67e74705SXin Li Diag(From->getLocStart(),
3543*67e74705SXin Li diag::err_arc_weak_unavailable_assign);
3544*67e74705SXin Li else
3545*67e74705SXin Li Diag(From->getLocStart(),
3546*67e74705SXin Li diag::err_arc_convesion_of_weak_unavailable)
3547*67e74705SXin Li << (Action == AA_Casting) << From->getType() << ToType
3548*67e74705SXin Li << From->getSourceRange();
3549*67e74705SXin Li }
3550*67e74705SXin Li
3551*67e74705SXin Li CastKind Kind = CK_Invalid;
3552*67e74705SXin Li CXXCastPath BasePath;
3553*67e74705SXin Li if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
3554*67e74705SXin Li return ExprError();
3555*67e74705SXin Li
3556*67e74705SXin Li // Make sure we extend blocks if necessary.
3557*67e74705SXin Li // FIXME: doing this here is really ugly.
3558*67e74705SXin Li if (Kind == CK_BlockPointerToObjCPointerCast) {
3559*67e74705SXin Li ExprResult E = From;
3560*67e74705SXin Li (void) PrepareCastToObjCObjectPointer(E);
3561*67e74705SXin Li From = E.get();
3562*67e74705SXin Li }
3563*67e74705SXin Li if (getLangOpts().ObjCAutoRefCount)
3564*67e74705SXin Li CheckObjCARCConversion(SourceRange(), ToType, From, CCK);
3565*67e74705SXin Li From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
3566*67e74705SXin Li .get();
3567*67e74705SXin Li break;
3568*67e74705SXin Li }
3569*67e74705SXin Li
3570*67e74705SXin Li case ICK_Pointer_Member: {
3571*67e74705SXin Li CastKind Kind = CK_Invalid;
3572*67e74705SXin Li CXXCastPath BasePath;
3573*67e74705SXin Li if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
3574*67e74705SXin Li return ExprError();
3575*67e74705SXin Li if (CheckExceptionSpecCompatibility(From, ToType))
3576*67e74705SXin Li return ExprError();
3577*67e74705SXin Li
3578*67e74705SXin Li // We may not have been able to figure out what this member pointer resolved
3579*67e74705SXin Li // to up until this exact point. Attempt to lock-in it's inheritance model.
3580*67e74705SXin Li if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3581*67e74705SXin Li (void)isCompleteType(From->getExprLoc(), From->getType());
3582*67e74705SXin Li (void)isCompleteType(From->getExprLoc(), ToType);
3583*67e74705SXin Li }
3584*67e74705SXin Li
3585*67e74705SXin Li From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
3586*67e74705SXin Li .get();
3587*67e74705SXin Li break;
3588*67e74705SXin Li }
3589*67e74705SXin Li
3590*67e74705SXin Li case ICK_Boolean_Conversion:
3591*67e74705SXin Li // Perform half-to-boolean conversion via float.
3592*67e74705SXin Li if (From->getType()->isHalfType()) {
3593*67e74705SXin Li From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
3594*67e74705SXin Li FromType = Context.FloatTy;
3595*67e74705SXin Li }
3596*67e74705SXin Li
3597*67e74705SXin Li From = ImpCastExprToType(From, Context.BoolTy,
3598*67e74705SXin Li ScalarTypeToBooleanCastKind(FromType),
3599*67e74705SXin Li VK_RValue, /*BasePath=*/nullptr, CCK).get();
3600*67e74705SXin Li break;
3601*67e74705SXin Li
3602*67e74705SXin Li case ICK_Derived_To_Base: {
3603*67e74705SXin Li CXXCastPath BasePath;
3604*67e74705SXin Li if (CheckDerivedToBaseConversion(From->getType(),
3605*67e74705SXin Li ToType.getNonReferenceType(),
3606*67e74705SXin Li From->getLocStart(),
3607*67e74705SXin Li From->getSourceRange(),
3608*67e74705SXin Li &BasePath,
3609*67e74705SXin Li CStyle))
3610*67e74705SXin Li return ExprError();
3611*67e74705SXin Li
3612*67e74705SXin Li From = ImpCastExprToType(From, ToType.getNonReferenceType(),
3613*67e74705SXin Li CK_DerivedToBase, From->getValueKind(),
3614*67e74705SXin Li &BasePath, CCK).get();
3615*67e74705SXin Li break;
3616*67e74705SXin Li }
3617*67e74705SXin Li
3618*67e74705SXin Li case ICK_Vector_Conversion:
3619*67e74705SXin Li From = ImpCastExprToType(From, ToType, CK_BitCast,
3620*67e74705SXin Li VK_RValue, /*BasePath=*/nullptr, CCK).get();
3621*67e74705SXin Li break;
3622*67e74705SXin Li
3623*67e74705SXin Li case ICK_Vector_Splat: {
3624*67e74705SXin Li // Vector splat from any arithmetic type to a vector.
3625*67e74705SXin Li Expr *Elem = prepareVectorSplat(ToType, From).get();
3626*67e74705SXin Li From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
3627*67e74705SXin Li /*BasePath=*/nullptr, CCK).get();
3628*67e74705SXin Li break;
3629*67e74705SXin Li }
3630*67e74705SXin Li
3631*67e74705SXin Li case ICK_Complex_Real:
3632*67e74705SXin Li // Case 1. x -> _Complex y
3633*67e74705SXin Li if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
3634*67e74705SXin Li QualType ElType = ToComplex->getElementType();
3635*67e74705SXin Li bool isFloatingComplex = ElType->isRealFloatingType();
3636*67e74705SXin Li
3637*67e74705SXin Li // x -> y
3638*67e74705SXin Li if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
3639*67e74705SXin Li // do nothing
3640*67e74705SXin Li } else if (From->getType()->isRealFloatingType()) {
3641*67e74705SXin Li From = ImpCastExprToType(From, ElType,
3642*67e74705SXin Li isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
3643*67e74705SXin Li } else {
3644*67e74705SXin Li assert(From->getType()->isIntegerType());
3645*67e74705SXin Li From = ImpCastExprToType(From, ElType,
3646*67e74705SXin Li isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
3647*67e74705SXin Li }
3648*67e74705SXin Li // y -> _Complex y
3649*67e74705SXin Li From = ImpCastExprToType(From, ToType,
3650*67e74705SXin Li isFloatingComplex ? CK_FloatingRealToComplex
3651*67e74705SXin Li : CK_IntegralRealToComplex).get();
3652*67e74705SXin Li
3653*67e74705SXin Li // Case 2. _Complex x -> y
3654*67e74705SXin Li } else {
3655*67e74705SXin Li const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
3656*67e74705SXin Li assert(FromComplex);
3657*67e74705SXin Li
3658*67e74705SXin Li QualType ElType = FromComplex->getElementType();
3659*67e74705SXin Li bool isFloatingComplex = ElType->isRealFloatingType();
3660*67e74705SXin Li
3661*67e74705SXin Li // _Complex x -> x
3662*67e74705SXin Li From = ImpCastExprToType(From, ElType,
3663*67e74705SXin Li isFloatingComplex ? CK_FloatingComplexToReal
3664*67e74705SXin Li : CK_IntegralComplexToReal,
3665*67e74705SXin Li VK_RValue, /*BasePath=*/nullptr, CCK).get();
3666*67e74705SXin Li
3667*67e74705SXin Li // x -> y
3668*67e74705SXin Li if (Context.hasSameUnqualifiedType(ElType, ToType)) {
3669*67e74705SXin Li // do nothing
3670*67e74705SXin Li } else if (ToType->isRealFloatingType()) {
3671*67e74705SXin Li From = ImpCastExprToType(From, ToType,
3672*67e74705SXin Li isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
3673*67e74705SXin Li VK_RValue, /*BasePath=*/nullptr, CCK).get();
3674*67e74705SXin Li } else {
3675*67e74705SXin Li assert(ToType->isIntegerType());
3676*67e74705SXin Li From = ImpCastExprToType(From, ToType,
3677*67e74705SXin Li isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
3678*67e74705SXin Li VK_RValue, /*BasePath=*/nullptr, CCK).get();
3679*67e74705SXin Li }
3680*67e74705SXin Li }
3681*67e74705SXin Li break;
3682*67e74705SXin Li
3683*67e74705SXin Li case ICK_Block_Pointer_Conversion: {
3684*67e74705SXin Li From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
3685*67e74705SXin Li VK_RValue, /*BasePath=*/nullptr, CCK).get();
3686*67e74705SXin Li break;
3687*67e74705SXin Li }
3688*67e74705SXin Li
3689*67e74705SXin Li case ICK_TransparentUnionConversion: {
3690*67e74705SXin Li ExprResult FromRes = From;
3691*67e74705SXin Li Sema::AssignConvertType ConvTy =
3692*67e74705SXin Li CheckTransparentUnionArgumentConstraints(ToType, FromRes);
3693*67e74705SXin Li if (FromRes.isInvalid())
3694*67e74705SXin Li return ExprError();
3695*67e74705SXin Li From = FromRes.get();
3696*67e74705SXin Li assert ((ConvTy == Sema::Compatible) &&
3697*67e74705SXin Li "Improper transparent union conversion");
3698*67e74705SXin Li (void)ConvTy;
3699*67e74705SXin Li break;
3700*67e74705SXin Li }
3701*67e74705SXin Li
3702*67e74705SXin Li case ICK_Zero_Event_Conversion:
3703*67e74705SXin Li From = ImpCastExprToType(From, ToType,
3704*67e74705SXin Li CK_ZeroToOCLEvent,
3705*67e74705SXin Li From->getValueKind()).get();
3706*67e74705SXin Li break;
3707*67e74705SXin Li
3708*67e74705SXin Li case ICK_Lvalue_To_Rvalue:
3709*67e74705SXin Li case ICK_Array_To_Pointer:
3710*67e74705SXin Li case ICK_Function_To_Pointer:
3711*67e74705SXin Li case ICK_Qualification:
3712*67e74705SXin Li case ICK_Num_Conversion_Kinds:
3713*67e74705SXin Li case ICK_C_Only_Conversion:
3714*67e74705SXin Li llvm_unreachable("Improper second standard conversion");
3715*67e74705SXin Li }
3716*67e74705SXin Li
3717*67e74705SXin Li switch (SCS.Third) {
3718*67e74705SXin Li case ICK_Identity:
3719*67e74705SXin Li // Nothing to do.
3720*67e74705SXin Li break;
3721*67e74705SXin Li
3722*67e74705SXin Li case ICK_Qualification: {
3723*67e74705SXin Li // The qualification keeps the category of the inner expression, unless the
3724*67e74705SXin Li // target type isn't a reference.
3725*67e74705SXin Li ExprValueKind VK = ToType->isReferenceType() ?
3726*67e74705SXin Li From->getValueKind() : VK_RValue;
3727*67e74705SXin Li From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
3728*67e74705SXin Li CK_NoOp, VK, /*BasePath=*/nullptr, CCK).get();
3729*67e74705SXin Li
3730*67e74705SXin Li if (SCS.DeprecatedStringLiteralToCharPtr &&
3731*67e74705SXin Li !getLangOpts().WritableStrings) {
3732*67e74705SXin Li Diag(From->getLocStart(), getLangOpts().CPlusPlus11
3733*67e74705SXin Li ? diag::ext_deprecated_string_literal_conversion
3734*67e74705SXin Li : diag::warn_deprecated_string_literal_conversion)
3735*67e74705SXin Li << ToType.getNonReferenceType();
3736*67e74705SXin Li }
3737*67e74705SXin Li
3738*67e74705SXin Li break;
3739*67e74705SXin Li }
3740*67e74705SXin Li
3741*67e74705SXin Li default:
3742*67e74705SXin Li llvm_unreachable("Improper third standard conversion");
3743*67e74705SXin Li }
3744*67e74705SXin Li
3745*67e74705SXin Li // If this conversion sequence involved a scalar -> atomic conversion, perform
3746*67e74705SXin Li // that conversion now.
3747*67e74705SXin Li if (!ToAtomicType.isNull()) {
3748*67e74705SXin Li assert(Context.hasSameType(
3749*67e74705SXin Li ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
3750*67e74705SXin Li From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
3751*67e74705SXin Li VK_RValue, nullptr, CCK).get();
3752*67e74705SXin Li }
3753*67e74705SXin Li
3754*67e74705SXin Li // If this conversion sequence succeeded and involved implicitly converting a
3755*67e74705SXin Li // _Nullable type to a _Nonnull one, complain.
3756*67e74705SXin Li if (CCK == CCK_ImplicitConversion)
3757*67e74705SXin Li diagnoseNullableToNonnullConversion(ToType, InitialFromType,
3758*67e74705SXin Li From->getLocStart());
3759*67e74705SXin Li
3760*67e74705SXin Li return From;
3761*67e74705SXin Li }
3762*67e74705SXin Li
3763*67e74705SXin Li /// \brief Check the completeness of a type in a unary type trait.
3764*67e74705SXin Li ///
3765*67e74705SXin Li /// If the particular type trait requires a complete type, tries to complete
3766*67e74705SXin Li /// it. If completing the type fails, a diagnostic is emitted and false
3767*67e74705SXin Li /// returned. If completing the type succeeds or no completion was required,
3768*67e74705SXin Li /// returns true.
CheckUnaryTypeTraitTypeCompleteness(Sema & S,TypeTrait UTT,SourceLocation Loc,QualType ArgTy)3769*67e74705SXin Li static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
3770*67e74705SXin Li SourceLocation Loc,
3771*67e74705SXin Li QualType ArgTy) {
3772*67e74705SXin Li // C++0x [meta.unary.prop]p3:
3773*67e74705SXin Li // For all of the class templates X declared in this Clause, instantiating
3774*67e74705SXin Li // that template with a template argument that is a class template
3775*67e74705SXin Li // specialization may result in the implicit instantiation of the template
3776*67e74705SXin Li // argument if and only if the semantics of X require that the argument
3777*67e74705SXin Li // must be a complete type.
3778*67e74705SXin Li // We apply this rule to all the type trait expressions used to implement
3779*67e74705SXin Li // these class templates. We also try to follow any GCC documented behavior
3780*67e74705SXin Li // in these expressions to ensure portability of standard libraries.
3781*67e74705SXin Li switch (UTT) {
3782*67e74705SXin Li default: llvm_unreachable("not a UTT");
3783*67e74705SXin Li // is_complete_type somewhat obviously cannot require a complete type.
3784*67e74705SXin Li case UTT_IsCompleteType:
3785*67e74705SXin Li // Fall-through
3786*67e74705SXin Li
3787*67e74705SXin Li // These traits are modeled on the type predicates in C++0x
3788*67e74705SXin Li // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
3789*67e74705SXin Li // requiring a complete type, as whether or not they return true cannot be
3790*67e74705SXin Li // impacted by the completeness of the type.
3791*67e74705SXin Li case UTT_IsVoid:
3792*67e74705SXin Li case UTT_IsIntegral:
3793*67e74705SXin Li case UTT_IsFloatingPoint:
3794*67e74705SXin Li case UTT_IsArray:
3795*67e74705SXin Li case UTT_IsPointer:
3796*67e74705SXin Li case UTT_IsLvalueReference:
3797*67e74705SXin Li case UTT_IsRvalueReference:
3798*67e74705SXin Li case UTT_IsMemberFunctionPointer:
3799*67e74705SXin Li case UTT_IsMemberObjectPointer:
3800*67e74705SXin Li case UTT_IsEnum:
3801*67e74705SXin Li case UTT_IsUnion:
3802*67e74705SXin Li case UTT_IsClass:
3803*67e74705SXin Li case UTT_IsFunction:
3804*67e74705SXin Li case UTT_IsReference:
3805*67e74705SXin Li case UTT_IsArithmetic:
3806*67e74705SXin Li case UTT_IsFundamental:
3807*67e74705SXin Li case UTT_IsObject:
3808*67e74705SXin Li case UTT_IsScalar:
3809*67e74705SXin Li case UTT_IsCompound:
3810*67e74705SXin Li case UTT_IsMemberPointer:
3811*67e74705SXin Li // Fall-through
3812*67e74705SXin Li
3813*67e74705SXin Li // These traits are modeled on type predicates in C++0x [meta.unary.prop]
3814*67e74705SXin Li // which requires some of its traits to have the complete type. However,
3815*67e74705SXin Li // the completeness of the type cannot impact these traits' semantics, and
3816*67e74705SXin Li // so they don't require it. This matches the comments on these traits in
3817*67e74705SXin Li // Table 49.
3818*67e74705SXin Li case UTT_IsConst:
3819*67e74705SXin Li case UTT_IsVolatile:
3820*67e74705SXin Li case UTT_IsSigned:
3821*67e74705SXin Li case UTT_IsUnsigned:
3822*67e74705SXin Li
3823*67e74705SXin Li // This type trait always returns false, checking the type is moot.
3824*67e74705SXin Li case UTT_IsInterfaceClass:
3825*67e74705SXin Li return true;
3826*67e74705SXin Li
3827*67e74705SXin Li // C++14 [meta.unary.prop]:
3828*67e74705SXin Li // If T is a non-union class type, T shall be a complete type.
3829*67e74705SXin Li case UTT_IsEmpty:
3830*67e74705SXin Li case UTT_IsPolymorphic:
3831*67e74705SXin Li case UTT_IsAbstract:
3832*67e74705SXin Li if (const auto *RD = ArgTy->getAsCXXRecordDecl())
3833*67e74705SXin Li if (!RD->isUnion())
3834*67e74705SXin Li return !S.RequireCompleteType(
3835*67e74705SXin Li Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
3836*67e74705SXin Li return true;
3837*67e74705SXin Li
3838*67e74705SXin Li // C++14 [meta.unary.prop]:
3839*67e74705SXin Li // If T is a class type, T shall be a complete type.
3840*67e74705SXin Li case UTT_IsFinal:
3841*67e74705SXin Li case UTT_IsSealed:
3842*67e74705SXin Li if (ArgTy->getAsCXXRecordDecl())
3843*67e74705SXin Li return !S.RequireCompleteType(
3844*67e74705SXin Li Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
3845*67e74705SXin Li return true;
3846*67e74705SXin Li
3847*67e74705SXin Li // C++0x [meta.unary.prop] Table 49 requires the following traits to be
3848*67e74705SXin Li // applied to a complete type.
3849*67e74705SXin Li case UTT_IsTrivial:
3850*67e74705SXin Li case UTT_IsTriviallyCopyable:
3851*67e74705SXin Li case UTT_IsStandardLayout:
3852*67e74705SXin Li case UTT_IsPOD:
3853*67e74705SXin Li case UTT_IsLiteral:
3854*67e74705SXin Li
3855*67e74705SXin Li case UTT_IsDestructible:
3856*67e74705SXin Li case UTT_IsNothrowDestructible:
3857*67e74705SXin Li // Fall-through
3858*67e74705SXin Li
3859*67e74705SXin Li // These trait expressions are designed to help implement predicates in
3860*67e74705SXin Li // [meta.unary.prop] despite not being named the same. They are specified
3861*67e74705SXin Li // by both GCC and the Embarcadero C++ compiler, and require the complete
3862*67e74705SXin Li // type due to the overarching C++0x type predicates being implemented
3863*67e74705SXin Li // requiring the complete type.
3864*67e74705SXin Li case UTT_HasNothrowAssign:
3865*67e74705SXin Li case UTT_HasNothrowMoveAssign:
3866*67e74705SXin Li case UTT_HasNothrowConstructor:
3867*67e74705SXin Li case UTT_HasNothrowCopy:
3868*67e74705SXin Li case UTT_HasTrivialAssign:
3869*67e74705SXin Li case UTT_HasTrivialMoveAssign:
3870*67e74705SXin Li case UTT_HasTrivialDefaultConstructor:
3871*67e74705SXin Li case UTT_HasTrivialMoveConstructor:
3872*67e74705SXin Li case UTT_HasTrivialCopy:
3873*67e74705SXin Li case UTT_HasTrivialDestructor:
3874*67e74705SXin Li case UTT_HasVirtualDestructor:
3875*67e74705SXin Li // Arrays of unknown bound are expressly allowed.
3876*67e74705SXin Li QualType ElTy = ArgTy;
3877*67e74705SXin Li if (ArgTy->isIncompleteArrayType())
3878*67e74705SXin Li ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
3879*67e74705SXin Li
3880*67e74705SXin Li // The void type is expressly allowed.
3881*67e74705SXin Li if (ElTy->isVoidType())
3882*67e74705SXin Li return true;
3883*67e74705SXin Li
3884*67e74705SXin Li return !S.RequireCompleteType(
3885*67e74705SXin Li Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
3886*67e74705SXin Li }
3887*67e74705SXin Li }
3888*67e74705SXin Li
HasNoThrowOperator(const RecordType * RT,OverloadedOperatorKind Op,Sema & Self,SourceLocation KeyLoc,ASTContext & C,bool (CXXRecordDecl::* HasTrivial)()const,bool (CXXRecordDecl::* HasNonTrivial)()const,bool (CXXMethodDecl::* IsDesiredOp)()const)3889*67e74705SXin Li static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
3890*67e74705SXin Li Sema &Self, SourceLocation KeyLoc, ASTContext &C,
3891*67e74705SXin Li bool (CXXRecordDecl::*HasTrivial)() const,
3892*67e74705SXin Li bool (CXXRecordDecl::*HasNonTrivial)() const,
3893*67e74705SXin Li bool (CXXMethodDecl::*IsDesiredOp)() const)
3894*67e74705SXin Li {
3895*67e74705SXin Li CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3896*67e74705SXin Li if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
3897*67e74705SXin Li return true;
3898*67e74705SXin Li
3899*67e74705SXin Li DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
3900*67e74705SXin Li DeclarationNameInfo NameInfo(Name, KeyLoc);
3901*67e74705SXin Li LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
3902*67e74705SXin Li if (Self.LookupQualifiedName(Res, RD)) {
3903*67e74705SXin Li bool FoundOperator = false;
3904*67e74705SXin Li Res.suppressDiagnostics();
3905*67e74705SXin Li for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
3906*67e74705SXin Li Op != OpEnd; ++Op) {
3907*67e74705SXin Li if (isa<FunctionTemplateDecl>(*Op))
3908*67e74705SXin Li continue;
3909*67e74705SXin Li
3910*67e74705SXin Li CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
3911*67e74705SXin Li if((Operator->*IsDesiredOp)()) {
3912*67e74705SXin Li FoundOperator = true;
3913*67e74705SXin Li const FunctionProtoType *CPT =
3914*67e74705SXin Li Operator->getType()->getAs<FunctionProtoType>();
3915*67e74705SXin Li CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3916*67e74705SXin Li if (!CPT || !CPT->isNothrow(C))
3917*67e74705SXin Li return false;
3918*67e74705SXin Li }
3919*67e74705SXin Li }
3920*67e74705SXin Li return FoundOperator;
3921*67e74705SXin Li }
3922*67e74705SXin Li return false;
3923*67e74705SXin Li }
3924*67e74705SXin Li
EvaluateUnaryTypeTrait(Sema & Self,TypeTrait UTT,SourceLocation KeyLoc,QualType T)3925*67e74705SXin Li static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
3926*67e74705SXin Li SourceLocation KeyLoc, QualType T) {
3927*67e74705SXin Li assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
3928*67e74705SXin Li
3929*67e74705SXin Li ASTContext &C = Self.Context;
3930*67e74705SXin Li switch(UTT) {
3931*67e74705SXin Li default: llvm_unreachable("not a UTT");
3932*67e74705SXin Li // Type trait expressions corresponding to the primary type category
3933*67e74705SXin Li // predicates in C++0x [meta.unary.cat].
3934*67e74705SXin Li case UTT_IsVoid:
3935*67e74705SXin Li return T->isVoidType();
3936*67e74705SXin Li case UTT_IsIntegral:
3937*67e74705SXin Li return T->isIntegralType(C);
3938*67e74705SXin Li case UTT_IsFloatingPoint:
3939*67e74705SXin Li return T->isFloatingType();
3940*67e74705SXin Li case UTT_IsArray:
3941*67e74705SXin Li return T->isArrayType();
3942*67e74705SXin Li case UTT_IsPointer:
3943*67e74705SXin Li return T->isPointerType();
3944*67e74705SXin Li case UTT_IsLvalueReference:
3945*67e74705SXin Li return T->isLValueReferenceType();
3946*67e74705SXin Li case UTT_IsRvalueReference:
3947*67e74705SXin Li return T->isRValueReferenceType();
3948*67e74705SXin Li case UTT_IsMemberFunctionPointer:
3949*67e74705SXin Li return T->isMemberFunctionPointerType();
3950*67e74705SXin Li case UTT_IsMemberObjectPointer:
3951*67e74705SXin Li return T->isMemberDataPointerType();
3952*67e74705SXin Li case UTT_IsEnum:
3953*67e74705SXin Li return T->isEnumeralType();
3954*67e74705SXin Li case UTT_IsUnion:
3955*67e74705SXin Li return T->isUnionType();
3956*67e74705SXin Li case UTT_IsClass:
3957*67e74705SXin Li return T->isClassType() || T->isStructureType() || T->isInterfaceType();
3958*67e74705SXin Li case UTT_IsFunction:
3959*67e74705SXin Li return T->isFunctionType();
3960*67e74705SXin Li
3961*67e74705SXin Li // Type trait expressions which correspond to the convenient composition
3962*67e74705SXin Li // predicates in C++0x [meta.unary.comp].
3963*67e74705SXin Li case UTT_IsReference:
3964*67e74705SXin Li return T->isReferenceType();
3965*67e74705SXin Li case UTT_IsArithmetic:
3966*67e74705SXin Li return T->isArithmeticType() && !T->isEnumeralType();
3967*67e74705SXin Li case UTT_IsFundamental:
3968*67e74705SXin Li return T->isFundamentalType();
3969*67e74705SXin Li case UTT_IsObject:
3970*67e74705SXin Li return T->isObjectType();
3971*67e74705SXin Li case UTT_IsScalar:
3972*67e74705SXin Li // Note: semantic analysis depends on Objective-C lifetime types to be
3973*67e74705SXin Li // considered scalar types. However, such types do not actually behave
3974*67e74705SXin Li // like scalar types at run time (since they may require retain/release
3975*67e74705SXin Li // operations), so we report them as non-scalar.
3976*67e74705SXin Li if (T->isObjCLifetimeType()) {
3977*67e74705SXin Li switch (T.getObjCLifetime()) {
3978*67e74705SXin Li case Qualifiers::OCL_None:
3979*67e74705SXin Li case Qualifiers::OCL_ExplicitNone:
3980*67e74705SXin Li return true;
3981*67e74705SXin Li
3982*67e74705SXin Li case Qualifiers::OCL_Strong:
3983*67e74705SXin Li case Qualifiers::OCL_Weak:
3984*67e74705SXin Li case Qualifiers::OCL_Autoreleasing:
3985*67e74705SXin Li return false;
3986*67e74705SXin Li }
3987*67e74705SXin Li }
3988*67e74705SXin Li
3989*67e74705SXin Li return T->isScalarType();
3990*67e74705SXin Li case UTT_IsCompound:
3991*67e74705SXin Li return T->isCompoundType();
3992*67e74705SXin Li case UTT_IsMemberPointer:
3993*67e74705SXin Li return T->isMemberPointerType();
3994*67e74705SXin Li
3995*67e74705SXin Li // Type trait expressions which correspond to the type property predicates
3996*67e74705SXin Li // in C++0x [meta.unary.prop].
3997*67e74705SXin Li case UTT_IsConst:
3998*67e74705SXin Li return T.isConstQualified();
3999*67e74705SXin Li case UTT_IsVolatile:
4000*67e74705SXin Li return T.isVolatileQualified();
4001*67e74705SXin Li case UTT_IsTrivial:
4002*67e74705SXin Li return T.isTrivialType(C);
4003*67e74705SXin Li case UTT_IsTriviallyCopyable:
4004*67e74705SXin Li return T.isTriviallyCopyableType(C);
4005*67e74705SXin Li case UTT_IsStandardLayout:
4006*67e74705SXin Li return T->isStandardLayoutType();
4007*67e74705SXin Li case UTT_IsPOD:
4008*67e74705SXin Li return T.isPODType(C);
4009*67e74705SXin Li case UTT_IsLiteral:
4010*67e74705SXin Li return T->isLiteralType(C);
4011*67e74705SXin Li case UTT_IsEmpty:
4012*67e74705SXin Li if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4013*67e74705SXin Li return !RD->isUnion() && RD->isEmpty();
4014*67e74705SXin Li return false;
4015*67e74705SXin Li case UTT_IsPolymorphic:
4016*67e74705SXin Li if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4017*67e74705SXin Li return !RD->isUnion() && RD->isPolymorphic();
4018*67e74705SXin Li return false;
4019*67e74705SXin Li case UTT_IsAbstract:
4020*67e74705SXin Li if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4021*67e74705SXin Li return !RD->isUnion() && RD->isAbstract();
4022*67e74705SXin Li return false;
4023*67e74705SXin Li // __is_interface_class only returns true when CL is invoked in /CLR mode and
4024*67e74705SXin Li // even then only when it is used with the 'interface struct ...' syntax
4025*67e74705SXin Li // Clang doesn't support /CLR which makes this type trait moot.
4026*67e74705SXin Li case UTT_IsInterfaceClass:
4027*67e74705SXin Li return false;
4028*67e74705SXin Li case UTT_IsFinal:
4029*67e74705SXin Li case UTT_IsSealed:
4030*67e74705SXin Li if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4031*67e74705SXin Li return RD->hasAttr<FinalAttr>();
4032*67e74705SXin Li return false;
4033*67e74705SXin Li case UTT_IsSigned:
4034*67e74705SXin Li return T->isSignedIntegerType();
4035*67e74705SXin Li case UTT_IsUnsigned:
4036*67e74705SXin Li return T->isUnsignedIntegerType();
4037*67e74705SXin Li
4038*67e74705SXin Li // Type trait expressions which query classes regarding their construction,
4039*67e74705SXin Li // destruction, and copying. Rather than being based directly on the
4040*67e74705SXin Li // related type predicates in the standard, they are specified by both
4041*67e74705SXin Li // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4042*67e74705SXin Li // specifications.
4043*67e74705SXin Li //
4044*67e74705SXin Li // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4045*67e74705SXin Li // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4046*67e74705SXin Li //
4047*67e74705SXin Li // Note that these builtins do not behave as documented in g++: if a class
4048*67e74705SXin Li // has both a trivial and a non-trivial special member of a particular kind,
4049*67e74705SXin Li // they return false! For now, we emulate this behavior.
4050*67e74705SXin Li // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4051*67e74705SXin Li // does not correctly compute triviality in the presence of multiple special
4052*67e74705SXin Li // members of the same kind. Revisit this once the g++ bug is fixed.
4053*67e74705SXin Li case UTT_HasTrivialDefaultConstructor:
4054*67e74705SXin Li // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4055*67e74705SXin Li // If __is_pod (type) is true then the trait is true, else if type is
4056*67e74705SXin Li // a cv class or union type (or array thereof) with a trivial default
4057*67e74705SXin Li // constructor ([class.ctor]) then the trait is true, else it is false.
4058*67e74705SXin Li if (T.isPODType(C))
4059*67e74705SXin Li return true;
4060*67e74705SXin Li if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4061*67e74705SXin Li return RD->hasTrivialDefaultConstructor() &&
4062*67e74705SXin Li !RD->hasNonTrivialDefaultConstructor();
4063*67e74705SXin Li return false;
4064*67e74705SXin Li case UTT_HasTrivialMoveConstructor:
4065*67e74705SXin Li // This trait is implemented by MSVC 2012 and needed to parse the
4066*67e74705SXin Li // standard library headers. Specifically this is used as the logic
4067*67e74705SXin Li // behind std::is_trivially_move_constructible (20.9.4.3).
4068*67e74705SXin Li if (T.isPODType(C))
4069*67e74705SXin Li return true;
4070*67e74705SXin Li if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4071*67e74705SXin Li return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4072*67e74705SXin Li return false;
4073*67e74705SXin Li case UTT_HasTrivialCopy:
4074*67e74705SXin Li // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4075*67e74705SXin Li // If __is_pod (type) is true or type is a reference type then
4076*67e74705SXin Li // the trait is true, else if type is a cv class or union type
4077*67e74705SXin Li // with a trivial copy constructor ([class.copy]) then the trait
4078*67e74705SXin Li // is true, else it is false.
4079*67e74705SXin Li if (T.isPODType(C) || T->isReferenceType())
4080*67e74705SXin Li return true;
4081*67e74705SXin Li if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4082*67e74705SXin Li return RD->hasTrivialCopyConstructor() &&
4083*67e74705SXin Li !RD->hasNonTrivialCopyConstructor();
4084*67e74705SXin Li return false;
4085*67e74705SXin Li case UTT_HasTrivialMoveAssign:
4086*67e74705SXin Li // This trait is implemented by MSVC 2012 and needed to parse the
4087*67e74705SXin Li // standard library headers. Specifically it is used as the logic
4088*67e74705SXin Li // behind std::is_trivially_move_assignable (20.9.4.3)
4089*67e74705SXin Li if (T.isPODType(C))
4090*67e74705SXin Li return true;
4091*67e74705SXin Li if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4092*67e74705SXin Li return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4093*67e74705SXin Li return false;
4094*67e74705SXin Li case UTT_HasTrivialAssign:
4095*67e74705SXin Li // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4096*67e74705SXin Li // If type is const qualified or is a reference type then the
4097*67e74705SXin Li // trait is false. Otherwise if __is_pod (type) is true then the
4098*67e74705SXin Li // trait is true, else if type is a cv class or union type with
4099*67e74705SXin Li // a trivial copy assignment ([class.copy]) then the trait is
4100*67e74705SXin Li // true, else it is false.
4101*67e74705SXin Li // Note: the const and reference restrictions are interesting,
4102*67e74705SXin Li // given that const and reference members don't prevent a class
4103*67e74705SXin Li // from having a trivial copy assignment operator (but do cause
4104*67e74705SXin Li // errors if the copy assignment operator is actually used, q.v.
4105*67e74705SXin Li // [class.copy]p12).
4106*67e74705SXin Li
4107*67e74705SXin Li if (T.isConstQualified())
4108*67e74705SXin Li return false;
4109*67e74705SXin Li if (T.isPODType(C))
4110*67e74705SXin Li return true;
4111*67e74705SXin Li if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4112*67e74705SXin Li return RD->hasTrivialCopyAssignment() &&
4113*67e74705SXin Li !RD->hasNonTrivialCopyAssignment();
4114*67e74705SXin Li return false;
4115*67e74705SXin Li case UTT_IsDestructible:
4116*67e74705SXin Li case UTT_IsNothrowDestructible:
4117*67e74705SXin Li // C++14 [meta.unary.prop]:
4118*67e74705SXin Li // For reference types, is_destructible<T>::value is true.
4119*67e74705SXin Li if (T->isReferenceType())
4120*67e74705SXin Li return true;
4121*67e74705SXin Li
4122*67e74705SXin Li // Objective-C++ ARC: autorelease types don't require destruction.
4123*67e74705SXin Li if (T->isObjCLifetimeType() &&
4124*67e74705SXin Li T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4125*67e74705SXin Li return true;
4126*67e74705SXin Li
4127*67e74705SXin Li // C++14 [meta.unary.prop]:
4128*67e74705SXin Li // For incomplete types and function types, is_destructible<T>::value is
4129*67e74705SXin Li // false.
4130*67e74705SXin Li if (T->isIncompleteType() || T->isFunctionType())
4131*67e74705SXin Li return false;
4132*67e74705SXin Li
4133*67e74705SXin Li // C++14 [meta.unary.prop]:
4134*67e74705SXin Li // For object types and given U equal to remove_all_extents_t<T>, if the
4135*67e74705SXin Li // expression std::declval<U&>().~U() is well-formed when treated as an
4136*67e74705SXin Li // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4137*67e74705SXin Li if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4138*67e74705SXin Li CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4139*67e74705SXin Li if (!Destructor)
4140*67e74705SXin Li return false;
4141*67e74705SXin Li // C++14 [dcl.fct.def.delete]p2:
4142*67e74705SXin Li // A program that refers to a deleted function implicitly or
4143*67e74705SXin Li // explicitly, other than to declare it, is ill-formed.
4144*67e74705SXin Li if (Destructor->isDeleted())
4145*67e74705SXin Li return false;
4146*67e74705SXin Li if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4147*67e74705SXin Li return false;
4148*67e74705SXin Li if (UTT == UTT_IsNothrowDestructible) {
4149*67e74705SXin Li const FunctionProtoType *CPT =
4150*67e74705SXin Li Destructor->getType()->getAs<FunctionProtoType>();
4151*67e74705SXin Li CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4152*67e74705SXin Li if (!CPT || !CPT->isNothrow(C))
4153*67e74705SXin Li return false;
4154*67e74705SXin Li }
4155*67e74705SXin Li }
4156*67e74705SXin Li return true;
4157*67e74705SXin Li
4158*67e74705SXin Li case UTT_HasTrivialDestructor:
4159*67e74705SXin Li // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4160*67e74705SXin Li // If __is_pod (type) is true or type is a reference type
4161*67e74705SXin Li // then the trait is true, else if type is a cv class or union
4162*67e74705SXin Li // type (or array thereof) with a trivial destructor
4163*67e74705SXin Li // ([class.dtor]) then the trait is true, else it is
4164*67e74705SXin Li // false.
4165*67e74705SXin Li if (T.isPODType(C) || T->isReferenceType())
4166*67e74705SXin Li return true;
4167*67e74705SXin Li
4168*67e74705SXin Li // Objective-C++ ARC: autorelease types don't require destruction.
4169*67e74705SXin Li if (T->isObjCLifetimeType() &&
4170*67e74705SXin Li T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4171*67e74705SXin Li return true;
4172*67e74705SXin Li
4173*67e74705SXin Li if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4174*67e74705SXin Li return RD->hasTrivialDestructor();
4175*67e74705SXin Li return false;
4176*67e74705SXin Li // TODO: Propagate nothrowness for implicitly declared special members.
4177*67e74705SXin Li case UTT_HasNothrowAssign:
4178*67e74705SXin Li // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4179*67e74705SXin Li // If type is const qualified or is a reference type then the
4180*67e74705SXin Li // trait is false. Otherwise if __has_trivial_assign (type)
4181*67e74705SXin Li // is true then the trait is true, else if type is a cv class
4182*67e74705SXin Li // or union type with copy assignment operators that are known
4183*67e74705SXin Li // not to throw an exception then the trait is true, else it is
4184*67e74705SXin Li // false.
4185*67e74705SXin Li if (C.getBaseElementType(T).isConstQualified())
4186*67e74705SXin Li return false;
4187*67e74705SXin Li if (T->isReferenceType())
4188*67e74705SXin Li return false;
4189*67e74705SXin Li if (T.isPODType(C) || T->isObjCLifetimeType())
4190*67e74705SXin Li return true;
4191*67e74705SXin Li
4192*67e74705SXin Li if (const RecordType *RT = T->getAs<RecordType>())
4193*67e74705SXin Li return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4194*67e74705SXin Li &CXXRecordDecl::hasTrivialCopyAssignment,
4195*67e74705SXin Li &CXXRecordDecl::hasNonTrivialCopyAssignment,
4196*67e74705SXin Li &CXXMethodDecl::isCopyAssignmentOperator);
4197*67e74705SXin Li return false;
4198*67e74705SXin Li case UTT_HasNothrowMoveAssign:
4199*67e74705SXin Li // This trait is implemented by MSVC 2012 and needed to parse the
4200*67e74705SXin Li // standard library headers. Specifically this is used as the logic
4201*67e74705SXin Li // behind std::is_nothrow_move_assignable (20.9.4.3).
4202*67e74705SXin Li if (T.isPODType(C))
4203*67e74705SXin Li return true;
4204*67e74705SXin Li
4205*67e74705SXin Li if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4206*67e74705SXin Li return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4207*67e74705SXin Li &CXXRecordDecl::hasTrivialMoveAssignment,
4208*67e74705SXin Li &CXXRecordDecl::hasNonTrivialMoveAssignment,
4209*67e74705SXin Li &CXXMethodDecl::isMoveAssignmentOperator);
4210*67e74705SXin Li return false;
4211*67e74705SXin Li case UTT_HasNothrowCopy:
4212*67e74705SXin Li // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4213*67e74705SXin Li // If __has_trivial_copy (type) is true then the trait is true, else
4214*67e74705SXin Li // if type is a cv class or union type with copy constructors that are
4215*67e74705SXin Li // known not to throw an exception then the trait is true, else it is
4216*67e74705SXin Li // false.
4217*67e74705SXin Li if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
4218*67e74705SXin Li return true;
4219*67e74705SXin Li if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4220*67e74705SXin Li if (RD->hasTrivialCopyConstructor() &&
4221*67e74705SXin Li !RD->hasNonTrivialCopyConstructor())
4222*67e74705SXin Li return true;
4223*67e74705SXin Li
4224*67e74705SXin Li bool FoundConstructor = false;
4225*67e74705SXin Li unsigned FoundTQs;
4226*67e74705SXin Li for (const auto *ND : Self.LookupConstructors(RD)) {
4227*67e74705SXin Li // A template constructor is never a copy constructor.
4228*67e74705SXin Li // FIXME: However, it may actually be selected at the actual overload
4229*67e74705SXin Li // resolution point.
4230*67e74705SXin Li if (isa<FunctionTemplateDecl>(ND))
4231*67e74705SXin Li continue;
4232*67e74705SXin Li const CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(ND);
4233*67e74705SXin Li if (Constructor->isCopyConstructor(FoundTQs)) {
4234*67e74705SXin Li FoundConstructor = true;
4235*67e74705SXin Li const FunctionProtoType *CPT
4236*67e74705SXin Li = Constructor->getType()->getAs<FunctionProtoType>();
4237*67e74705SXin Li CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4238*67e74705SXin Li if (!CPT)
4239*67e74705SXin Li return false;
4240*67e74705SXin Li // TODO: check whether evaluating default arguments can throw.
4241*67e74705SXin Li // For now, we'll be conservative and assume that they can throw.
4242*67e74705SXin Li if (!CPT->isNothrow(C) || CPT->getNumParams() > 1)
4243*67e74705SXin Li return false;
4244*67e74705SXin Li }
4245*67e74705SXin Li }
4246*67e74705SXin Li
4247*67e74705SXin Li return FoundConstructor;
4248*67e74705SXin Li }
4249*67e74705SXin Li return false;
4250*67e74705SXin Li case UTT_HasNothrowConstructor:
4251*67e74705SXin Li // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4252*67e74705SXin Li // If __has_trivial_constructor (type) is true then the trait is
4253*67e74705SXin Li // true, else if type is a cv class or union type (or array
4254*67e74705SXin Li // thereof) with a default constructor that is known not to
4255*67e74705SXin Li // throw an exception then the trait is true, else it is false.
4256*67e74705SXin Li if (T.isPODType(C) || T->isObjCLifetimeType())
4257*67e74705SXin Li return true;
4258*67e74705SXin Li if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4259*67e74705SXin Li if (RD->hasTrivialDefaultConstructor() &&
4260*67e74705SXin Li !RD->hasNonTrivialDefaultConstructor())
4261*67e74705SXin Li return true;
4262*67e74705SXin Li
4263*67e74705SXin Li bool FoundConstructor = false;
4264*67e74705SXin Li for (const auto *ND : Self.LookupConstructors(RD)) {
4265*67e74705SXin Li // FIXME: In C++0x, a constructor template can be a default constructor.
4266*67e74705SXin Li if (isa<FunctionTemplateDecl>(ND))
4267*67e74705SXin Li continue;
4268*67e74705SXin Li const CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(ND);
4269*67e74705SXin Li if (Constructor->isDefaultConstructor()) {
4270*67e74705SXin Li FoundConstructor = true;
4271*67e74705SXin Li const FunctionProtoType *CPT
4272*67e74705SXin Li = Constructor->getType()->getAs<FunctionProtoType>();
4273*67e74705SXin Li CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4274*67e74705SXin Li if (!CPT)
4275*67e74705SXin Li return false;
4276*67e74705SXin Li // FIXME: check whether evaluating default arguments can throw.
4277*67e74705SXin Li // For now, we'll be conservative and assume that they can throw.
4278*67e74705SXin Li if (!CPT->isNothrow(C) || CPT->getNumParams() > 0)
4279*67e74705SXin Li return false;
4280*67e74705SXin Li }
4281*67e74705SXin Li }
4282*67e74705SXin Li return FoundConstructor;
4283*67e74705SXin Li }
4284*67e74705SXin Li return false;
4285*67e74705SXin Li case UTT_HasVirtualDestructor:
4286*67e74705SXin Li // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4287*67e74705SXin Li // If type is a class type with a virtual destructor ([class.dtor])
4288*67e74705SXin Li // then the trait is true, else it is false.
4289*67e74705SXin Li if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4290*67e74705SXin Li if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
4291*67e74705SXin Li return Destructor->isVirtual();
4292*67e74705SXin Li return false;
4293*67e74705SXin Li
4294*67e74705SXin Li // These type trait expressions are modeled on the specifications for the
4295*67e74705SXin Li // Embarcadero C++0x type trait functions:
4296*67e74705SXin Li // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4297*67e74705SXin Li case UTT_IsCompleteType:
4298*67e74705SXin Li // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4299*67e74705SXin Li // Returns True if and only if T is a complete type at the point of the
4300*67e74705SXin Li // function call.
4301*67e74705SXin Li return !T->isIncompleteType();
4302*67e74705SXin Li }
4303*67e74705SXin Li }
4304*67e74705SXin Li
4305*67e74705SXin Li /// \brief Determine whether T has a non-trivial Objective-C lifetime in
4306*67e74705SXin Li /// ARC mode.
hasNontrivialObjCLifetime(QualType T)4307*67e74705SXin Li static bool hasNontrivialObjCLifetime(QualType T) {
4308*67e74705SXin Li switch (T.getObjCLifetime()) {
4309*67e74705SXin Li case Qualifiers::OCL_ExplicitNone:
4310*67e74705SXin Li return false;
4311*67e74705SXin Li
4312*67e74705SXin Li case Qualifiers::OCL_Strong:
4313*67e74705SXin Li case Qualifiers::OCL_Weak:
4314*67e74705SXin Li case Qualifiers::OCL_Autoreleasing:
4315*67e74705SXin Li return true;
4316*67e74705SXin Li
4317*67e74705SXin Li case Qualifiers::OCL_None:
4318*67e74705SXin Li return T->isObjCLifetimeType();
4319*67e74705SXin Li }
4320*67e74705SXin Li
4321*67e74705SXin Li llvm_unreachable("Unknown ObjC lifetime qualifier");
4322*67e74705SXin Li }
4323*67e74705SXin Li
4324*67e74705SXin Li static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4325*67e74705SXin Li QualType RhsT, SourceLocation KeyLoc);
4326*67e74705SXin Li
evaluateTypeTrait(Sema & S,TypeTrait Kind,SourceLocation KWLoc,ArrayRef<TypeSourceInfo * > Args,SourceLocation RParenLoc)4327*67e74705SXin Li static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4328*67e74705SXin Li ArrayRef<TypeSourceInfo *> Args,
4329*67e74705SXin Li SourceLocation RParenLoc) {
4330*67e74705SXin Li if (Kind <= UTT_Last)
4331*67e74705SXin Li return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4332*67e74705SXin Li
4333*67e74705SXin Li if (Kind <= BTT_Last)
4334*67e74705SXin Li return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4335*67e74705SXin Li Args[1]->getType(), RParenLoc);
4336*67e74705SXin Li
4337*67e74705SXin Li switch (Kind) {
4338*67e74705SXin Li case clang::TT_IsConstructible:
4339*67e74705SXin Li case clang::TT_IsNothrowConstructible:
4340*67e74705SXin Li case clang::TT_IsTriviallyConstructible: {
4341*67e74705SXin Li // C++11 [meta.unary.prop]:
4342*67e74705SXin Li // is_trivially_constructible is defined as:
4343*67e74705SXin Li //
4344*67e74705SXin Li // is_constructible<T, Args...>::value is true and the variable
4345*67e74705SXin Li // definition for is_constructible, as defined below, is known to call
4346*67e74705SXin Li // no operation that is not trivial.
4347*67e74705SXin Li //
4348*67e74705SXin Li // The predicate condition for a template specialization
4349*67e74705SXin Li // is_constructible<T, Args...> shall be satisfied if and only if the
4350*67e74705SXin Li // following variable definition would be well-formed for some invented
4351*67e74705SXin Li // variable t:
4352*67e74705SXin Li //
4353*67e74705SXin Li // T t(create<Args>()...);
4354*67e74705SXin Li assert(!Args.empty());
4355*67e74705SXin Li
4356*67e74705SXin Li // Precondition: T and all types in the parameter pack Args shall be
4357*67e74705SXin Li // complete types, (possibly cv-qualified) void, or arrays of
4358*67e74705SXin Li // unknown bound.
4359*67e74705SXin Li for (const auto *TSI : Args) {
4360*67e74705SXin Li QualType ArgTy = TSI->getType();
4361*67e74705SXin Li if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
4362*67e74705SXin Li continue;
4363*67e74705SXin Li
4364*67e74705SXin Li if (S.RequireCompleteType(KWLoc, ArgTy,
4365*67e74705SXin Li diag::err_incomplete_type_used_in_type_trait_expr))
4366*67e74705SXin Li return false;
4367*67e74705SXin Li }
4368*67e74705SXin Li
4369*67e74705SXin Li // Make sure the first argument is not incomplete nor a function type.
4370*67e74705SXin Li QualType T = Args[0]->getType();
4371*67e74705SXin Li if (T->isIncompleteType() || T->isFunctionType())
4372*67e74705SXin Li return false;
4373*67e74705SXin Li
4374*67e74705SXin Li // Make sure the first argument is not an abstract type.
4375*67e74705SXin Li CXXRecordDecl *RD = T->getAsCXXRecordDecl();
4376*67e74705SXin Li if (RD && RD->isAbstract())
4377*67e74705SXin Li return false;
4378*67e74705SXin Li
4379*67e74705SXin Li SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4380*67e74705SXin Li SmallVector<Expr *, 2> ArgExprs;
4381*67e74705SXin Li ArgExprs.reserve(Args.size() - 1);
4382*67e74705SXin Li for (unsigned I = 1, N = Args.size(); I != N; ++I) {
4383*67e74705SXin Li QualType ArgTy = Args[I]->getType();
4384*67e74705SXin Li if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4385*67e74705SXin Li ArgTy = S.Context.getRValueReferenceType(ArgTy);
4386*67e74705SXin Li OpaqueArgExprs.push_back(
4387*67e74705SXin Li OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
4388*67e74705SXin Li ArgTy.getNonLValueExprType(S.Context),
4389*67e74705SXin Li Expr::getValueKindForType(ArgTy)));
4390*67e74705SXin Li }
4391*67e74705SXin Li for (Expr &E : OpaqueArgExprs)
4392*67e74705SXin Li ArgExprs.push_back(&E);
4393*67e74705SXin Li
4394*67e74705SXin Li // Perform the initialization in an unevaluated context within a SFINAE
4395*67e74705SXin Li // trap at translation unit scope.
4396*67e74705SXin Li EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
4397*67e74705SXin Li Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4398*67e74705SXin Li Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4399*67e74705SXin Li InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
4400*67e74705SXin Li InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
4401*67e74705SXin Li RParenLoc));
4402*67e74705SXin Li InitializationSequence Init(S, To, InitKind, ArgExprs);
4403*67e74705SXin Li if (Init.Failed())
4404*67e74705SXin Li return false;
4405*67e74705SXin Li
4406*67e74705SXin Li ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
4407*67e74705SXin Li if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4408*67e74705SXin Li return false;
4409*67e74705SXin Li
4410*67e74705SXin Li if (Kind == clang::TT_IsConstructible)
4411*67e74705SXin Li return true;
4412*67e74705SXin Li
4413*67e74705SXin Li if (Kind == clang::TT_IsNothrowConstructible)
4414*67e74705SXin Li return S.canThrow(Result.get()) == CT_Cannot;
4415*67e74705SXin Li
4416*67e74705SXin Li if (Kind == clang::TT_IsTriviallyConstructible) {
4417*67e74705SXin Li // Under Objective-C ARC, if the destination has non-trivial Objective-C
4418*67e74705SXin Li // lifetime, this is a non-trivial construction.
4419*67e74705SXin Li if (S.getLangOpts().ObjCAutoRefCount &&
4420*67e74705SXin Li hasNontrivialObjCLifetime(T.getNonReferenceType()))
4421*67e74705SXin Li return false;
4422*67e74705SXin Li
4423*67e74705SXin Li // The initialization succeeded; now make sure there are no non-trivial
4424*67e74705SXin Li // calls.
4425*67e74705SXin Li return !Result.get()->hasNonTrivialCall(S.Context);
4426*67e74705SXin Li }
4427*67e74705SXin Li
4428*67e74705SXin Li llvm_unreachable("unhandled type trait");
4429*67e74705SXin Li return false;
4430*67e74705SXin Li }
4431*67e74705SXin Li default: llvm_unreachable("not a TT");
4432*67e74705SXin Li }
4433*67e74705SXin Li
4434*67e74705SXin Li return false;
4435*67e74705SXin Li }
4436*67e74705SXin Li
BuildTypeTrait(TypeTrait Kind,SourceLocation KWLoc,ArrayRef<TypeSourceInfo * > Args,SourceLocation RParenLoc)4437*67e74705SXin Li ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4438*67e74705SXin Li ArrayRef<TypeSourceInfo *> Args,
4439*67e74705SXin Li SourceLocation RParenLoc) {
4440*67e74705SXin Li QualType ResultType = Context.getLogicalOperationType();
4441*67e74705SXin Li
4442*67e74705SXin Li if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
4443*67e74705SXin Li *this, Kind, KWLoc, Args[0]->getType()))
4444*67e74705SXin Li return ExprError();
4445*67e74705SXin Li
4446*67e74705SXin Li bool Dependent = false;
4447*67e74705SXin Li for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4448*67e74705SXin Li if (Args[I]->getType()->isDependentType()) {
4449*67e74705SXin Li Dependent = true;
4450*67e74705SXin Li break;
4451*67e74705SXin Li }
4452*67e74705SXin Li }
4453*67e74705SXin Li
4454*67e74705SXin Li bool Result = false;
4455*67e74705SXin Li if (!Dependent)
4456*67e74705SXin Li Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
4457*67e74705SXin Li
4458*67e74705SXin Li return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
4459*67e74705SXin Li RParenLoc, Result);
4460*67e74705SXin Li }
4461*67e74705SXin Li
ActOnTypeTrait(TypeTrait Kind,SourceLocation KWLoc,ArrayRef<ParsedType> Args,SourceLocation RParenLoc)4462*67e74705SXin Li ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4463*67e74705SXin Li ArrayRef<ParsedType> Args,
4464*67e74705SXin Li SourceLocation RParenLoc) {
4465*67e74705SXin Li SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
4466*67e74705SXin Li ConvertedArgs.reserve(Args.size());
4467*67e74705SXin Li
4468*67e74705SXin Li for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4469*67e74705SXin Li TypeSourceInfo *TInfo;
4470*67e74705SXin Li QualType T = GetTypeFromParser(Args[I], &TInfo);
4471*67e74705SXin Li if (!TInfo)
4472*67e74705SXin Li TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
4473*67e74705SXin Li
4474*67e74705SXin Li ConvertedArgs.push_back(TInfo);
4475*67e74705SXin Li }
4476*67e74705SXin Li
4477*67e74705SXin Li return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
4478*67e74705SXin Li }
4479*67e74705SXin Li
EvaluateBinaryTypeTrait(Sema & Self,TypeTrait BTT,QualType LhsT,QualType RhsT,SourceLocation KeyLoc)4480*67e74705SXin Li static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4481*67e74705SXin Li QualType RhsT, SourceLocation KeyLoc) {
4482*67e74705SXin Li assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
4483*67e74705SXin Li "Cannot evaluate traits of dependent types");
4484*67e74705SXin Li
4485*67e74705SXin Li switch(BTT) {
4486*67e74705SXin Li case BTT_IsBaseOf: {
4487*67e74705SXin Li // C++0x [meta.rel]p2
4488*67e74705SXin Li // Base is a base class of Derived without regard to cv-qualifiers or
4489*67e74705SXin Li // Base and Derived are not unions and name the same class type without
4490*67e74705SXin Li // regard to cv-qualifiers.
4491*67e74705SXin Li
4492*67e74705SXin Li const RecordType *lhsRecord = LhsT->getAs<RecordType>();
4493*67e74705SXin Li if (!lhsRecord) return false;
4494*67e74705SXin Li
4495*67e74705SXin Li const RecordType *rhsRecord = RhsT->getAs<RecordType>();
4496*67e74705SXin Li if (!rhsRecord) return false;
4497*67e74705SXin Li
4498*67e74705SXin Li assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
4499*67e74705SXin Li == (lhsRecord == rhsRecord));
4500*67e74705SXin Li
4501*67e74705SXin Li if (lhsRecord == rhsRecord)
4502*67e74705SXin Li return !lhsRecord->getDecl()->isUnion();
4503*67e74705SXin Li
4504*67e74705SXin Li // C++0x [meta.rel]p2:
4505*67e74705SXin Li // If Base and Derived are class types and are different types
4506*67e74705SXin Li // (ignoring possible cv-qualifiers) then Derived shall be a
4507*67e74705SXin Li // complete type.
4508*67e74705SXin Li if (Self.RequireCompleteType(KeyLoc, RhsT,
4509*67e74705SXin Li diag::err_incomplete_type_used_in_type_trait_expr))
4510*67e74705SXin Li return false;
4511*67e74705SXin Li
4512*67e74705SXin Li return cast<CXXRecordDecl>(rhsRecord->getDecl())
4513*67e74705SXin Li ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
4514*67e74705SXin Li }
4515*67e74705SXin Li case BTT_IsSame:
4516*67e74705SXin Li return Self.Context.hasSameType(LhsT, RhsT);
4517*67e74705SXin Li case BTT_TypeCompatible:
4518*67e74705SXin Li return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
4519*67e74705SXin Li RhsT.getUnqualifiedType());
4520*67e74705SXin Li case BTT_IsConvertible:
4521*67e74705SXin Li case BTT_IsConvertibleTo: {
4522*67e74705SXin Li // C++0x [meta.rel]p4:
4523*67e74705SXin Li // Given the following function prototype:
4524*67e74705SXin Li //
4525*67e74705SXin Li // template <class T>
4526*67e74705SXin Li // typename add_rvalue_reference<T>::type create();
4527*67e74705SXin Li //
4528*67e74705SXin Li // the predicate condition for a template specialization
4529*67e74705SXin Li // is_convertible<From, To> shall be satisfied if and only if
4530*67e74705SXin Li // the return expression in the following code would be
4531*67e74705SXin Li // well-formed, including any implicit conversions to the return
4532*67e74705SXin Li // type of the function:
4533*67e74705SXin Li //
4534*67e74705SXin Li // To test() {
4535*67e74705SXin Li // return create<From>();
4536*67e74705SXin Li // }
4537*67e74705SXin Li //
4538*67e74705SXin Li // Access checking is performed as if in a context unrelated to To and
4539*67e74705SXin Li // From. Only the validity of the immediate context of the expression
4540*67e74705SXin Li // of the return-statement (including conversions to the return type)
4541*67e74705SXin Li // is considered.
4542*67e74705SXin Li //
4543*67e74705SXin Li // We model the initialization as a copy-initialization of a temporary
4544*67e74705SXin Li // of the appropriate type, which for this expression is identical to the
4545*67e74705SXin Li // return statement (since NRVO doesn't apply).
4546*67e74705SXin Li
4547*67e74705SXin Li // Functions aren't allowed to return function or array types.
4548*67e74705SXin Li if (RhsT->isFunctionType() || RhsT->isArrayType())
4549*67e74705SXin Li return false;
4550*67e74705SXin Li
4551*67e74705SXin Li // A return statement in a void function must have void type.
4552*67e74705SXin Li if (RhsT->isVoidType())
4553*67e74705SXin Li return LhsT->isVoidType();
4554*67e74705SXin Li
4555*67e74705SXin Li // A function definition requires a complete, non-abstract return type.
4556*67e74705SXin Li if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
4557*67e74705SXin Li return false;
4558*67e74705SXin Li
4559*67e74705SXin Li // Compute the result of add_rvalue_reference.
4560*67e74705SXin Li if (LhsT->isObjectType() || LhsT->isFunctionType())
4561*67e74705SXin Li LhsT = Self.Context.getRValueReferenceType(LhsT);
4562*67e74705SXin Li
4563*67e74705SXin Li // Build a fake source and destination for initialization.
4564*67e74705SXin Li InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
4565*67e74705SXin Li OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
4566*67e74705SXin Li Expr::getValueKindForType(LhsT));
4567*67e74705SXin Li Expr *FromPtr = &From;
4568*67e74705SXin Li InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
4569*67e74705SXin Li SourceLocation()));
4570*67e74705SXin Li
4571*67e74705SXin Li // Perform the initialization in an unevaluated context within a SFINAE
4572*67e74705SXin Li // trap at translation unit scope.
4573*67e74705SXin Li EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
4574*67e74705SXin Li Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4575*67e74705SXin Li Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
4576*67e74705SXin Li InitializationSequence Init(Self, To, Kind, FromPtr);
4577*67e74705SXin Li if (Init.Failed())
4578*67e74705SXin Li return false;
4579*67e74705SXin Li
4580*67e74705SXin Li ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
4581*67e74705SXin Li return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
4582*67e74705SXin Li }
4583*67e74705SXin Li
4584*67e74705SXin Li case BTT_IsAssignable:
4585*67e74705SXin Li case BTT_IsNothrowAssignable:
4586*67e74705SXin Li case BTT_IsTriviallyAssignable: {
4587*67e74705SXin Li // C++11 [meta.unary.prop]p3:
4588*67e74705SXin Li // is_trivially_assignable is defined as:
4589*67e74705SXin Li // is_assignable<T, U>::value is true and the assignment, as defined by
4590*67e74705SXin Li // is_assignable, is known to call no operation that is not trivial
4591*67e74705SXin Li //
4592*67e74705SXin Li // is_assignable is defined as:
4593*67e74705SXin Li // The expression declval<T>() = declval<U>() is well-formed when
4594*67e74705SXin Li // treated as an unevaluated operand (Clause 5).
4595*67e74705SXin Li //
4596*67e74705SXin Li // For both, T and U shall be complete types, (possibly cv-qualified)
4597*67e74705SXin Li // void, or arrays of unknown bound.
4598*67e74705SXin Li if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
4599*67e74705SXin Li Self.RequireCompleteType(KeyLoc, LhsT,
4600*67e74705SXin Li diag::err_incomplete_type_used_in_type_trait_expr))
4601*67e74705SXin Li return false;
4602*67e74705SXin Li if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
4603*67e74705SXin Li Self.RequireCompleteType(KeyLoc, RhsT,
4604*67e74705SXin Li diag::err_incomplete_type_used_in_type_trait_expr))
4605*67e74705SXin Li return false;
4606*67e74705SXin Li
4607*67e74705SXin Li // cv void is never assignable.
4608*67e74705SXin Li if (LhsT->isVoidType() || RhsT->isVoidType())
4609*67e74705SXin Li return false;
4610*67e74705SXin Li
4611*67e74705SXin Li // Build expressions that emulate the effect of declval<T>() and
4612*67e74705SXin Li // declval<U>().
4613*67e74705SXin Li if (LhsT->isObjectType() || LhsT->isFunctionType())
4614*67e74705SXin Li LhsT = Self.Context.getRValueReferenceType(LhsT);
4615*67e74705SXin Li if (RhsT->isObjectType() || RhsT->isFunctionType())
4616*67e74705SXin Li RhsT = Self.Context.getRValueReferenceType(RhsT);
4617*67e74705SXin Li OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
4618*67e74705SXin Li Expr::getValueKindForType(LhsT));
4619*67e74705SXin Li OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
4620*67e74705SXin Li Expr::getValueKindForType(RhsT));
4621*67e74705SXin Li
4622*67e74705SXin Li // Attempt the assignment in an unevaluated context within a SFINAE
4623*67e74705SXin Li // trap at translation unit scope.
4624*67e74705SXin Li EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
4625*67e74705SXin Li Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4626*67e74705SXin Li Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
4627*67e74705SXin Li ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
4628*67e74705SXin Li &Rhs);
4629*67e74705SXin Li if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4630*67e74705SXin Li return false;
4631*67e74705SXin Li
4632*67e74705SXin Li if (BTT == BTT_IsAssignable)
4633*67e74705SXin Li return true;
4634*67e74705SXin Li
4635*67e74705SXin Li if (BTT == BTT_IsNothrowAssignable)
4636*67e74705SXin Li return Self.canThrow(Result.get()) == CT_Cannot;
4637*67e74705SXin Li
4638*67e74705SXin Li if (BTT == BTT_IsTriviallyAssignable) {
4639*67e74705SXin Li // Under Objective-C ARC, if the destination has non-trivial Objective-C
4640*67e74705SXin Li // lifetime, this is a non-trivial assignment.
4641*67e74705SXin Li if (Self.getLangOpts().ObjCAutoRefCount &&
4642*67e74705SXin Li hasNontrivialObjCLifetime(LhsT.getNonReferenceType()))
4643*67e74705SXin Li return false;
4644*67e74705SXin Li
4645*67e74705SXin Li return !Result.get()->hasNonTrivialCall(Self.Context);
4646*67e74705SXin Li }
4647*67e74705SXin Li
4648*67e74705SXin Li llvm_unreachable("unhandled type trait");
4649*67e74705SXin Li return false;
4650*67e74705SXin Li }
4651*67e74705SXin Li default: llvm_unreachable("not a BTT");
4652*67e74705SXin Li }
4653*67e74705SXin Li llvm_unreachable("Unknown type trait or not implemented");
4654*67e74705SXin Li }
4655*67e74705SXin Li
ActOnArrayTypeTrait(ArrayTypeTrait ATT,SourceLocation KWLoc,ParsedType Ty,Expr * DimExpr,SourceLocation RParen)4656*67e74705SXin Li ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
4657*67e74705SXin Li SourceLocation KWLoc,
4658*67e74705SXin Li ParsedType Ty,
4659*67e74705SXin Li Expr* DimExpr,
4660*67e74705SXin Li SourceLocation RParen) {
4661*67e74705SXin Li TypeSourceInfo *TSInfo;
4662*67e74705SXin Li QualType T = GetTypeFromParser(Ty, &TSInfo);
4663*67e74705SXin Li if (!TSInfo)
4664*67e74705SXin Li TSInfo = Context.getTrivialTypeSourceInfo(T);
4665*67e74705SXin Li
4666*67e74705SXin Li return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
4667*67e74705SXin Li }
4668*67e74705SXin Li
EvaluateArrayTypeTrait(Sema & Self,ArrayTypeTrait ATT,QualType T,Expr * DimExpr,SourceLocation KeyLoc)4669*67e74705SXin Li static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
4670*67e74705SXin Li QualType T, Expr *DimExpr,
4671*67e74705SXin Li SourceLocation KeyLoc) {
4672*67e74705SXin Li assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
4673*67e74705SXin Li
4674*67e74705SXin Li switch(ATT) {
4675*67e74705SXin Li case ATT_ArrayRank:
4676*67e74705SXin Li if (T->isArrayType()) {
4677*67e74705SXin Li unsigned Dim = 0;
4678*67e74705SXin Li while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
4679*67e74705SXin Li ++Dim;
4680*67e74705SXin Li T = AT->getElementType();
4681*67e74705SXin Li }
4682*67e74705SXin Li return Dim;
4683*67e74705SXin Li }
4684*67e74705SXin Li return 0;
4685*67e74705SXin Li
4686*67e74705SXin Li case ATT_ArrayExtent: {
4687*67e74705SXin Li llvm::APSInt Value;
4688*67e74705SXin Li uint64_t Dim;
4689*67e74705SXin Li if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
4690*67e74705SXin Li diag::err_dimension_expr_not_constant_integer,
4691*67e74705SXin Li false).isInvalid())
4692*67e74705SXin Li return 0;
4693*67e74705SXin Li if (Value.isSigned() && Value.isNegative()) {
4694*67e74705SXin Li Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
4695*67e74705SXin Li << DimExpr->getSourceRange();
4696*67e74705SXin Li return 0;
4697*67e74705SXin Li }
4698*67e74705SXin Li Dim = Value.getLimitedValue();
4699*67e74705SXin Li
4700*67e74705SXin Li if (T->isArrayType()) {
4701*67e74705SXin Li unsigned D = 0;
4702*67e74705SXin Li bool Matched = false;
4703*67e74705SXin Li while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
4704*67e74705SXin Li if (Dim == D) {
4705*67e74705SXin Li Matched = true;
4706*67e74705SXin Li break;
4707*67e74705SXin Li }
4708*67e74705SXin Li ++D;
4709*67e74705SXin Li T = AT->getElementType();
4710*67e74705SXin Li }
4711*67e74705SXin Li
4712*67e74705SXin Li if (Matched && T->isArrayType()) {
4713*67e74705SXin Li if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
4714*67e74705SXin Li return CAT->getSize().getLimitedValue();
4715*67e74705SXin Li }
4716*67e74705SXin Li }
4717*67e74705SXin Li return 0;
4718*67e74705SXin Li }
4719*67e74705SXin Li }
4720*67e74705SXin Li llvm_unreachable("Unknown type trait or not implemented");
4721*67e74705SXin Li }
4722*67e74705SXin Li
BuildArrayTypeTrait(ArrayTypeTrait ATT,SourceLocation KWLoc,TypeSourceInfo * TSInfo,Expr * DimExpr,SourceLocation RParen)4723*67e74705SXin Li ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
4724*67e74705SXin Li SourceLocation KWLoc,
4725*67e74705SXin Li TypeSourceInfo *TSInfo,
4726*67e74705SXin Li Expr* DimExpr,
4727*67e74705SXin Li SourceLocation RParen) {
4728*67e74705SXin Li QualType T = TSInfo->getType();
4729*67e74705SXin Li
4730*67e74705SXin Li // FIXME: This should likely be tracked as an APInt to remove any host
4731*67e74705SXin Li // assumptions about the width of size_t on the target.
4732*67e74705SXin Li uint64_t Value = 0;
4733*67e74705SXin Li if (!T->isDependentType())
4734*67e74705SXin Li Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
4735*67e74705SXin Li
4736*67e74705SXin Li // While the specification for these traits from the Embarcadero C++
4737*67e74705SXin Li // compiler's documentation says the return type is 'unsigned int', Clang
4738*67e74705SXin Li // returns 'size_t'. On Windows, the primary platform for the Embarcadero
4739*67e74705SXin Li // compiler, there is no difference. On several other platforms this is an
4740*67e74705SXin Li // important distinction.
4741*67e74705SXin Li return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
4742*67e74705SXin Li RParen, Context.getSizeType());
4743*67e74705SXin Li }
4744*67e74705SXin Li
ActOnExpressionTrait(ExpressionTrait ET,SourceLocation KWLoc,Expr * Queried,SourceLocation RParen)4745*67e74705SXin Li ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
4746*67e74705SXin Li SourceLocation KWLoc,
4747*67e74705SXin Li Expr *Queried,
4748*67e74705SXin Li SourceLocation RParen) {
4749*67e74705SXin Li // If error parsing the expression, ignore.
4750*67e74705SXin Li if (!Queried)
4751*67e74705SXin Li return ExprError();
4752*67e74705SXin Li
4753*67e74705SXin Li ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
4754*67e74705SXin Li
4755*67e74705SXin Li return Result;
4756*67e74705SXin Li }
4757*67e74705SXin Li
EvaluateExpressionTrait(ExpressionTrait ET,Expr * E)4758*67e74705SXin Li static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
4759*67e74705SXin Li switch (ET) {
4760*67e74705SXin Li case ET_IsLValueExpr: return E->isLValue();
4761*67e74705SXin Li case ET_IsRValueExpr: return E->isRValue();
4762*67e74705SXin Li }
4763*67e74705SXin Li llvm_unreachable("Expression trait not covered by switch");
4764*67e74705SXin Li }
4765*67e74705SXin Li
BuildExpressionTrait(ExpressionTrait ET,SourceLocation KWLoc,Expr * Queried,SourceLocation RParen)4766*67e74705SXin Li ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
4767*67e74705SXin Li SourceLocation KWLoc,
4768*67e74705SXin Li Expr *Queried,
4769*67e74705SXin Li SourceLocation RParen) {
4770*67e74705SXin Li if (Queried->isTypeDependent()) {
4771*67e74705SXin Li // Delay type-checking for type-dependent expressions.
4772*67e74705SXin Li } else if (Queried->getType()->isPlaceholderType()) {
4773*67e74705SXin Li ExprResult PE = CheckPlaceholderExpr(Queried);
4774*67e74705SXin Li if (PE.isInvalid()) return ExprError();
4775*67e74705SXin Li return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
4776*67e74705SXin Li }
4777*67e74705SXin Li
4778*67e74705SXin Li bool Value = EvaluateExpressionTrait(ET, Queried);
4779*67e74705SXin Li
4780*67e74705SXin Li return new (Context)
4781*67e74705SXin Li ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
4782*67e74705SXin Li }
4783*67e74705SXin Li
CheckPointerToMemberOperands(ExprResult & LHS,ExprResult & RHS,ExprValueKind & VK,SourceLocation Loc,bool isIndirect)4784*67e74705SXin Li QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
4785*67e74705SXin Li ExprValueKind &VK,
4786*67e74705SXin Li SourceLocation Loc,
4787*67e74705SXin Li bool isIndirect) {
4788*67e74705SXin Li assert(!LHS.get()->getType()->isPlaceholderType() &&
4789*67e74705SXin Li !RHS.get()->getType()->isPlaceholderType() &&
4790*67e74705SXin Li "placeholders should have been weeded out by now");
4791*67e74705SXin Li
4792*67e74705SXin Li // The LHS undergoes lvalue conversions if this is ->*.
4793*67e74705SXin Li if (isIndirect) {
4794*67e74705SXin Li LHS = DefaultLvalueConversion(LHS.get());
4795*67e74705SXin Li if (LHS.isInvalid()) return QualType();
4796*67e74705SXin Li }
4797*67e74705SXin Li
4798*67e74705SXin Li // The RHS always undergoes lvalue conversions.
4799*67e74705SXin Li RHS = DefaultLvalueConversion(RHS.get());
4800*67e74705SXin Li if (RHS.isInvalid()) return QualType();
4801*67e74705SXin Li
4802*67e74705SXin Li const char *OpSpelling = isIndirect ? "->*" : ".*";
4803*67e74705SXin Li // C++ 5.5p2
4804*67e74705SXin Li // The binary operator .* [p3: ->*] binds its second operand, which shall
4805*67e74705SXin Li // be of type "pointer to member of T" (where T is a completely-defined
4806*67e74705SXin Li // class type) [...]
4807*67e74705SXin Li QualType RHSType = RHS.get()->getType();
4808*67e74705SXin Li const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
4809*67e74705SXin Li if (!MemPtr) {
4810*67e74705SXin Li Diag(Loc, diag::err_bad_memptr_rhs)
4811*67e74705SXin Li << OpSpelling << RHSType << RHS.get()->getSourceRange();
4812*67e74705SXin Li return QualType();
4813*67e74705SXin Li }
4814*67e74705SXin Li
4815*67e74705SXin Li QualType Class(MemPtr->getClass(), 0);
4816*67e74705SXin Li
4817*67e74705SXin Li // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
4818*67e74705SXin Li // member pointer points must be completely-defined. However, there is no
4819*67e74705SXin Li // reason for this semantic distinction, and the rule is not enforced by
4820*67e74705SXin Li // other compilers. Therefore, we do not check this property, as it is
4821*67e74705SXin Li // likely to be considered a defect.
4822*67e74705SXin Li
4823*67e74705SXin Li // C++ 5.5p2
4824*67e74705SXin Li // [...] to its first operand, which shall be of class T or of a class of
4825*67e74705SXin Li // which T is an unambiguous and accessible base class. [p3: a pointer to
4826*67e74705SXin Li // such a class]
4827*67e74705SXin Li QualType LHSType = LHS.get()->getType();
4828*67e74705SXin Li if (isIndirect) {
4829*67e74705SXin Li if (const PointerType *Ptr = LHSType->getAs<PointerType>())
4830*67e74705SXin Li LHSType = Ptr->getPointeeType();
4831*67e74705SXin Li else {
4832*67e74705SXin Li Diag(Loc, diag::err_bad_memptr_lhs)
4833*67e74705SXin Li << OpSpelling << 1 << LHSType
4834*67e74705SXin Li << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
4835*67e74705SXin Li return QualType();
4836*67e74705SXin Li }
4837*67e74705SXin Li }
4838*67e74705SXin Li
4839*67e74705SXin Li if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
4840*67e74705SXin Li // If we want to check the hierarchy, we need a complete type.
4841*67e74705SXin Li if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
4842*67e74705SXin Li OpSpelling, (int)isIndirect)) {
4843*67e74705SXin Li return QualType();
4844*67e74705SXin Li }
4845*67e74705SXin Li
4846*67e74705SXin Li if (!IsDerivedFrom(Loc, LHSType, Class)) {
4847*67e74705SXin Li Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
4848*67e74705SXin Li << (int)isIndirect << LHS.get()->getType();
4849*67e74705SXin Li return QualType();
4850*67e74705SXin Li }
4851*67e74705SXin Li
4852*67e74705SXin Li CXXCastPath BasePath;
4853*67e74705SXin Li if (CheckDerivedToBaseConversion(LHSType, Class, Loc,
4854*67e74705SXin Li SourceRange(LHS.get()->getLocStart(),
4855*67e74705SXin Li RHS.get()->getLocEnd()),
4856*67e74705SXin Li &BasePath))
4857*67e74705SXin Li return QualType();
4858*67e74705SXin Li
4859*67e74705SXin Li // Cast LHS to type of use.
4860*67e74705SXin Li QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
4861*67e74705SXin Li ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
4862*67e74705SXin Li LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
4863*67e74705SXin Li &BasePath);
4864*67e74705SXin Li }
4865*67e74705SXin Li
4866*67e74705SXin Li if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
4867*67e74705SXin Li // Diagnose use of pointer-to-member type which when used as
4868*67e74705SXin Li // the functional cast in a pointer-to-member expression.
4869*67e74705SXin Li Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
4870*67e74705SXin Li return QualType();
4871*67e74705SXin Li }
4872*67e74705SXin Li
4873*67e74705SXin Li // C++ 5.5p2
4874*67e74705SXin Li // The result is an object or a function of the type specified by the
4875*67e74705SXin Li // second operand.
4876*67e74705SXin Li // The cv qualifiers are the union of those in the pointer and the left side,
4877*67e74705SXin Li // in accordance with 5.5p5 and 5.2.5.
4878*67e74705SXin Li QualType Result = MemPtr->getPointeeType();
4879*67e74705SXin Li Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
4880*67e74705SXin Li
4881*67e74705SXin Li // C++0x [expr.mptr.oper]p6:
4882*67e74705SXin Li // In a .* expression whose object expression is an rvalue, the program is
4883*67e74705SXin Li // ill-formed if the second operand is a pointer to member function with
4884*67e74705SXin Li // ref-qualifier &. In a ->* expression or in a .* expression whose object
4885*67e74705SXin Li // expression is an lvalue, the program is ill-formed if the second operand
4886*67e74705SXin Li // is a pointer to member function with ref-qualifier &&.
4887*67e74705SXin Li if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
4888*67e74705SXin Li switch (Proto->getRefQualifier()) {
4889*67e74705SXin Li case RQ_None:
4890*67e74705SXin Li // Do nothing
4891*67e74705SXin Li break;
4892*67e74705SXin Li
4893*67e74705SXin Li case RQ_LValue:
4894*67e74705SXin Li if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
4895*67e74705SXin Li Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
4896*67e74705SXin Li << RHSType << 1 << LHS.get()->getSourceRange();
4897*67e74705SXin Li break;
4898*67e74705SXin Li
4899*67e74705SXin Li case RQ_RValue:
4900*67e74705SXin Li if (isIndirect || !LHS.get()->Classify(Context).isRValue())
4901*67e74705SXin Li Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
4902*67e74705SXin Li << RHSType << 0 << LHS.get()->getSourceRange();
4903*67e74705SXin Li break;
4904*67e74705SXin Li }
4905*67e74705SXin Li }
4906*67e74705SXin Li
4907*67e74705SXin Li // C++ [expr.mptr.oper]p6:
4908*67e74705SXin Li // The result of a .* expression whose second operand is a pointer
4909*67e74705SXin Li // to a data member is of the same value category as its
4910*67e74705SXin Li // first operand. The result of a .* expression whose second
4911*67e74705SXin Li // operand is a pointer to a member function is a prvalue. The
4912*67e74705SXin Li // result of an ->* expression is an lvalue if its second operand
4913*67e74705SXin Li // is a pointer to data member and a prvalue otherwise.
4914*67e74705SXin Li if (Result->isFunctionType()) {
4915*67e74705SXin Li VK = VK_RValue;
4916*67e74705SXin Li return Context.BoundMemberTy;
4917*67e74705SXin Li } else if (isIndirect) {
4918*67e74705SXin Li VK = VK_LValue;
4919*67e74705SXin Li } else {
4920*67e74705SXin Li VK = LHS.get()->getValueKind();
4921*67e74705SXin Li }
4922*67e74705SXin Li
4923*67e74705SXin Li return Result;
4924*67e74705SXin Li }
4925*67e74705SXin Li
4926*67e74705SXin Li /// \brief Try to convert a type to another according to C++11 5.16p3.
4927*67e74705SXin Li ///
4928*67e74705SXin Li /// This is part of the parameter validation for the ? operator. If either
4929*67e74705SXin Li /// value operand is a class type, the two operands are attempted to be
4930*67e74705SXin Li /// converted to each other. This function does the conversion in one direction.
4931*67e74705SXin Li /// It returns true if the program is ill-formed and has already been diagnosed
4932*67e74705SXin Li /// as such.
TryClassUnification(Sema & Self,Expr * From,Expr * To,SourceLocation QuestionLoc,bool & HaveConversion,QualType & ToType)4933*67e74705SXin Li static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
4934*67e74705SXin Li SourceLocation QuestionLoc,
4935*67e74705SXin Li bool &HaveConversion,
4936*67e74705SXin Li QualType &ToType) {
4937*67e74705SXin Li HaveConversion = false;
4938*67e74705SXin Li ToType = To->getType();
4939*67e74705SXin Li
4940*67e74705SXin Li InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
4941*67e74705SXin Li SourceLocation());
4942*67e74705SXin Li // C++11 5.16p3
4943*67e74705SXin Li // The process for determining whether an operand expression E1 of type T1
4944*67e74705SXin Li // can be converted to match an operand expression E2 of type T2 is defined
4945*67e74705SXin Li // as follows:
4946*67e74705SXin Li // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
4947*67e74705SXin Li // implicitly converted to type "lvalue reference to T2", subject to the
4948*67e74705SXin Li // constraint that in the conversion the reference must bind directly to
4949*67e74705SXin Li // an lvalue.
4950*67e74705SXin Li // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
4951*67e74705SXin Li // implicitly conveted to the type "rvalue reference to R2", subject to
4952*67e74705SXin Li // the constraint that the reference must bind directly.
4953*67e74705SXin Li if (To->isLValue() || To->isXValue()) {
4954*67e74705SXin Li QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
4955*67e74705SXin Li : Self.Context.getRValueReferenceType(ToType);
4956*67e74705SXin Li
4957*67e74705SXin Li InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
4958*67e74705SXin Li
4959*67e74705SXin Li InitializationSequence InitSeq(Self, Entity, Kind, From);
4960*67e74705SXin Li if (InitSeq.isDirectReferenceBinding()) {
4961*67e74705SXin Li ToType = T;
4962*67e74705SXin Li HaveConversion = true;
4963*67e74705SXin Li return false;
4964*67e74705SXin Li }
4965*67e74705SXin Li
4966*67e74705SXin Li if (InitSeq.isAmbiguous())
4967*67e74705SXin Li return InitSeq.Diagnose(Self, Entity, Kind, From);
4968*67e74705SXin Li }
4969*67e74705SXin Li
4970*67e74705SXin Li // -- If E2 is an rvalue, or if the conversion above cannot be done:
4971*67e74705SXin Li // -- if E1 and E2 have class type, and the underlying class types are
4972*67e74705SXin Li // the same or one is a base class of the other:
4973*67e74705SXin Li QualType FTy = From->getType();
4974*67e74705SXin Li QualType TTy = To->getType();
4975*67e74705SXin Li const RecordType *FRec = FTy->getAs<RecordType>();
4976*67e74705SXin Li const RecordType *TRec = TTy->getAs<RecordType>();
4977*67e74705SXin Li bool FDerivedFromT = FRec && TRec && FRec != TRec &&
4978*67e74705SXin Li Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
4979*67e74705SXin Li if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
4980*67e74705SXin Li Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
4981*67e74705SXin Li // E1 can be converted to match E2 if the class of T2 is the
4982*67e74705SXin Li // same type as, or a base class of, the class of T1, and
4983*67e74705SXin Li // [cv2 > cv1].
4984*67e74705SXin Li if (FRec == TRec || FDerivedFromT) {
4985*67e74705SXin Li if (TTy.isAtLeastAsQualifiedAs(FTy)) {
4986*67e74705SXin Li InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
4987*67e74705SXin Li InitializationSequence InitSeq(Self, Entity, Kind, From);
4988*67e74705SXin Li if (InitSeq) {
4989*67e74705SXin Li HaveConversion = true;
4990*67e74705SXin Li return false;
4991*67e74705SXin Li }
4992*67e74705SXin Li
4993*67e74705SXin Li if (InitSeq.isAmbiguous())
4994*67e74705SXin Li return InitSeq.Diagnose(Self, Entity, Kind, From);
4995*67e74705SXin Li }
4996*67e74705SXin Li }
4997*67e74705SXin Li
4998*67e74705SXin Li return false;
4999*67e74705SXin Li }
5000*67e74705SXin Li
5001*67e74705SXin Li // -- Otherwise: E1 can be converted to match E2 if E1 can be
5002*67e74705SXin Li // implicitly converted to the type that expression E2 would have
5003*67e74705SXin Li // if E2 were converted to an rvalue (or the type it has, if E2 is
5004*67e74705SXin Li // an rvalue).
5005*67e74705SXin Li //
5006*67e74705SXin Li // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5007*67e74705SXin Li // to the array-to-pointer or function-to-pointer conversions.
5008*67e74705SXin Li if (!TTy->getAs<TagType>())
5009*67e74705SXin Li TTy = TTy.getUnqualifiedType();
5010*67e74705SXin Li
5011*67e74705SXin Li InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
5012*67e74705SXin Li InitializationSequence InitSeq(Self, Entity, Kind, From);
5013*67e74705SXin Li HaveConversion = !InitSeq.Failed();
5014*67e74705SXin Li ToType = TTy;
5015*67e74705SXin Li if (InitSeq.isAmbiguous())
5016*67e74705SXin Li return InitSeq.Diagnose(Self, Entity, Kind, From);
5017*67e74705SXin Li
5018*67e74705SXin Li return false;
5019*67e74705SXin Li }
5020*67e74705SXin Li
5021*67e74705SXin Li /// \brief Try to find a common type for two according to C++0x 5.16p5.
5022*67e74705SXin Li ///
5023*67e74705SXin Li /// This is part of the parameter validation for the ? operator. If either
5024*67e74705SXin Li /// value operand is a class type, overload resolution is used to find a
5025*67e74705SXin Li /// conversion to a common type.
FindConditionalOverload(Sema & Self,ExprResult & LHS,ExprResult & RHS,SourceLocation QuestionLoc)5026*67e74705SXin Li static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
5027*67e74705SXin Li SourceLocation QuestionLoc) {
5028*67e74705SXin Li Expr *Args[2] = { LHS.get(), RHS.get() };
5029*67e74705SXin Li OverloadCandidateSet CandidateSet(QuestionLoc,
5030*67e74705SXin Li OverloadCandidateSet::CSK_Operator);
5031*67e74705SXin Li Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
5032*67e74705SXin Li CandidateSet);
5033*67e74705SXin Li
5034*67e74705SXin Li OverloadCandidateSet::iterator Best;
5035*67e74705SXin Li switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
5036*67e74705SXin Li case OR_Success: {
5037*67e74705SXin Li // We found a match. Perform the conversions on the arguments and move on.
5038*67e74705SXin Li ExprResult LHSRes =
5039*67e74705SXin Li Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
5040*67e74705SXin Li Best->Conversions[0], Sema::AA_Converting);
5041*67e74705SXin Li if (LHSRes.isInvalid())
5042*67e74705SXin Li break;
5043*67e74705SXin Li LHS = LHSRes;
5044*67e74705SXin Li
5045*67e74705SXin Li ExprResult RHSRes =
5046*67e74705SXin Li Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
5047*67e74705SXin Li Best->Conversions[1], Sema::AA_Converting);
5048*67e74705SXin Li if (RHSRes.isInvalid())
5049*67e74705SXin Li break;
5050*67e74705SXin Li RHS = RHSRes;
5051*67e74705SXin Li if (Best->Function)
5052*67e74705SXin Li Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
5053*67e74705SXin Li return false;
5054*67e74705SXin Li }
5055*67e74705SXin Li
5056*67e74705SXin Li case OR_No_Viable_Function:
5057*67e74705SXin Li
5058*67e74705SXin Li // Emit a better diagnostic if one of the expressions is a null pointer
5059*67e74705SXin Li // constant and the other is a pointer type. In this case, the user most
5060*67e74705SXin Li // likely forgot to take the address of the other expression.
5061*67e74705SXin Li if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5062*67e74705SXin Li return true;
5063*67e74705SXin Li
5064*67e74705SXin Li Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5065*67e74705SXin Li << LHS.get()->getType() << RHS.get()->getType()
5066*67e74705SXin Li << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5067*67e74705SXin Li return true;
5068*67e74705SXin Li
5069*67e74705SXin Li case OR_Ambiguous:
5070*67e74705SXin Li Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
5071*67e74705SXin Li << LHS.get()->getType() << RHS.get()->getType()
5072*67e74705SXin Li << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5073*67e74705SXin Li // FIXME: Print the possible common types by printing the return types of
5074*67e74705SXin Li // the viable candidates.
5075*67e74705SXin Li break;
5076*67e74705SXin Li
5077*67e74705SXin Li case OR_Deleted:
5078*67e74705SXin Li llvm_unreachable("Conditional operator has only built-in overloads");
5079*67e74705SXin Li }
5080*67e74705SXin Li return true;
5081*67e74705SXin Li }
5082*67e74705SXin Li
5083*67e74705SXin Li /// \brief Perform an "extended" implicit conversion as returned by
5084*67e74705SXin Li /// TryClassUnification.
ConvertForConditional(Sema & Self,ExprResult & E,QualType T)5085*67e74705SXin Li static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
5086*67e74705SXin Li InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
5087*67e74705SXin Li InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
5088*67e74705SXin Li SourceLocation());
5089*67e74705SXin Li Expr *Arg = E.get();
5090*67e74705SXin Li InitializationSequence InitSeq(Self, Entity, Kind, Arg);
5091*67e74705SXin Li ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
5092*67e74705SXin Li if (Result.isInvalid())
5093*67e74705SXin Li return true;
5094*67e74705SXin Li
5095*67e74705SXin Li E = Result;
5096*67e74705SXin Li return false;
5097*67e74705SXin Li }
5098*67e74705SXin Li
5099*67e74705SXin Li /// \brief Check the operands of ?: under C++ semantics.
5100*67e74705SXin Li ///
5101*67e74705SXin Li /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5102*67e74705SXin Li /// extension. In this case, LHS == Cond. (But they're not aliases.)
CXXCheckConditionalOperands(ExprResult & Cond,ExprResult & LHS,ExprResult & RHS,ExprValueKind & VK,ExprObjectKind & OK,SourceLocation QuestionLoc)5103*67e74705SXin Li QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5104*67e74705SXin Li ExprResult &RHS, ExprValueKind &VK,
5105*67e74705SXin Li ExprObjectKind &OK,
5106*67e74705SXin Li SourceLocation QuestionLoc) {
5107*67e74705SXin Li // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5108*67e74705SXin Li // interface pointers.
5109*67e74705SXin Li
5110*67e74705SXin Li // C++11 [expr.cond]p1
5111*67e74705SXin Li // The first expression is contextually converted to bool.
5112*67e74705SXin Li if (!Cond.get()->isTypeDependent()) {
5113*67e74705SXin Li ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
5114*67e74705SXin Li if (CondRes.isInvalid())
5115*67e74705SXin Li return QualType();
5116*67e74705SXin Li Cond = CondRes;
5117*67e74705SXin Li }
5118*67e74705SXin Li
5119*67e74705SXin Li // Assume r-value.
5120*67e74705SXin Li VK = VK_RValue;
5121*67e74705SXin Li OK = OK_Ordinary;
5122*67e74705SXin Li
5123*67e74705SXin Li // Either of the arguments dependent?
5124*67e74705SXin Li if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
5125*67e74705SXin Li return Context.DependentTy;
5126*67e74705SXin Li
5127*67e74705SXin Li // C++11 [expr.cond]p2
5128*67e74705SXin Li // If either the second or the third operand has type (cv) void, ...
5129*67e74705SXin Li QualType LTy = LHS.get()->getType();
5130*67e74705SXin Li QualType RTy = RHS.get()->getType();
5131*67e74705SXin Li bool LVoid = LTy->isVoidType();
5132*67e74705SXin Li bool RVoid = RTy->isVoidType();
5133*67e74705SXin Li if (LVoid || RVoid) {
5134*67e74705SXin Li // ... one of the following shall hold:
5135*67e74705SXin Li // -- The second or the third operand (but not both) is a (possibly
5136*67e74705SXin Li // parenthesized) throw-expression; the result is of the type
5137*67e74705SXin Li // and value category of the other.
5138*67e74705SXin Li bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5139*67e74705SXin Li bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5140*67e74705SXin Li if (LThrow != RThrow) {
5141*67e74705SXin Li Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5142*67e74705SXin Li VK = NonThrow->getValueKind();
5143*67e74705SXin Li // DR (no number yet): the result is a bit-field if the
5144*67e74705SXin Li // non-throw-expression operand is a bit-field.
5145*67e74705SXin Li OK = NonThrow->getObjectKind();
5146*67e74705SXin Li return NonThrow->getType();
5147*67e74705SXin Li }
5148*67e74705SXin Li
5149*67e74705SXin Li // -- Both the second and third operands have type void; the result is of
5150*67e74705SXin Li // type void and is a prvalue.
5151*67e74705SXin Li if (LVoid && RVoid)
5152*67e74705SXin Li return Context.VoidTy;
5153*67e74705SXin Li
5154*67e74705SXin Li // Neither holds, error.
5155*67e74705SXin Li Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5156*67e74705SXin Li << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
5157*67e74705SXin Li << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5158*67e74705SXin Li return QualType();
5159*67e74705SXin Li }
5160*67e74705SXin Li
5161*67e74705SXin Li // Neither is void.
5162*67e74705SXin Li
5163*67e74705SXin Li // C++11 [expr.cond]p3
5164*67e74705SXin Li // Otherwise, if the second and third operand have different types, and
5165*67e74705SXin Li // either has (cv) class type [...] an attempt is made to convert each of
5166*67e74705SXin Li // those operands to the type of the other.
5167*67e74705SXin Li if (!Context.hasSameType(LTy, RTy) &&
5168*67e74705SXin Li (LTy->isRecordType() || RTy->isRecordType())) {
5169*67e74705SXin Li // These return true if a single direction is already ambiguous.
5170*67e74705SXin Li QualType L2RType, R2LType;
5171*67e74705SXin Li bool HaveL2R, HaveR2L;
5172*67e74705SXin Li if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
5173*67e74705SXin Li return QualType();
5174*67e74705SXin Li if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
5175*67e74705SXin Li return QualType();
5176*67e74705SXin Li
5177*67e74705SXin Li // If both can be converted, [...] the program is ill-formed.
5178*67e74705SXin Li if (HaveL2R && HaveR2L) {
5179*67e74705SXin Li Diag(QuestionLoc, diag::err_conditional_ambiguous)
5180*67e74705SXin Li << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5181*67e74705SXin Li return QualType();
5182*67e74705SXin Li }
5183*67e74705SXin Li
5184*67e74705SXin Li // If exactly one conversion is possible, that conversion is applied to
5185*67e74705SXin Li // the chosen operand and the converted operands are used in place of the
5186*67e74705SXin Li // original operands for the remainder of this section.
5187*67e74705SXin Li if (HaveL2R) {
5188*67e74705SXin Li if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
5189*67e74705SXin Li return QualType();
5190*67e74705SXin Li LTy = LHS.get()->getType();
5191*67e74705SXin Li } else if (HaveR2L) {
5192*67e74705SXin Li if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
5193*67e74705SXin Li return QualType();
5194*67e74705SXin Li RTy = RHS.get()->getType();
5195*67e74705SXin Li }
5196*67e74705SXin Li }
5197*67e74705SXin Li
5198*67e74705SXin Li // C++11 [expr.cond]p3
5199*67e74705SXin Li // if both are glvalues of the same value category and the same type except
5200*67e74705SXin Li // for cv-qualification, an attempt is made to convert each of those
5201*67e74705SXin Li // operands to the type of the other.
5202*67e74705SXin Li ExprValueKind LVK = LHS.get()->getValueKind();
5203*67e74705SXin Li ExprValueKind RVK = RHS.get()->getValueKind();
5204*67e74705SXin Li if (!Context.hasSameType(LTy, RTy) &&
5205*67e74705SXin Li Context.hasSameUnqualifiedType(LTy, RTy) &&
5206*67e74705SXin Li LVK == RVK && LVK != VK_RValue) {
5207*67e74705SXin Li // Since the unqualified types are reference-related and we require the
5208*67e74705SXin Li // result to be as if a reference bound directly, the only conversion
5209*67e74705SXin Li // we can perform is to add cv-qualifiers.
5210*67e74705SXin Li Qualifiers LCVR = Qualifiers::fromCVRMask(LTy.getCVRQualifiers());
5211*67e74705SXin Li Qualifiers RCVR = Qualifiers::fromCVRMask(RTy.getCVRQualifiers());
5212*67e74705SXin Li if (RCVR.isStrictSupersetOf(LCVR)) {
5213*67e74705SXin Li LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
5214*67e74705SXin Li LTy = LHS.get()->getType();
5215*67e74705SXin Li }
5216*67e74705SXin Li else if (LCVR.isStrictSupersetOf(RCVR)) {
5217*67e74705SXin Li RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
5218*67e74705SXin Li RTy = RHS.get()->getType();
5219*67e74705SXin Li }
5220*67e74705SXin Li }
5221*67e74705SXin Li
5222*67e74705SXin Li // C++11 [expr.cond]p4
5223*67e74705SXin Li // If the second and third operands are glvalues of the same value
5224*67e74705SXin Li // category and have the same type, the result is of that type and
5225*67e74705SXin Li // value category and it is a bit-field if the second or the third
5226*67e74705SXin Li // operand is a bit-field, or if both are bit-fields.
5227*67e74705SXin Li // We only extend this to bitfields, not to the crazy other kinds of
5228*67e74705SXin Li // l-values.
5229*67e74705SXin Li bool Same = Context.hasSameType(LTy, RTy);
5230*67e74705SXin Li if (Same && LVK == RVK && LVK != VK_RValue &&
5231*67e74705SXin Li LHS.get()->isOrdinaryOrBitFieldObject() &&
5232*67e74705SXin Li RHS.get()->isOrdinaryOrBitFieldObject()) {
5233*67e74705SXin Li VK = LHS.get()->getValueKind();
5234*67e74705SXin Li if (LHS.get()->getObjectKind() == OK_BitField ||
5235*67e74705SXin Li RHS.get()->getObjectKind() == OK_BitField)
5236*67e74705SXin Li OK = OK_BitField;
5237*67e74705SXin Li return LTy;
5238*67e74705SXin Li }
5239*67e74705SXin Li
5240*67e74705SXin Li // C++11 [expr.cond]p5
5241*67e74705SXin Li // Otherwise, the result is a prvalue. If the second and third operands
5242*67e74705SXin Li // do not have the same type, and either has (cv) class type, ...
5243*67e74705SXin Li if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
5244*67e74705SXin Li // ... overload resolution is used to determine the conversions (if any)
5245*67e74705SXin Li // to be applied to the operands. If the overload resolution fails, the
5246*67e74705SXin Li // program is ill-formed.
5247*67e74705SXin Li if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
5248*67e74705SXin Li return QualType();
5249*67e74705SXin Li }
5250*67e74705SXin Li
5251*67e74705SXin Li // C++11 [expr.cond]p6
5252*67e74705SXin Li // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
5253*67e74705SXin Li // conversions are performed on the second and third operands.
5254*67e74705SXin Li LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5255*67e74705SXin Li RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
5256*67e74705SXin Li if (LHS.isInvalid() || RHS.isInvalid())
5257*67e74705SXin Li return QualType();
5258*67e74705SXin Li LTy = LHS.get()->getType();
5259*67e74705SXin Li RTy = RHS.get()->getType();
5260*67e74705SXin Li
5261*67e74705SXin Li // After those conversions, one of the following shall hold:
5262*67e74705SXin Li // -- The second and third operands have the same type; the result
5263*67e74705SXin Li // is of that type. If the operands have class type, the result
5264*67e74705SXin Li // is a prvalue temporary of the result type, which is
5265*67e74705SXin Li // copy-initialized from either the second operand or the third
5266*67e74705SXin Li // operand depending on the value of the first operand.
5267*67e74705SXin Li if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
5268*67e74705SXin Li if (LTy->isRecordType()) {
5269*67e74705SXin Li // The operands have class type. Make a temporary copy.
5270*67e74705SXin Li if (RequireNonAbstractType(QuestionLoc, LTy,
5271*67e74705SXin Li diag::err_allocation_of_abstract_type))
5272*67e74705SXin Li return QualType();
5273*67e74705SXin Li InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
5274*67e74705SXin Li
5275*67e74705SXin Li ExprResult LHSCopy = PerformCopyInitialization(Entity,
5276*67e74705SXin Li SourceLocation(),
5277*67e74705SXin Li LHS);
5278*67e74705SXin Li if (LHSCopy.isInvalid())
5279*67e74705SXin Li return QualType();
5280*67e74705SXin Li
5281*67e74705SXin Li ExprResult RHSCopy = PerformCopyInitialization(Entity,
5282*67e74705SXin Li SourceLocation(),
5283*67e74705SXin Li RHS);
5284*67e74705SXin Li if (RHSCopy.isInvalid())
5285*67e74705SXin Li return QualType();
5286*67e74705SXin Li
5287*67e74705SXin Li LHS = LHSCopy;
5288*67e74705SXin Li RHS = RHSCopy;
5289*67e74705SXin Li }
5290*67e74705SXin Li
5291*67e74705SXin Li return LTy;
5292*67e74705SXin Li }
5293*67e74705SXin Li
5294*67e74705SXin Li // Extension: conditional operator involving vector types.
5295*67e74705SXin Li if (LTy->isVectorType() || RTy->isVectorType())
5296*67e74705SXin Li return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
5297*67e74705SXin Li /*AllowBothBool*/true,
5298*67e74705SXin Li /*AllowBoolConversions*/false);
5299*67e74705SXin Li
5300*67e74705SXin Li // -- The second and third operands have arithmetic or enumeration type;
5301*67e74705SXin Li // the usual arithmetic conversions are performed to bring them to a
5302*67e74705SXin Li // common type, and the result is of that type.
5303*67e74705SXin Li if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
5304*67e74705SXin Li QualType ResTy = UsualArithmeticConversions(LHS, RHS);
5305*67e74705SXin Li if (LHS.isInvalid() || RHS.isInvalid())
5306*67e74705SXin Li return QualType();
5307*67e74705SXin Li if (ResTy.isNull()) {
5308*67e74705SXin Li Diag(QuestionLoc,
5309*67e74705SXin Li diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
5310*67e74705SXin Li << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5311*67e74705SXin Li return QualType();
5312*67e74705SXin Li }
5313*67e74705SXin Li
5314*67e74705SXin Li LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5315*67e74705SXin Li RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5316*67e74705SXin Li
5317*67e74705SXin Li return ResTy;
5318*67e74705SXin Li }
5319*67e74705SXin Li
5320*67e74705SXin Li // -- The second and third operands have pointer type, or one has pointer
5321*67e74705SXin Li // type and the other is a null pointer constant, or both are null
5322*67e74705SXin Li // pointer constants, at least one of which is non-integral; pointer
5323*67e74705SXin Li // conversions and qualification conversions are performed to bring them
5324*67e74705SXin Li // to their composite pointer type. The result is of the composite
5325*67e74705SXin Li // pointer type.
5326*67e74705SXin Li // -- The second and third operands have pointer to member type, or one has
5327*67e74705SXin Li // pointer to member type and the other is a null pointer constant;
5328*67e74705SXin Li // pointer to member conversions and qualification conversions are
5329*67e74705SXin Li // performed to bring them to a common type, whose cv-qualification
5330*67e74705SXin Li // shall match the cv-qualification of either the second or the third
5331*67e74705SXin Li // operand. The result is of the common type.
5332*67e74705SXin Li bool NonStandardCompositeType = false;
5333*67e74705SXin Li QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
5334*67e74705SXin Li isSFINAEContext() ? nullptr
5335*67e74705SXin Li : &NonStandardCompositeType);
5336*67e74705SXin Li if (!Composite.isNull()) {
5337*67e74705SXin Li if (NonStandardCompositeType)
5338*67e74705SXin Li Diag(QuestionLoc,
5339*67e74705SXin Li diag::ext_typecheck_cond_incompatible_operands_nonstandard)
5340*67e74705SXin Li << LTy << RTy << Composite
5341*67e74705SXin Li << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5342*67e74705SXin Li
5343*67e74705SXin Li return Composite;
5344*67e74705SXin Li }
5345*67e74705SXin Li
5346*67e74705SXin Li // Similarly, attempt to find composite type of two objective-c pointers.
5347*67e74705SXin Li Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
5348*67e74705SXin Li if (!Composite.isNull())
5349*67e74705SXin Li return Composite;
5350*67e74705SXin Li
5351*67e74705SXin Li // Check if we are using a null with a non-pointer type.
5352*67e74705SXin Li if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5353*67e74705SXin Li return QualType();
5354*67e74705SXin Li
5355*67e74705SXin Li Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5356*67e74705SXin Li << LHS.get()->getType() << RHS.get()->getType()
5357*67e74705SXin Li << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5358*67e74705SXin Li return QualType();
5359*67e74705SXin Li }
5360*67e74705SXin Li
5361*67e74705SXin Li /// \brief Find a merged pointer type and convert the two expressions to it.
5362*67e74705SXin Li ///
5363*67e74705SXin Li /// This finds the composite pointer type (or member pointer type) for @p E1
5364*67e74705SXin Li /// and @p E2 according to C++11 5.9p2. It converts both expressions to this
5365*67e74705SXin Li /// type and returns it.
5366*67e74705SXin Li /// It does not emit diagnostics.
5367*67e74705SXin Li ///
5368*67e74705SXin Li /// \param Loc The location of the operator requiring these two expressions to
5369*67e74705SXin Li /// be converted to the composite pointer type.
5370*67e74705SXin Li ///
5371*67e74705SXin Li /// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
5372*67e74705SXin Li /// a non-standard (but still sane) composite type to which both expressions
5373*67e74705SXin Li /// can be converted. When such a type is chosen, \c *NonStandardCompositeType
5374*67e74705SXin Li /// will be set true.
FindCompositePointerType(SourceLocation Loc,Expr * & E1,Expr * & E2,bool * NonStandardCompositeType)5375*67e74705SXin Li QualType Sema::FindCompositePointerType(SourceLocation Loc,
5376*67e74705SXin Li Expr *&E1, Expr *&E2,
5377*67e74705SXin Li bool *NonStandardCompositeType) {
5378*67e74705SXin Li if (NonStandardCompositeType)
5379*67e74705SXin Li *NonStandardCompositeType = false;
5380*67e74705SXin Li
5381*67e74705SXin Li assert(getLangOpts().CPlusPlus && "This function assumes C++");
5382*67e74705SXin Li QualType T1 = E1->getType(), T2 = E2->getType();
5383*67e74705SXin Li
5384*67e74705SXin Li // C++11 5.9p2
5385*67e74705SXin Li // Pointer conversions and qualification conversions are performed on
5386*67e74705SXin Li // pointer operands to bring them to their composite pointer type. If
5387*67e74705SXin Li // one operand is a null pointer constant, the composite pointer type is
5388*67e74705SXin Li // std::nullptr_t if the other operand is also a null pointer constant or,
5389*67e74705SXin Li // if the other operand is a pointer, the type of the other operand.
5390*67e74705SXin Li if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
5391*67e74705SXin Li !T2->isAnyPointerType() && !T2->isMemberPointerType()) {
5392*67e74705SXin Li if (T1->isNullPtrType() &&
5393*67e74705SXin Li E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5394*67e74705SXin Li E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).get();
5395*67e74705SXin Li return T1;
5396*67e74705SXin Li }
5397*67e74705SXin Li if (T2->isNullPtrType() &&
5398*67e74705SXin Li E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5399*67e74705SXin Li E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).get();
5400*67e74705SXin Li return T2;
5401*67e74705SXin Li }
5402*67e74705SXin Li return QualType();
5403*67e74705SXin Li }
5404*67e74705SXin Li
5405*67e74705SXin Li if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5406*67e74705SXin Li if (T2->isMemberPointerType())
5407*67e74705SXin Li E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).get();
5408*67e74705SXin Li else
5409*67e74705SXin Li E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).get();
5410*67e74705SXin Li return T2;
5411*67e74705SXin Li }
5412*67e74705SXin Li if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5413*67e74705SXin Li if (T1->isMemberPointerType())
5414*67e74705SXin Li E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).get();
5415*67e74705SXin Li else
5416*67e74705SXin Li E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).get();
5417*67e74705SXin Li return T1;
5418*67e74705SXin Li }
5419*67e74705SXin Li
5420*67e74705SXin Li // Now both have to be pointers or member pointers.
5421*67e74705SXin Li if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
5422*67e74705SXin Li (!T2->isPointerType() && !T2->isMemberPointerType()))
5423*67e74705SXin Li return QualType();
5424*67e74705SXin Li
5425*67e74705SXin Li // Otherwise, of one of the operands has type "pointer to cv1 void," then
5426*67e74705SXin Li // the other has type "pointer to cv2 T" and the composite pointer type is
5427*67e74705SXin Li // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
5428*67e74705SXin Li // Otherwise, the composite pointer type is a pointer type similar to the
5429*67e74705SXin Li // type of one of the operands, with a cv-qualification signature that is
5430*67e74705SXin Li // the union of the cv-qualification signatures of the operand types.
5431*67e74705SXin Li // In practice, the first part here is redundant; it's subsumed by the second.
5432*67e74705SXin Li // What we do here is, we build the two possible composite types, and try the
5433*67e74705SXin Li // conversions in both directions. If only one works, or if the two composite
5434*67e74705SXin Li // types are the same, we have succeeded.
5435*67e74705SXin Li // FIXME: extended qualifiers?
5436*67e74705SXin Li typedef SmallVector<unsigned, 4> QualifierVector;
5437*67e74705SXin Li QualifierVector QualifierUnion;
5438*67e74705SXin Li typedef SmallVector<std::pair<const Type *, const Type *>, 4>
5439*67e74705SXin Li ContainingClassVector;
5440*67e74705SXin Li ContainingClassVector MemberOfClass;
5441*67e74705SXin Li QualType Composite1 = Context.getCanonicalType(T1),
5442*67e74705SXin Li Composite2 = Context.getCanonicalType(T2);
5443*67e74705SXin Li unsigned NeedConstBefore = 0;
5444*67e74705SXin Li do {
5445*67e74705SXin Li const PointerType *Ptr1, *Ptr2;
5446*67e74705SXin Li if ((Ptr1 = Composite1->getAs<PointerType>()) &&
5447*67e74705SXin Li (Ptr2 = Composite2->getAs<PointerType>())) {
5448*67e74705SXin Li Composite1 = Ptr1->getPointeeType();
5449*67e74705SXin Li Composite2 = Ptr2->getPointeeType();
5450*67e74705SXin Li
5451*67e74705SXin Li // If we're allowed to create a non-standard composite type, keep track
5452*67e74705SXin Li // of where we need to fill in additional 'const' qualifiers.
5453*67e74705SXin Li if (NonStandardCompositeType &&
5454*67e74705SXin Li Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
5455*67e74705SXin Li NeedConstBefore = QualifierUnion.size();
5456*67e74705SXin Li
5457*67e74705SXin Li QualifierUnion.push_back(
5458*67e74705SXin Li Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
5459*67e74705SXin Li MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
5460*67e74705SXin Li continue;
5461*67e74705SXin Li }
5462*67e74705SXin Li
5463*67e74705SXin Li const MemberPointerType *MemPtr1, *MemPtr2;
5464*67e74705SXin Li if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
5465*67e74705SXin Li (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
5466*67e74705SXin Li Composite1 = MemPtr1->getPointeeType();
5467*67e74705SXin Li Composite2 = MemPtr2->getPointeeType();
5468*67e74705SXin Li
5469*67e74705SXin Li // If we're allowed to create a non-standard composite type, keep track
5470*67e74705SXin Li // of where we need to fill in additional 'const' qualifiers.
5471*67e74705SXin Li if (NonStandardCompositeType &&
5472*67e74705SXin Li Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
5473*67e74705SXin Li NeedConstBefore = QualifierUnion.size();
5474*67e74705SXin Li
5475*67e74705SXin Li QualifierUnion.push_back(
5476*67e74705SXin Li Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
5477*67e74705SXin Li MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
5478*67e74705SXin Li MemPtr2->getClass()));
5479*67e74705SXin Li continue;
5480*67e74705SXin Li }
5481*67e74705SXin Li
5482*67e74705SXin Li // FIXME: block pointer types?
5483*67e74705SXin Li
5484*67e74705SXin Li // Cannot unwrap any more types.
5485*67e74705SXin Li break;
5486*67e74705SXin Li } while (true);
5487*67e74705SXin Li
5488*67e74705SXin Li if (NeedConstBefore && NonStandardCompositeType) {
5489*67e74705SXin Li // Extension: Add 'const' to qualifiers that come before the first qualifier
5490*67e74705SXin Li // mismatch, so that our (non-standard!) composite type meets the
5491*67e74705SXin Li // requirements of C++ [conv.qual]p4 bullet 3.
5492*67e74705SXin Li for (unsigned I = 0; I != NeedConstBefore; ++I) {
5493*67e74705SXin Li if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
5494*67e74705SXin Li QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
5495*67e74705SXin Li *NonStandardCompositeType = true;
5496*67e74705SXin Li }
5497*67e74705SXin Li }
5498*67e74705SXin Li }
5499*67e74705SXin Li
5500*67e74705SXin Li // Rewrap the composites as pointers or member pointers with the union CVRs.
5501*67e74705SXin Li ContainingClassVector::reverse_iterator MOC
5502*67e74705SXin Li = MemberOfClass.rbegin();
5503*67e74705SXin Li for (QualifierVector::reverse_iterator
5504*67e74705SXin Li I = QualifierUnion.rbegin(),
5505*67e74705SXin Li E = QualifierUnion.rend();
5506*67e74705SXin Li I != E; (void)++I, ++MOC) {
5507*67e74705SXin Li Qualifiers Quals = Qualifiers::fromCVRMask(*I);
5508*67e74705SXin Li if (MOC->first && MOC->second) {
5509*67e74705SXin Li // Rebuild member pointer type
5510*67e74705SXin Li Composite1 = Context.getMemberPointerType(
5511*67e74705SXin Li Context.getQualifiedType(Composite1, Quals),
5512*67e74705SXin Li MOC->first);
5513*67e74705SXin Li Composite2 = Context.getMemberPointerType(
5514*67e74705SXin Li Context.getQualifiedType(Composite2, Quals),
5515*67e74705SXin Li MOC->second);
5516*67e74705SXin Li } else {
5517*67e74705SXin Li // Rebuild pointer type
5518*67e74705SXin Li Composite1
5519*67e74705SXin Li = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
5520*67e74705SXin Li Composite2
5521*67e74705SXin Li = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
5522*67e74705SXin Li }
5523*67e74705SXin Li }
5524*67e74705SXin Li
5525*67e74705SXin Li // Try to convert to the first composite pointer type.
5526*67e74705SXin Li InitializedEntity Entity1
5527*67e74705SXin Li = InitializedEntity::InitializeTemporary(Composite1);
5528*67e74705SXin Li InitializationKind Kind
5529*67e74705SXin Li = InitializationKind::CreateCopy(Loc, SourceLocation());
5530*67e74705SXin Li InitializationSequence E1ToC1(*this, Entity1, Kind, E1);
5531*67e74705SXin Li InitializationSequence E2ToC1(*this, Entity1, Kind, E2);
5532*67e74705SXin Li
5533*67e74705SXin Li if (E1ToC1 && E2ToC1) {
5534*67e74705SXin Li // Conversion to Composite1 is viable.
5535*67e74705SXin Li if (!Context.hasSameType(Composite1, Composite2)) {
5536*67e74705SXin Li // Composite2 is a different type from Composite1. Check whether
5537*67e74705SXin Li // Composite2 is also viable.
5538*67e74705SXin Li InitializedEntity Entity2
5539*67e74705SXin Li = InitializedEntity::InitializeTemporary(Composite2);
5540*67e74705SXin Li InitializationSequence E1ToC2(*this, Entity2, Kind, E1);
5541*67e74705SXin Li InitializationSequence E2ToC2(*this, Entity2, Kind, E2);
5542*67e74705SXin Li if (E1ToC2 && E2ToC2) {
5543*67e74705SXin Li // Both Composite1 and Composite2 are viable and are different;
5544*67e74705SXin Li // this is an ambiguity.
5545*67e74705SXin Li return QualType();
5546*67e74705SXin Li }
5547*67e74705SXin Li }
5548*67e74705SXin Li
5549*67e74705SXin Li // Convert E1 to Composite1
5550*67e74705SXin Li ExprResult E1Result
5551*67e74705SXin Li = E1ToC1.Perform(*this, Entity1, Kind, E1);
5552*67e74705SXin Li if (E1Result.isInvalid())
5553*67e74705SXin Li return QualType();
5554*67e74705SXin Li E1 = E1Result.getAs<Expr>();
5555*67e74705SXin Li
5556*67e74705SXin Li // Convert E2 to Composite1
5557*67e74705SXin Li ExprResult E2Result
5558*67e74705SXin Li = E2ToC1.Perform(*this, Entity1, Kind, E2);
5559*67e74705SXin Li if (E2Result.isInvalid())
5560*67e74705SXin Li return QualType();
5561*67e74705SXin Li E2 = E2Result.getAs<Expr>();
5562*67e74705SXin Li
5563*67e74705SXin Li return Composite1;
5564*67e74705SXin Li }
5565*67e74705SXin Li
5566*67e74705SXin Li // Check whether Composite2 is viable.
5567*67e74705SXin Li InitializedEntity Entity2
5568*67e74705SXin Li = InitializedEntity::InitializeTemporary(Composite2);
5569*67e74705SXin Li InitializationSequence E1ToC2(*this, Entity2, Kind, E1);
5570*67e74705SXin Li InitializationSequence E2ToC2(*this, Entity2, Kind, E2);
5571*67e74705SXin Li if (!E1ToC2 || !E2ToC2)
5572*67e74705SXin Li return QualType();
5573*67e74705SXin Li
5574*67e74705SXin Li // Convert E1 to Composite2
5575*67e74705SXin Li ExprResult E1Result
5576*67e74705SXin Li = E1ToC2.Perform(*this, Entity2, Kind, E1);
5577*67e74705SXin Li if (E1Result.isInvalid())
5578*67e74705SXin Li return QualType();
5579*67e74705SXin Li E1 = E1Result.getAs<Expr>();
5580*67e74705SXin Li
5581*67e74705SXin Li // Convert E2 to Composite2
5582*67e74705SXin Li ExprResult E2Result
5583*67e74705SXin Li = E2ToC2.Perform(*this, Entity2, Kind, E2);
5584*67e74705SXin Li if (E2Result.isInvalid())
5585*67e74705SXin Li return QualType();
5586*67e74705SXin Li E2 = E2Result.getAs<Expr>();
5587*67e74705SXin Li
5588*67e74705SXin Li return Composite2;
5589*67e74705SXin Li }
5590*67e74705SXin Li
MaybeBindToTemporary(Expr * E)5591*67e74705SXin Li ExprResult Sema::MaybeBindToTemporary(Expr *E) {
5592*67e74705SXin Li if (!E)
5593*67e74705SXin Li return ExprError();
5594*67e74705SXin Li
5595*67e74705SXin Li assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
5596*67e74705SXin Li
5597*67e74705SXin Li // If the result is a glvalue, we shouldn't bind it.
5598*67e74705SXin Li if (!E->isRValue())
5599*67e74705SXin Li return E;
5600*67e74705SXin Li
5601*67e74705SXin Li // In ARC, calls that return a retainable type can return retained,
5602*67e74705SXin Li // in which case we have to insert a consuming cast.
5603*67e74705SXin Li if (getLangOpts().ObjCAutoRefCount &&
5604*67e74705SXin Li E->getType()->isObjCRetainableType()) {
5605*67e74705SXin Li
5606*67e74705SXin Li bool ReturnsRetained;
5607*67e74705SXin Li
5608*67e74705SXin Li // For actual calls, we compute this by examining the type of the
5609*67e74705SXin Li // called value.
5610*67e74705SXin Li if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
5611*67e74705SXin Li Expr *Callee = Call->getCallee()->IgnoreParens();
5612*67e74705SXin Li QualType T = Callee->getType();
5613*67e74705SXin Li
5614*67e74705SXin Li if (T == Context.BoundMemberTy) {
5615*67e74705SXin Li // Handle pointer-to-members.
5616*67e74705SXin Li if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
5617*67e74705SXin Li T = BinOp->getRHS()->getType();
5618*67e74705SXin Li else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
5619*67e74705SXin Li T = Mem->getMemberDecl()->getType();
5620*67e74705SXin Li }
5621*67e74705SXin Li
5622*67e74705SXin Li if (const PointerType *Ptr = T->getAs<PointerType>())
5623*67e74705SXin Li T = Ptr->getPointeeType();
5624*67e74705SXin Li else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
5625*67e74705SXin Li T = Ptr->getPointeeType();
5626*67e74705SXin Li else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
5627*67e74705SXin Li T = MemPtr->getPointeeType();
5628*67e74705SXin Li
5629*67e74705SXin Li const FunctionType *FTy = T->getAs<FunctionType>();
5630*67e74705SXin Li assert(FTy && "call to value not of function type?");
5631*67e74705SXin Li ReturnsRetained = FTy->getExtInfo().getProducesResult();
5632*67e74705SXin Li
5633*67e74705SXin Li // ActOnStmtExpr arranges things so that StmtExprs of retainable
5634*67e74705SXin Li // type always produce a +1 object.
5635*67e74705SXin Li } else if (isa<StmtExpr>(E)) {
5636*67e74705SXin Li ReturnsRetained = true;
5637*67e74705SXin Li
5638*67e74705SXin Li // We hit this case with the lambda conversion-to-block optimization;
5639*67e74705SXin Li // we don't want any extra casts here.
5640*67e74705SXin Li } else if (isa<CastExpr>(E) &&
5641*67e74705SXin Li isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
5642*67e74705SXin Li return E;
5643*67e74705SXin Li
5644*67e74705SXin Li // For message sends and property references, we try to find an
5645*67e74705SXin Li // actual method. FIXME: we should infer retention by selector in
5646*67e74705SXin Li // cases where we don't have an actual method.
5647*67e74705SXin Li } else {
5648*67e74705SXin Li ObjCMethodDecl *D = nullptr;
5649*67e74705SXin Li if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
5650*67e74705SXin Li D = Send->getMethodDecl();
5651*67e74705SXin Li } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
5652*67e74705SXin Li D = BoxedExpr->getBoxingMethod();
5653*67e74705SXin Li } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
5654*67e74705SXin Li D = ArrayLit->getArrayWithObjectsMethod();
5655*67e74705SXin Li } else if (ObjCDictionaryLiteral *DictLit
5656*67e74705SXin Li = dyn_cast<ObjCDictionaryLiteral>(E)) {
5657*67e74705SXin Li D = DictLit->getDictWithObjectsMethod();
5658*67e74705SXin Li }
5659*67e74705SXin Li
5660*67e74705SXin Li ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
5661*67e74705SXin Li
5662*67e74705SXin Li // Don't do reclaims on performSelector calls; despite their
5663*67e74705SXin Li // return type, the invoked method doesn't necessarily actually
5664*67e74705SXin Li // return an object.
5665*67e74705SXin Li if (!ReturnsRetained &&
5666*67e74705SXin Li D && D->getMethodFamily() == OMF_performSelector)
5667*67e74705SXin Li return E;
5668*67e74705SXin Li }
5669*67e74705SXin Li
5670*67e74705SXin Li // Don't reclaim an object of Class type.
5671*67e74705SXin Li if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
5672*67e74705SXin Li return E;
5673*67e74705SXin Li
5674*67e74705SXin Li Cleanup.setExprNeedsCleanups(true);
5675*67e74705SXin Li
5676*67e74705SXin Li CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
5677*67e74705SXin Li : CK_ARCReclaimReturnedObject);
5678*67e74705SXin Li return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
5679*67e74705SXin Li VK_RValue);
5680*67e74705SXin Li }
5681*67e74705SXin Li
5682*67e74705SXin Li if (!getLangOpts().CPlusPlus)
5683*67e74705SXin Li return E;
5684*67e74705SXin Li
5685*67e74705SXin Li // Search for the base element type (cf. ASTContext::getBaseElementType) with
5686*67e74705SXin Li // a fast path for the common case that the type is directly a RecordType.
5687*67e74705SXin Li const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
5688*67e74705SXin Li const RecordType *RT = nullptr;
5689*67e74705SXin Li while (!RT) {
5690*67e74705SXin Li switch (T->getTypeClass()) {
5691*67e74705SXin Li case Type::Record:
5692*67e74705SXin Li RT = cast<RecordType>(T);
5693*67e74705SXin Li break;
5694*67e74705SXin Li case Type::ConstantArray:
5695*67e74705SXin Li case Type::IncompleteArray:
5696*67e74705SXin Li case Type::VariableArray:
5697*67e74705SXin Li case Type::DependentSizedArray:
5698*67e74705SXin Li T = cast<ArrayType>(T)->getElementType().getTypePtr();
5699*67e74705SXin Li break;
5700*67e74705SXin Li default:
5701*67e74705SXin Li return E;
5702*67e74705SXin Li }
5703*67e74705SXin Li }
5704*67e74705SXin Li
5705*67e74705SXin Li // That should be enough to guarantee that this type is complete, if we're
5706*67e74705SXin Li // not processing a decltype expression.
5707*67e74705SXin Li CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
5708*67e74705SXin Li if (RD->isInvalidDecl() || RD->isDependentContext())
5709*67e74705SXin Li return E;
5710*67e74705SXin Li
5711*67e74705SXin Li bool IsDecltype = ExprEvalContexts.back().IsDecltype;
5712*67e74705SXin Li CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
5713*67e74705SXin Li
5714*67e74705SXin Li if (Destructor) {
5715*67e74705SXin Li MarkFunctionReferenced(E->getExprLoc(), Destructor);
5716*67e74705SXin Li CheckDestructorAccess(E->getExprLoc(), Destructor,
5717*67e74705SXin Li PDiag(diag::err_access_dtor_temp)
5718*67e74705SXin Li << E->getType());
5719*67e74705SXin Li if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
5720*67e74705SXin Li return ExprError();
5721*67e74705SXin Li
5722*67e74705SXin Li // If destructor is trivial, we can avoid the extra copy.
5723*67e74705SXin Li if (Destructor->isTrivial())
5724*67e74705SXin Li return E;
5725*67e74705SXin Li
5726*67e74705SXin Li // We need a cleanup, but we don't need to remember the temporary.
5727*67e74705SXin Li Cleanup.setExprNeedsCleanups(true);
5728*67e74705SXin Li }
5729*67e74705SXin Li
5730*67e74705SXin Li CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
5731*67e74705SXin Li CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
5732*67e74705SXin Li
5733*67e74705SXin Li if (IsDecltype)
5734*67e74705SXin Li ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
5735*67e74705SXin Li
5736*67e74705SXin Li return Bind;
5737*67e74705SXin Li }
5738*67e74705SXin Li
5739*67e74705SXin Li ExprResult
MaybeCreateExprWithCleanups(ExprResult SubExpr)5740*67e74705SXin Li Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
5741*67e74705SXin Li if (SubExpr.isInvalid())
5742*67e74705SXin Li return ExprError();
5743*67e74705SXin Li
5744*67e74705SXin Li return MaybeCreateExprWithCleanups(SubExpr.get());
5745*67e74705SXin Li }
5746*67e74705SXin Li
MaybeCreateExprWithCleanups(Expr * SubExpr)5747*67e74705SXin Li Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
5748*67e74705SXin Li assert(SubExpr && "subexpression can't be null!");
5749*67e74705SXin Li
5750*67e74705SXin Li CleanupVarDeclMarking();
5751*67e74705SXin Li
5752*67e74705SXin Li unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
5753*67e74705SXin Li assert(ExprCleanupObjects.size() >= FirstCleanup);
5754*67e74705SXin Li assert(Cleanup.exprNeedsCleanups() ||
5755*67e74705SXin Li ExprCleanupObjects.size() == FirstCleanup);
5756*67e74705SXin Li if (!Cleanup.exprNeedsCleanups())
5757*67e74705SXin Li return SubExpr;
5758*67e74705SXin Li
5759*67e74705SXin Li auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
5760*67e74705SXin Li ExprCleanupObjects.size() - FirstCleanup);
5761*67e74705SXin Li
5762*67e74705SXin Li auto *E = ExprWithCleanups::Create(
5763*67e74705SXin Li Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
5764*67e74705SXin Li DiscardCleanupsInEvaluationContext();
5765*67e74705SXin Li
5766*67e74705SXin Li return E;
5767*67e74705SXin Li }
5768*67e74705SXin Li
MaybeCreateStmtWithCleanups(Stmt * SubStmt)5769*67e74705SXin Li Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
5770*67e74705SXin Li assert(SubStmt && "sub-statement can't be null!");
5771*67e74705SXin Li
5772*67e74705SXin Li CleanupVarDeclMarking();
5773*67e74705SXin Li
5774*67e74705SXin Li if (!Cleanup.exprNeedsCleanups())
5775*67e74705SXin Li return SubStmt;
5776*67e74705SXin Li
5777*67e74705SXin Li // FIXME: In order to attach the temporaries, wrap the statement into
5778*67e74705SXin Li // a StmtExpr; currently this is only used for asm statements.
5779*67e74705SXin Li // This is hacky, either create a new CXXStmtWithTemporaries statement or
5780*67e74705SXin Li // a new AsmStmtWithTemporaries.
5781*67e74705SXin Li CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, SubStmt,
5782*67e74705SXin Li SourceLocation(),
5783*67e74705SXin Li SourceLocation());
5784*67e74705SXin Li Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
5785*67e74705SXin Li SourceLocation());
5786*67e74705SXin Li return MaybeCreateExprWithCleanups(E);
5787*67e74705SXin Li }
5788*67e74705SXin Li
5789*67e74705SXin Li /// Process the expression contained within a decltype. For such expressions,
5790*67e74705SXin Li /// certain semantic checks on temporaries are delayed until this point, and
5791*67e74705SXin Li /// are omitted for the 'topmost' call in the decltype expression. If the
5792*67e74705SXin Li /// topmost call bound a temporary, strip that temporary off the expression.
ActOnDecltypeExpression(Expr * E)5793*67e74705SXin Li ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
5794*67e74705SXin Li assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression");
5795*67e74705SXin Li
5796*67e74705SXin Li // C++11 [expr.call]p11:
5797*67e74705SXin Li // If a function call is a prvalue of object type,
5798*67e74705SXin Li // -- if the function call is either
5799*67e74705SXin Li // -- the operand of a decltype-specifier, or
5800*67e74705SXin Li // -- the right operand of a comma operator that is the operand of a
5801*67e74705SXin Li // decltype-specifier,
5802*67e74705SXin Li // a temporary object is not introduced for the prvalue.
5803*67e74705SXin Li
5804*67e74705SXin Li // Recursively rebuild ParenExprs and comma expressions to strip out the
5805*67e74705SXin Li // outermost CXXBindTemporaryExpr, if any.
5806*67e74705SXin Li if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
5807*67e74705SXin Li ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
5808*67e74705SXin Li if (SubExpr.isInvalid())
5809*67e74705SXin Li return ExprError();
5810*67e74705SXin Li if (SubExpr.get() == PE->getSubExpr())
5811*67e74705SXin Li return E;
5812*67e74705SXin Li return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
5813*67e74705SXin Li }
5814*67e74705SXin Li if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5815*67e74705SXin Li if (BO->getOpcode() == BO_Comma) {
5816*67e74705SXin Li ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
5817*67e74705SXin Li if (RHS.isInvalid())
5818*67e74705SXin Li return ExprError();
5819*67e74705SXin Li if (RHS.get() == BO->getRHS())
5820*67e74705SXin Li return E;
5821*67e74705SXin Li return new (Context) BinaryOperator(
5822*67e74705SXin Li BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
5823*67e74705SXin Li BO->getObjectKind(), BO->getOperatorLoc(), BO->isFPContractable());
5824*67e74705SXin Li }
5825*67e74705SXin Li }
5826*67e74705SXin Li
5827*67e74705SXin Li CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
5828*67e74705SXin Li CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
5829*67e74705SXin Li : nullptr;
5830*67e74705SXin Li if (TopCall)
5831*67e74705SXin Li E = TopCall;
5832*67e74705SXin Li else
5833*67e74705SXin Li TopBind = nullptr;
5834*67e74705SXin Li
5835*67e74705SXin Li // Disable the special decltype handling now.
5836*67e74705SXin Li ExprEvalContexts.back().IsDecltype = false;
5837*67e74705SXin Li
5838*67e74705SXin Li // In MS mode, don't perform any extra checking of call return types within a
5839*67e74705SXin Li // decltype expression.
5840*67e74705SXin Li if (getLangOpts().MSVCCompat)
5841*67e74705SXin Li return E;
5842*67e74705SXin Li
5843*67e74705SXin Li // Perform the semantic checks we delayed until this point.
5844*67e74705SXin Li for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
5845*67e74705SXin Li I != N; ++I) {
5846*67e74705SXin Li CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
5847*67e74705SXin Li if (Call == TopCall)
5848*67e74705SXin Li continue;
5849*67e74705SXin Li
5850*67e74705SXin Li if (CheckCallReturnType(Call->getCallReturnType(Context),
5851*67e74705SXin Li Call->getLocStart(),
5852*67e74705SXin Li Call, Call->getDirectCallee()))
5853*67e74705SXin Li return ExprError();
5854*67e74705SXin Li }
5855*67e74705SXin Li
5856*67e74705SXin Li // Now all relevant types are complete, check the destructors are accessible
5857*67e74705SXin Li // and non-deleted, and annotate them on the temporaries.
5858*67e74705SXin Li for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
5859*67e74705SXin Li I != N; ++I) {
5860*67e74705SXin Li CXXBindTemporaryExpr *Bind =
5861*67e74705SXin Li ExprEvalContexts.back().DelayedDecltypeBinds[I];
5862*67e74705SXin Li if (Bind == TopBind)
5863*67e74705SXin Li continue;
5864*67e74705SXin Li
5865*67e74705SXin Li CXXTemporary *Temp = Bind->getTemporary();
5866*67e74705SXin Li
5867*67e74705SXin Li CXXRecordDecl *RD =
5868*67e74705SXin Li Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5869*67e74705SXin Li CXXDestructorDecl *Destructor = LookupDestructor(RD);
5870*67e74705SXin Li Temp->setDestructor(Destructor);
5871*67e74705SXin Li
5872*67e74705SXin Li MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
5873*67e74705SXin Li CheckDestructorAccess(Bind->getExprLoc(), Destructor,
5874*67e74705SXin Li PDiag(diag::err_access_dtor_temp)
5875*67e74705SXin Li << Bind->getType());
5876*67e74705SXin Li if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
5877*67e74705SXin Li return ExprError();
5878*67e74705SXin Li
5879*67e74705SXin Li // We need a cleanup, but we don't need to remember the temporary.
5880*67e74705SXin Li Cleanup.setExprNeedsCleanups(true);
5881*67e74705SXin Li }
5882*67e74705SXin Li
5883*67e74705SXin Li // Possibly strip off the top CXXBindTemporaryExpr.
5884*67e74705SXin Li return E;
5885*67e74705SXin Li }
5886*67e74705SXin Li
5887*67e74705SXin Li /// Note a set of 'operator->' functions that were used for a member access.
noteOperatorArrows(Sema & S,ArrayRef<FunctionDecl * > OperatorArrows)5888*67e74705SXin Li static void noteOperatorArrows(Sema &S,
5889*67e74705SXin Li ArrayRef<FunctionDecl *> OperatorArrows) {
5890*67e74705SXin Li unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
5891*67e74705SXin Li // FIXME: Make this configurable?
5892*67e74705SXin Li unsigned Limit = 9;
5893*67e74705SXin Li if (OperatorArrows.size() > Limit) {
5894*67e74705SXin Li // Produce Limit-1 normal notes and one 'skipping' note.
5895*67e74705SXin Li SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
5896*67e74705SXin Li SkipCount = OperatorArrows.size() - (Limit - 1);
5897*67e74705SXin Li }
5898*67e74705SXin Li
5899*67e74705SXin Li for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
5900*67e74705SXin Li if (I == SkipStart) {
5901*67e74705SXin Li S.Diag(OperatorArrows[I]->getLocation(),
5902*67e74705SXin Li diag::note_operator_arrows_suppressed)
5903*67e74705SXin Li << SkipCount;
5904*67e74705SXin Li I += SkipCount;
5905*67e74705SXin Li } else {
5906*67e74705SXin Li S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
5907*67e74705SXin Li << OperatorArrows[I]->getCallResultType();
5908*67e74705SXin Li ++I;
5909*67e74705SXin Li }
5910*67e74705SXin Li }
5911*67e74705SXin Li }
5912*67e74705SXin Li
ActOnStartCXXMemberReference(Scope * S,Expr * Base,SourceLocation OpLoc,tok::TokenKind OpKind,ParsedType & ObjectType,bool & MayBePseudoDestructor)5913*67e74705SXin Li ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
5914*67e74705SXin Li SourceLocation OpLoc,
5915*67e74705SXin Li tok::TokenKind OpKind,
5916*67e74705SXin Li ParsedType &ObjectType,
5917*67e74705SXin Li bool &MayBePseudoDestructor) {
5918*67e74705SXin Li // Since this might be a postfix expression, get rid of ParenListExprs.
5919*67e74705SXin Li ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
5920*67e74705SXin Li if (Result.isInvalid()) return ExprError();
5921*67e74705SXin Li Base = Result.get();
5922*67e74705SXin Li
5923*67e74705SXin Li Result = CheckPlaceholderExpr(Base);
5924*67e74705SXin Li if (Result.isInvalid()) return ExprError();
5925*67e74705SXin Li Base = Result.get();
5926*67e74705SXin Li
5927*67e74705SXin Li QualType BaseType = Base->getType();
5928*67e74705SXin Li MayBePseudoDestructor = false;
5929*67e74705SXin Li if (BaseType->isDependentType()) {
5930*67e74705SXin Li // If we have a pointer to a dependent type and are using the -> operator,
5931*67e74705SXin Li // the object type is the type that the pointer points to. We might still
5932*67e74705SXin Li // have enough information about that type to do something useful.
5933*67e74705SXin Li if (OpKind == tok::arrow)
5934*67e74705SXin Li if (const PointerType *Ptr = BaseType->getAs<PointerType>())
5935*67e74705SXin Li BaseType = Ptr->getPointeeType();
5936*67e74705SXin Li
5937*67e74705SXin Li ObjectType = ParsedType::make(BaseType);
5938*67e74705SXin Li MayBePseudoDestructor = true;
5939*67e74705SXin Li return Base;
5940*67e74705SXin Li }
5941*67e74705SXin Li
5942*67e74705SXin Li // C++ [over.match.oper]p8:
5943*67e74705SXin Li // [...] When operator->returns, the operator-> is applied to the value
5944*67e74705SXin Li // returned, with the original second operand.
5945*67e74705SXin Li if (OpKind == tok::arrow) {
5946*67e74705SXin Li QualType StartingType = BaseType;
5947*67e74705SXin Li bool NoArrowOperatorFound = false;
5948*67e74705SXin Li bool FirstIteration = true;
5949*67e74705SXin Li FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
5950*67e74705SXin Li // The set of types we've considered so far.
5951*67e74705SXin Li llvm::SmallPtrSet<CanQualType,8> CTypes;
5952*67e74705SXin Li SmallVector<FunctionDecl*, 8> OperatorArrows;
5953*67e74705SXin Li CTypes.insert(Context.getCanonicalType(BaseType));
5954*67e74705SXin Li
5955*67e74705SXin Li while (BaseType->isRecordType()) {
5956*67e74705SXin Li if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
5957*67e74705SXin Li Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
5958*67e74705SXin Li << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
5959*67e74705SXin Li noteOperatorArrows(*this, OperatorArrows);
5960*67e74705SXin Li Diag(OpLoc, diag::note_operator_arrow_depth)
5961*67e74705SXin Li << getLangOpts().ArrowDepth;
5962*67e74705SXin Li return ExprError();
5963*67e74705SXin Li }
5964*67e74705SXin Li
5965*67e74705SXin Li Result = BuildOverloadedArrowExpr(
5966*67e74705SXin Li S, Base, OpLoc,
5967*67e74705SXin Li // When in a template specialization and on the first loop iteration,
5968*67e74705SXin Li // potentially give the default diagnostic (with the fixit in a
5969*67e74705SXin Li // separate note) instead of having the error reported back to here
5970*67e74705SXin Li // and giving a diagnostic with a fixit attached to the error itself.
5971*67e74705SXin Li (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
5972*67e74705SXin Li ? nullptr
5973*67e74705SXin Li : &NoArrowOperatorFound);
5974*67e74705SXin Li if (Result.isInvalid()) {
5975*67e74705SXin Li if (NoArrowOperatorFound) {
5976*67e74705SXin Li if (FirstIteration) {
5977*67e74705SXin Li Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
5978*67e74705SXin Li << BaseType << 1 << Base->getSourceRange()
5979*67e74705SXin Li << FixItHint::CreateReplacement(OpLoc, ".");
5980*67e74705SXin Li OpKind = tok::period;
5981*67e74705SXin Li break;
5982*67e74705SXin Li }
5983*67e74705SXin Li Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
5984*67e74705SXin Li << BaseType << Base->getSourceRange();
5985*67e74705SXin Li CallExpr *CE = dyn_cast<CallExpr>(Base);
5986*67e74705SXin Li if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
5987*67e74705SXin Li Diag(CD->getLocStart(),
5988*67e74705SXin Li diag::note_member_reference_arrow_from_operator_arrow);
5989*67e74705SXin Li }
5990*67e74705SXin Li }
5991*67e74705SXin Li return ExprError();
5992*67e74705SXin Li }
5993*67e74705SXin Li Base = Result.get();
5994*67e74705SXin Li if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
5995*67e74705SXin Li OperatorArrows.push_back(OpCall->getDirectCallee());
5996*67e74705SXin Li BaseType = Base->getType();
5997*67e74705SXin Li CanQualType CBaseType = Context.getCanonicalType(BaseType);
5998*67e74705SXin Li if (!CTypes.insert(CBaseType).second) {
5999*67e74705SXin Li Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
6000*67e74705SXin Li noteOperatorArrows(*this, OperatorArrows);
6001*67e74705SXin Li return ExprError();
6002*67e74705SXin Li }
6003*67e74705SXin Li FirstIteration = false;
6004*67e74705SXin Li }
6005*67e74705SXin Li
6006*67e74705SXin Li if (OpKind == tok::arrow &&
6007*67e74705SXin Li (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
6008*67e74705SXin Li BaseType = BaseType->getPointeeType();
6009*67e74705SXin Li }
6010*67e74705SXin Li
6011*67e74705SXin Li // Objective-C properties allow "." access on Objective-C pointer types,
6012*67e74705SXin Li // so adjust the base type to the object type itself.
6013*67e74705SXin Li if (BaseType->isObjCObjectPointerType())
6014*67e74705SXin Li BaseType = BaseType->getPointeeType();
6015*67e74705SXin Li
6016*67e74705SXin Li // C++ [basic.lookup.classref]p2:
6017*67e74705SXin Li // [...] If the type of the object expression is of pointer to scalar
6018*67e74705SXin Li // type, the unqualified-id is looked up in the context of the complete
6019*67e74705SXin Li // postfix-expression.
6020*67e74705SXin Li //
6021*67e74705SXin Li // This also indicates that we could be parsing a pseudo-destructor-name.
6022*67e74705SXin Li // Note that Objective-C class and object types can be pseudo-destructor
6023*67e74705SXin Li // expressions or normal member (ivar or property) access expressions, and
6024*67e74705SXin Li // it's legal for the type to be incomplete if this is a pseudo-destructor
6025*67e74705SXin Li // call. We'll do more incomplete-type checks later in the lookup process,
6026*67e74705SXin Li // so just skip this check for ObjC types.
6027*67e74705SXin Li if (BaseType->isObjCObjectOrInterfaceType()) {
6028*67e74705SXin Li ObjectType = ParsedType::make(BaseType);
6029*67e74705SXin Li MayBePseudoDestructor = true;
6030*67e74705SXin Li return Base;
6031*67e74705SXin Li } else if (!BaseType->isRecordType()) {
6032*67e74705SXin Li ObjectType = nullptr;
6033*67e74705SXin Li MayBePseudoDestructor = true;
6034*67e74705SXin Li return Base;
6035*67e74705SXin Li }
6036*67e74705SXin Li
6037*67e74705SXin Li // The object type must be complete (or dependent), or
6038*67e74705SXin Li // C++11 [expr.prim.general]p3:
6039*67e74705SXin Li // Unlike the object expression in other contexts, *this is not required to
6040*67e74705SXin Li // be of complete type for purposes of class member access (5.2.5) outside
6041*67e74705SXin Li // the member function body.
6042*67e74705SXin Li if (!BaseType->isDependentType() &&
6043*67e74705SXin Li !isThisOutsideMemberFunctionBody(BaseType) &&
6044*67e74705SXin Li RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
6045*67e74705SXin Li return ExprError();
6046*67e74705SXin Li
6047*67e74705SXin Li // C++ [basic.lookup.classref]p2:
6048*67e74705SXin Li // If the id-expression in a class member access (5.2.5) is an
6049*67e74705SXin Li // unqualified-id, and the type of the object expression is of a class
6050*67e74705SXin Li // type C (or of pointer to a class type C), the unqualified-id is looked
6051*67e74705SXin Li // up in the scope of class C. [...]
6052*67e74705SXin Li ObjectType = ParsedType::make(BaseType);
6053*67e74705SXin Li return Base;
6054*67e74705SXin Li }
6055*67e74705SXin Li
CheckArrow(Sema & S,QualType & ObjectType,Expr * & Base,tok::TokenKind & OpKind,SourceLocation OpLoc)6056*67e74705SXin Li static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
6057*67e74705SXin Li tok::TokenKind& OpKind, SourceLocation OpLoc) {
6058*67e74705SXin Li if (Base->hasPlaceholderType()) {
6059*67e74705SXin Li ExprResult result = S.CheckPlaceholderExpr(Base);
6060*67e74705SXin Li if (result.isInvalid()) return true;
6061*67e74705SXin Li Base = result.get();
6062*67e74705SXin Li }
6063*67e74705SXin Li ObjectType = Base->getType();
6064*67e74705SXin Li
6065*67e74705SXin Li // C++ [expr.pseudo]p2:
6066*67e74705SXin Li // The left-hand side of the dot operator shall be of scalar type. The
6067*67e74705SXin Li // left-hand side of the arrow operator shall be of pointer to scalar type.
6068*67e74705SXin Li // This scalar type is the object type.
6069*67e74705SXin Li // Note that this is rather different from the normal handling for the
6070*67e74705SXin Li // arrow operator.
6071*67e74705SXin Li if (OpKind == tok::arrow) {
6072*67e74705SXin Li if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
6073*67e74705SXin Li ObjectType = Ptr->getPointeeType();
6074*67e74705SXin Li } else if (!Base->isTypeDependent()) {
6075*67e74705SXin Li // The user wrote "p->" when they probably meant "p."; fix it.
6076*67e74705SXin Li S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6077*67e74705SXin Li << ObjectType << true
6078*67e74705SXin Li << FixItHint::CreateReplacement(OpLoc, ".");
6079*67e74705SXin Li if (S.isSFINAEContext())
6080*67e74705SXin Li return true;
6081*67e74705SXin Li
6082*67e74705SXin Li OpKind = tok::period;
6083*67e74705SXin Li }
6084*67e74705SXin Li }
6085*67e74705SXin Li
6086*67e74705SXin Li return false;
6087*67e74705SXin Li }
6088*67e74705SXin Li
BuildPseudoDestructorExpr(Expr * Base,SourceLocation OpLoc,tok::TokenKind OpKind,const CXXScopeSpec & SS,TypeSourceInfo * ScopeTypeInfo,SourceLocation CCLoc,SourceLocation TildeLoc,PseudoDestructorTypeStorage Destructed)6089*67e74705SXin Li ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
6090*67e74705SXin Li SourceLocation OpLoc,
6091*67e74705SXin Li tok::TokenKind OpKind,
6092*67e74705SXin Li const CXXScopeSpec &SS,
6093*67e74705SXin Li TypeSourceInfo *ScopeTypeInfo,
6094*67e74705SXin Li SourceLocation CCLoc,
6095*67e74705SXin Li SourceLocation TildeLoc,
6096*67e74705SXin Li PseudoDestructorTypeStorage Destructed) {
6097*67e74705SXin Li TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
6098*67e74705SXin Li
6099*67e74705SXin Li QualType ObjectType;
6100*67e74705SXin Li if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6101*67e74705SXin Li return ExprError();
6102*67e74705SXin Li
6103*67e74705SXin Li if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
6104*67e74705SXin Li !ObjectType->isVectorType()) {
6105*67e74705SXin Li if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
6106*67e74705SXin Li Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
6107*67e74705SXin Li else {
6108*67e74705SXin Li Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
6109*67e74705SXin Li << ObjectType << Base->getSourceRange();
6110*67e74705SXin Li return ExprError();
6111*67e74705SXin Li }
6112*67e74705SXin Li }
6113*67e74705SXin Li
6114*67e74705SXin Li // C++ [expr.pseudo]p2:
6115*67e74705SXin Li // [...] The cv-unqualified versions of the object type and of the type
6116*67e74705SXin Li // designated by the pseudo-destructor-name shall be the same type.
6117*67e74705SXin Li if (DestructedTypeInfo) {
6118*67e74705SXin Li QualType DestructedType = DestructedTypeInfo->getType();
6119*67e74705SXin Li SourceLocation DestructedTypeStart
6120*67e74705SXin Li = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
6121*67e74705SXin Li if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
6122*67e74705SXin Li if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
6123*67e74705SXin Li Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
6124*67e74705SXin Li << ObjectType << DestructedType << Base->getSourceRange()
6125*67e74705SXin Li << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6126*67e74705SXin Li
6127*67e74705SXin Li // Recover by setting the destructed type to the object type.
6128*67e74705SXin Li DestructedType = ObjectType;
6129*67e74705SXin Li DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6130*67e74705SXin Li DestructedTypeStart);
6131*67e74705SXin Li Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6132*67e74705SXin Li } else if (DestructedType.getObjCLifetime() !=
6133*67e74705SXin Li ObjectType.getObjCLifetime()) {
6134*67e74705SXin Li
6135*67e74705SXin Li if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
6136*67e74705SXin Li // Okay: just pretend that the user provided the correctly-qualified
6137*67e74705SXin Li // type.
6138*67e74705SXin Li } else {
6139*67e74705SXin Li Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
6140*67e74705SXin Li << ObjectType << DestructedType << Base->getSourceRange()
6141*67e74705SXin Li << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6142*67e74705SXin Li }
6143*67e74705SXin Li
6144*67e74705SXin Li // Recover by setting the destructed type to the object type.
6145*67e74705SXin Li DestructedType = ObjectType;
6146*67e74705SXin Li DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6147*67e74705SXin Li DestructedTypeStart);
6148*67e74705SXin Li Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6149*67e74705SXin Li }
6150*67e74705SXin Li }
6151*67e74705SXin Li }
6152*67e74705SXin Li
6153*67e74705SXin Li // C++ [expr.pseudo]p2:
6154*67e74705SXin Li // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
6155*67e74705SXin Li // form
6156*67e74705SXin Li //
6157*67e74705SXin Li // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
6158*67e74705SXin Li //
6159*67e74705SXin Li // shall designate the same scalar type.
6160*67e74705SXin Li if (ScopeTypeInfo) {
6161*67e74705SXin Li QualType ScopeType = ScopeTypeInfo->getType();
6162*67e74705SXin Li if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
6163*67e74705SXin Li !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
6164*67e74705SXin Li
6165*67e74705SXin Li Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
6166*67e74705SXin Li diag::err_pseudo_dtor_type_mismatch)
6167*67e74705SXin Li << ObjectType << ScopeType << Base->getSourceRange()
6168*67e74705SXin Li << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
6169*67e74705SXin Li
6170*67e74705SXin Li ScopeType = QualType();
6171*67e74705SXin Li ScopeTypeInfo = nullptr;
6172*67e74705SXin Li }
6173*67e74705SXin Li }
6174*67e74705SXin Li
6175*67e74705SXin Li Expr *Result
6176*67e74705SXin Li = new (Context) CXXPseudoDestructorExpr(Context, Base,
6177*67e74705SXin Li OpKind == tok::arrow, OpLoc,
6178*67e74705SXin Li SS.getWithLocInContext(Context),
6179*67e74705SXin Li ScopeTypeInfo,
6180*67e74705SXin Li CCLoc,
6181*67e74705SXin Li TildeLoc,
6182*67e74705SXin Li Destructed);
6183*67e74705SXin Li
6184*67e74705SXin Li return Result;
6185*67e74705SXin Li }
6186*67e74705SXin Li
ActOnPseudoDestructorExpr(Scope * S,Expr * Base,SourceLocation OpLoc,tok::TokenKind OpKind,CXXScopeSpec & SS,UnqualifiedId & FirstTypeName,SourceLocation CCLoc,SourceLocation TildeLoc,UnqualifiedId & SecondTypeName)6187*67e74705SXin Li ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6188*67e74705SXin Li SourceLocation OpLoc,
6189*67e74705SXin Li tok::TokenKind OpKind,
6190*67e74705SXin Li CXXScopeSpec &SS,
6191*67e74705SXin Li UnqualifiedId &FirstTypeName,
6192*67e74705SXin Li SourceLocation CCLoc,
6193*67e74705SXin Li SourceLocation TildeLoc,
6194*67e74705SXin Li UnqualifiedId &SecondTypeName) {
6195*67e74705SXin Li assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6196*67e74705SXin Li FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
6197*67e74705SXin Li "Invalid first type name in pseudo-destructor");
6198*67e74705SXin Li assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6199*67e74705SXin Li SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
6200*67e74705SXin Li "Invalid second type name in pseudo-destructor");
6201*67e74705SXin Li
6202*67e74705SXin Li QualType ObjectType;
6203*67e74705SXin Li if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6204*67e74705SXin Li return ExprError();
6205*67e74705SXin Li
6206*67e74705SXin Li // Compute the object type that we should use for name lookup purposes. Only
6207*67e74705SXin Li // record types and dependent types matter.
6208*67e74705SXin Li ParsedType ObjectTypePtrForLookup;
6209*67e74705SXin Li if (!SS.isSet()) {
6210*67e74705SXin Li if (ObjectType->isRecordType())
6211*67e74705SXin Li ObjectTypePtrForLookup = ParsedType::make(ObjectType);
6212*67e74705SXin Li else if (ObjectType->isDependentType())
6213*67e74705SXin Li ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
6214*67e74705SXin Li }
6215*67e74705SXin Li
6216*67e74705SXin Li // Convert the name of the type being destructed (following the ~) into a
6217*67e74705SXin Li // type (with source-location information).
6218*67e74705SXin Li QualType DestructedType;
6219*67e74705SXin Li TypeSourceInfo *DestructedTypeInfo = nullptr;
6220*67e74705SXin Li PseudoDestructorTypeStorage Destructed;
6221*67e74705SXin Li if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
6222*67e74705SXin Li ParsedType T = getTypeName(*SecondTypeName.Identifier,
6223*67e74705SXin Li SecondTypeName.StartLocation,
6224*67e74705SXin Li S, &SS, true, false, ObjectTypePtrForLookup);
6225*67e74705SXin Li if (!T &&
6226*67e74705SXin Li ((SS.isSet() && !computeDeclContext(SS, false)) ||
6227*67e74705SXin Li (!SS.isSet() && ObjectType->isDependentType()))) {
6228*67e74705SXin Li // The name of the type being destroyed is a dependent name, and we
6229*67e74705SXin Li // couldn't find anything useful in scope. Just store the identifier and
6230*67e74705SXin Li // it's location, and we'll perform (qualified) name lookup again at
6231*67e74705SXin Li // template instantiation time.
6232*67e74705SXin Li Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
6233*67e74705SXin Li SecondTypeName.StartLocation);
6234*67e74705SXin Li } else if (!T) {
6235*67e74705SXin Li Diag(SecondTypeName.StartLocation,
6236*67e74705SXin Li diag::err_pseudo_dtor_destructor_non_type)
6237*67e74705SXin Li << SecondTypeName.Identifier << ObjectType;
6238*67e74705SXin Li if (isSFINAEContext())
6239*67e74705SXin Li return ExprError();
6240*67e74705SXin Li
6241*67e74705SXin Li // Recover by assuming we had the right type all along.
6242*67e74705SXin Li DestructedType = ObjectType;
6243*67e74705SXin Li } else
6244*67e74705SXin Li DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
6245*67e74705SXin Li } else {
6246*67e74705SXin Li // Resolve the template-id to a type.
6247*67e74705SXin Li TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
6248*67e74705SXin Li ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6249*67e74705SXin Li TemplateId->NumArgs);
6250*67e74705SXin Li TypeResult T = ActOnTemplateIdType(TemplateId->SS,
6251*67e74705SXin Li TemplateId->TemplateKWLoc,
6252*67e74705SXin Li TemplateId->Template,
6253*67e74705SXin Li TemplateId->TemplateNameLoc,
6254*67e74705SXin Li TemplateId->LAngleLoc,
6255*67e74705SXin Li TemplateArgsPtr,
6256*67e74705SXin Li TemplateId->RAngleLoc);
6257*67e74705SXin Li if (T.isInvalid() || !T.get()) {
6258*67e74705SXin Li // Recover by assuming we had the right type all along.
6259*67e74705SXin Li DestructedType = ObjectType;
6260*67e74705SXin Li } else
6261*67e74705SXin Li DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
6262*67e74705SXin Li }
6263*67e74705SXin Li
6264*67e74705SXin Li // If we've performed some kind of recovery, (re-)build the type source
6265*67e74705SXin Li // information.
6266*67e74705SXin Li if (!DestructedType.isNull()) {
6267*67e74705SXin Li if (!DestructedTypeInfo)
6268*67e74705SXin Li DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
6269*67e74705SXin Li SecondTypeName.StartLocation);
6270*67e74705SXin Li Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6271*67e74705SXin Li }
6272*67e74705SXin Li
6273*67e74705SXin Li // Convert the name of the scope type (the type prior to '::') into a type.
6274*67e74705SXin Li TypeSourceInfo *ScopeTypeInfo = nullptr;
6275*67e74705SXin Li QualType ScopeType;
6276*67e74705SXin Li if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6277*67e74705SXin Li FirstTypeName.Identifier) {
6278*67e74705SXin Li if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
6279*67e74705SXin Li ParsedType T = getTypeName(*FirstTypeName.Identifier,
6280*67e74705SXin Li FirstTypeName.StartLocation,
6281*67e74705SXin Li S, &SS, true, false, ObjectTypePtrForLookup);
6282*67e74705SXin Li if (!T) {
6283*67e74705SXin Li Diag(FirstTypeName.StartLocation,
6284*67e74705SXin Li diag::err_pseudo_dtor_destructor_non_type)
6285*67e74705SXin Li << FirstTypeName.Identifier << ObjectType;
6286*67e74705SXin Li
6287*67e74705SXin Li if (isSFINAEContext())
6288*67e74705SXin Li return ExprError();
6289*67e74705SXin Li
6290*67e74705SXin Li // Just drop this type. It's unnecessary anyway.
6291*67e74705SXin Li ScopeType = QualType();
6292*67e74705SXin Li } else
6293*67e74705SXin Li ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
6294*67e74705SXin Li } else {
6295*67e74705SXin Li // Resolve the template-id to a type.
6296*67e74705SXin Li TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
6297*67e74705SXin Li ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6298*67e74705SXin Li TemplateId->NumArgs);
6299*67e74705SXin Li TypeResult T = ActOnTemplateIdType(TemplateId->SS,
6300*67e74705SXin Li TemplateId->TemplateKWLoc,
6301*67e74705SXin Li TemplateId->Template,
6302*67e74705SXin Li TemplateId->TemplateNameLoc,
6303*67e74705SXin Li TemplateId->LAngleLoc,
6304*67e74705SXin Li TemplateArgsPtr,
6305*67e74705SXin Li TemplateId->RAngleLoc);
6306*67e74705SXin Li if (T.isInvalid() || !T.get()) {
6307*67e74705SXin Li // Recover by dropping this type.
6308*67e74705SXin Li ScopeType = QualType();
6309*67e74705SXin Li } else
6310*67e74705SXin Li ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
6311*67e74705SXin Li }
6312*67e74705SXin Li }
6313*67e74705SXin Li
6314*67e74705SXin Li if (!ScopeType.isNull() && !ScopeTypeInfo)
6315*67e74705SXin Li ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
6316*67e74705SXin Li FirstTypeName.StartLocation);
6317*67e74705SXin Li
6318*67e74705SXin Li
6319*67e74705SXin Li return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
6320*67e74705SXin Li ScopeTypeInfo, CCLoc, TildeLoc,
6321*67e74705SXin Li Destructed);
6322*67e74705SXin Li }
6323*67e74705SXin Li
ActOnPseudoDestructorExpr(Scope * S,Expr * Base,SourceLocation OpLoc,tok::TokenKind OpKind,SourceLocation TildeLoc,const DeclSpec & DS)6324*67e74705SXin Li ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6325*67e74705SXin Li SourceLocation OpLoc,
6326*67e74705SXin Li tok::TokenKind OpKind,
6327*67e74705SXin Li SourceLocation TildeLoc,
6328*67e74705SXin Li const DeclSpec& DS) {
6329*67e74705SXin Li QualType ObjectType;
6330*67e74705SXin Li if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6331*67e74705SXin Li return ExprError();
6332*67e74705SXin Li
6333*67e74705SXin Li QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
6334*67e74705SXin Li false);
6335*67e74705SXin Li
6336*67e74705SXin Li TypeLocBuilder TLB;
6337*67e74705SXin Li DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
6338*67e74705SXin Li DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
6339*67e74705SXin Li TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
6340*67e74705SXin Li PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
6341*67e74705SXin Li
6342*67e74705SXin Li return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
6343*67e74705SXin Li nullptr, SourceLocation(), TildeLoc,
6344*67e74705SXin Li Destructed);
6345*67e74705SXin Li }
6346*67e74705SXin Li
BuildCXXMemberCallExpr(Expr * E,NamedDecl * FoundDecl,CXXConversionDecl * Method,bool HadMultipleCandidates)6347*67e74705SXin Li ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
6348*67e74705SXin Li CXXConversionDecl *Method,
6349*67e74705SXin Li bool HadMultipleCandidates) {
6350*67e74705SXin Li if (Method->getParent()->isLambda() &&
6351*67e74705SXin Li Method->getConversionType()->isBlockPointerType()) {
6352*67e74705SXin Li // This is a lambda coversion to block pointer; check if the argument
6353*67e74705SXin Li // is a LambdaExpr.
6354*67e74705SXin Li Expr *SubE = E;
6355*67e74705SXin Li CastExpr *CE = dyn_cast<CastExpr>(SubE);
6356*67e74705SXin Li if (CE && CE->getCastKind() == CK_NoOp)
6357*67e74705SXin Li SubE = CE->getSubExpr();
6358*67e74705SXin Li SubE = SubE->IgnoreParens();
6359*67e74705SXin Li if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
6360*67e74705SXin Li SubE = BE->getSubExpr();
6361*67e74705SXin Li if (isa<LambdaExpr>(SubE)) {
6362*67e74705SXin Li // For the conversion to block pointer on a lambda expression, we
6363*67e74705SXin Li // construct a special BlockLiteral instead; this doesn't really make
6364*67e74705SXin Li // a difference in ARC, but outside of ARC the resulting block literal
6365*67e74705SXin Li // follows the normal lifetime rules for block literals instead of being
6366*67e74705SXin Li // autoreleased.
6367*67e74705SXin Li DiagnosticErrorTrap Trap(Diags);
6368*67e74705SXin Li PushExpressionEvaluationContext(PotentiallyEvaluated);
6369*67e74705SXin Li ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
6370*67e74705SXin Li E->getExprLoc(),
6371*67e74705SXin Li Method, E);
6372*67e74705SXin Li PopExpressionEvaluationContext();
6373*67e74705SXin Li
6374*67e74705SXin Li if (Exp.isInvalid())
6375*67e74705SXin Li Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
6376*67e74705SXin Li return Exp;
6377*67e74705SXin Li }
6378*67e74705SXin Li }
6379*67e74705SXin Li
6380*67e74705SXin Li ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
6381*67e74705SXin Li FoundDecl, Method);
6382*67e74705SXin Li if (Exp.isInvalid())
6383*67e74705SXin Li return true;
6384*67e74705SXin Li
6385*67e74705SXin Li MemberExpr *ME = new (Context) MemberExpr(
6386*67e74705SXin Li Exp.get(), /*IsArrow=*/false, SourceLocation(), Method, SourceLocation(),
6387*67e74705SXin Li Context.BoundMemberTy, VK_RValue, OK_Ordinary);
6388*67e74705SXin Li if (HadMultipleCandidates)
6389*67e74705SXin Li ME->setHadMultipleCandidates(true);
6390*67e74705SXin Li MarkMemberReferenced(ME);
6391*67e74705SXin Li
6392*67e74705SXin Li QualType ResultType = Method->getReturnType();
6393*67e74705SXin Li ExprValueKind VK = Expr::getValueKindForType(ResultType);
6394*67e74705SXin Li ResultType = ResultType.getNonLValueExprType(Context);
6395*67e74705SXin Li
6396*67e74705SXin Li CXXMemberCallExpr *CE =
6397*67e74705SXin Li new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK,
6398*67e74705SXin Li Exp.get()->getLocEnd());
6399*67e74705SXin Li return CE;
6400*67e74705SXin Li }
6401*67e74705SXin Li
BuildCXXNoexceptExpr(SourceLocation KeyLoc,Expr * Operand,SourceLocation RParen)6402*67e74705SXin Li ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
6403*67e74705SXin Li SourceLocation RParen) {
6404*67e74705SXin Li // If the operand is an unresolved lookup expression, the expression is ill-
6405*67e74705SXin Li // formed per [over.over]p1, because overloaded function names cannot be used
6406*67e74705SXin Li // without arguments except in explicit contexts.
6407*67e74705SXin Li ExprResult R = CheckPlaceholderExpr(Operand);
6408*67e74705SXin Li if (R.isInvalid())
6409*67e74705SXin Li return R;
6410*67e74705SXin Li
6411*67e74705SXin Li // The operand may have been modified when checking the placeholder type.
6412*67e74705SXin Li Operand = R.get();
6413*67e74705SXin Li
6414*67e74705SXin Li if (ActiveTemplateInstantiations.empty() &&
6415*67e74705SXin Li Operand->HasSideEffects(Context, false)) {
6416*67e74705SXin Li // The expression operand for noexcept is in an unevaluated expression
6417*67e74705SXin Li // context, so side effects could result in unintended consequences.
6418*67e74705SXin Li Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
6419*67e74705SXin Li }
6420*67e74705SXin Li
6421*67e74705SXin Li CanThrowResult CanThrow = canThrow(Operand);
6422*67e74705SXin Li return new (Context)
6423*67e74705SXin Li CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
6424*67e74705SXin Li }
6425*67e74705SXin Li
ActOnNoexceptExpr(SourceLocation KeyLoc,SourceLocation,Expr * Operand,SourceLocation RParen)6426*67e74705SXin Li ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
6427*67e74705SXin Li Expr *Operand, SourceLocation RParen) {
6428*67e74705SXin Li return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
6429*67e74705SXin Li }
6430*67e74705SXin Li
IsSpecialDiscardedValue(Expr * E)6431*67e74705SXin Li static bool IsSpecialDiscardedValue(Expr *E) {
6432*67e74705SXin Li // In C++11, discarded-value expressions of a certain form are special,
6433*67e74705SXin Li // according to [expr]p10:
6434*67e74705SXin Li // The lvalue-to-rvalue conversion (4.1) is applied only if the
6435*67e74705SXin Li // expression is an lvalue of volatile-qualified type and it has
6436*67e74705SXin Li // one of the following forms:
6437*67e74705SXin Li E = E->IgnoreParens();
6438*67e74705SXin Li
6439*67e74705SXin Li // - id-expression (5.1.1),
6440*67e74705SXin Li if (isa<DeclRefExpr>(E))
6441*67e74705SXin Li return true;
6442*67e74705SXin Li
6443*67e74705SXin Li // - subscripting (5.2.1),
6444*67e74705SXin Li if (isa<ArraySubscriptExpr>(E))
6445*67e74705SXin Li return true;
6446*67e74705SXin Li
6447*67e74705SXin Li // - class member access (5.2.5),
6448*67e74705SXin Li if (isa<MemberExpr>(E))
6449*67e74705SXin Li return true;
6450*67e74705SXin Li
6451*67e74705SXin Li // - indirection (5.3.1),
6452*67e74705SXin Li if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
6453*67e74705SXin Li if (UO->getOpcode() == UO_Deref)
6454*67e74705SXin Li return true;
6455*67e74705SXin Li
6456*67e74705SXin Li if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6457*67e74705SXin Li // - pointer-to-member operation (5.5),
6458*67e74705SXin Li if (BO->isPtrMemOp())
6459*67e74705SXin Li return true;
6460*67e74705SXin Li
6461*67e74705SXin Li // - comma expression (5.18) where the right operand is one of the above.
6462*67e74705SXin Li if (BO->getOpcode() == BO_Comma)
6463*67e74705SXin Li return IsSpecialDiscardedValue(BO->getRHS());
6464*67e74705SXin Li }
6465*67e74705SXin Li
6466*67e74705SXin Li // - conditional expression (5.16) where both the second and the third
6467*67e74705SXin Li // operands are one of the above, or
6468*67e74705SXin Li if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
6469*67e74705SXin Li return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
6470*67e74705SXin Li IsSpecialDiscardedValue(CO->getFalseExpr());
6471*67e74705SXin Li // The related edge case of "*x ?: *x".
6472*67e74705SXin Li if (BinaryConditionalOperator *BCO =
6473*67e74705SXin Li dyn_cast<BinaryConditionalOperator>(E)) {
6474*67e74705SXin Li if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
6475*67e74705SXin Li return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
6476*67e74705SXin Li IsSpecialDiscardedValue(BCO->getFalseExpr());
6477*67e74705SXin Li }
6478*67e74705SXin Li
6479*67e74705SXin Li // Objective-C++ extensions to the rule.
6480*67e74705SXin Li if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
6481*67e74705SXin Li return true;
6482*67e74705SXin Li
6483*67e74705SXin Li return false;
6484*67e74705SXin Li }
6485*67e74705SXin Li
6486*67e74705SXin Li /// Perform the conversions required for an expression used in a
6487*67e74705SXin Li /// context that ignores the result.
IgnoredValueConversions(Expr * E)6488*67e74705SXin Li ExprResult Sema::IgnoredValueConversions(Expr *E) {
6489*67e74705SXin Li if (E->hasPlaceholderType()) {
6490*67e74705SXin Li ExprResult result = CheckPlaceholderExpr(E);
6491*67e74705SXin Li if (result.isInvalid()) return E;
6492*67e74705SXin Li E = result.get();
6493*67e74705SXin Li }
6494*67e74705SXin Li
6495*67e74705SXin Li // C99 6.3.2.1:
6496*67e74705SXin Li // [Except in specific positions,] an lvalue that does not have
6497*67e74705SXin Li // array type is converted to the value stored in the
6498*67e74705SXin Li // designated object (and is no longer an lvalue).
6499*67e74705SXin Li if (E->isRValue()) {
6500*67e74705SXin Li // In C, function designators (i.e. expressions of function type)
6501*67e74705SXin Li // are r-values, but we still want to do function-to-pointer decay
6502*67e74705SXin Li // on them. This is both technically correct and convenient for
6503*67e74705SXin Li // some clients.
6504*67e74705SXin Li if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
6505*67e74705SXin Li return DefaultFunctionArrayConversion(E);
6506*67e74705SXin Li
6507*67e74705SXin Li return E;
6508*67e74705SXin Li }
6509*67e74705SXin Li
6510*67e74705SXin Li if (getLangOpts().CPlusPlus) {
6511*67e74705SXin Li // The C++11 standard defines the notion of a discarded-value expression;
6512*67e74705SXin Li // normally, we don't need to do anything to handle it, but if it is a
6513*67e74705SXin Li // volatile lvalue with a special form, we perform an lvalue-to-rvalue
6514*67e74705SXin Li // conversion.
6515*67e74705SXin Li if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
6516*67e74705SXin Li E->getType().isVolatileQualified() &&
6517*67e74705SXin Li IsSpecialDiscardedValue(E)) {
6518*67e74705SXin Li ExprResult Res = DefaultLvalueConversion(E);
6519*67e74705SXin Li if (Res.isInvalid())
6520*67e74705SXin Li return E;
6521*67e74705SXin Li E = Res.get();
6522*67e74705SXin Li }
6523*67e74705SXin Li return E;
6524*67e74705SXin Li }
6525*67e74705SXin Li
6526*67e74705SXin Li // GCC seems to also exclude expressions of incomplete enum type.
6527*67e74705SXin Li if (const EnumType *T = E->getType()->getAs<EnumType>()) {
6528*67e74705SXin Li if (!T->getDecl()->isComplete()) {
6529*67e74705SXin Li // FIXME: stupid workaround for a codegen bug!
6530*67e74705SXin Li E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
6531*67e74705SXin Li return E;
6532*67e74705SXin Li }
6533*67e74705SXin Li }
6534*67e74705SXin Li
6535*67e74705SXin Li ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
6536*67e74705SXin Li if (Res.isInvalid())
6537*67e74705SXin Li return E;
6538*67e74705SXin Li E = Res.get();
6539*67e74705SXin Li
6540*67e74705SXin Li if (!E->getType()->isVoidType())
6541*67e74705SXin Li RequireCompleteType(E->getExprLoc(), E->getType(),
6542*67e74705SXin Li diag::err_incomplete_type);
6543*67e74705SXin Li return E;
6544*67e74705SXin Li }
6545*67e74705SXin Li
6546*67e74705SXin Li // If we can unambiguously determine whether Var can never be used
6547*67e74705SXin Li // in a constant expression, return true.
6548*67e74705SXin Li // - if the variable and its initializer are non-dependent, then
6549*67e74705SXin Li // we can unambiguously check if the variable is a constant expression.
6550*67e74705SXin Li // - if the initializer is not value dependent - we can determine whether
6551*67e74705SXin Li // it can be used to initialize a constant expression. If Init can not
6552*67e74705SXin Li // be used to initialize a constant expression we conclude that Var can
6553*67e74705SXin Li // never be a constant expression.
6554*67e74705SXin Li // - FXIME: if the initializer is dependent, we can still do some analysis and
6555*67e74705SXin Li // identify certain cases unambiguously as non-const by using a Visitor:
6556*67e74705SXin Li // - such as those that involve odr-use of a ParmVarDecl, involve a new
6557*67e74705SXin Li // delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
VariableCanNeverBeAConstantExpression(VarDecl * Var,ASTContext & Context)6558*67e74705SXin Li static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
6559*67e74705SXin Li ASTContext &Context) {
6560*67e74705SXin Li if (isa<ParmVarDecl>(Var)) return true;
6561*67e74705SXin Li const VarDecl *DefVD = nullptr;
6562*67e74705SXin Li
6563*67e74705SXin Li // If there is no initializer - this can not be a constant expression.
6564*67e74705SXin Li if (!Var->getAnyInitializer(DefVD)) return true;
6565*67e74705SXin Li assert(DefVD);
6566*67e74705SXin Li if (DefVD->isWeak()) return false;
6567*67e74705SXin Li EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
6568*67e74705SXin Li
6569*67e74705SXin Li Expr *Init = cast<Expr>(Eval->Value);
6570*67e74705SXin Li
6571*67e74705SXin Li if (Var->getType()->isDependentType() || Init->isValueDependent()) {
6572*67e74705SXin Li // FIXME: Teach the constant evaluator to deal with the non-dependent parts
6573*67e74705SXin Li // of value-dependent expressions, and use it here to determine whether the
6574*67e74705SXin Li // initializer is a potential constant expression.
6575*67e74705SXin Li return false;
6576*67e74705SXin Li }
6577*67e74705SXin Li
6578*67e74705SXin Li return !IsVariableAConstantExpression(Var, Context);
6579*67e74705SXin Li }
6580*67e74705SXin Li
6581*67e74705SXin Li /// \brief Check if the current lambda has any potential captures
6582*67e74705SXin Li /// that must be captured by any of its enclosing lambdas that are ready to
6583*67e74705SXin Li /// capture. If there is a lambda that can capture a nested
6584*67e74705SXin Li /// potential-capture, go ahead and do so. Also, check to see if any
6585*67e74705SXin Li /// variables are uncaptureable or do not involve an odr-use so do not
6586*67e74705SXin Li /// need to be captured.
6587*67e74705SXin Li
CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(Expr * const FE,LambdaScopeInfo * const CurrentLSI,Sema & S)6588*67e74705SXin Li static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
6589*67e74705SXin Li Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
6590*67e74705SXin Li
6591*67e74705SXin Li assert(!S.isUnevaluatedContext());
6592*67e74705SXin Li assert(S.CurContext->isDependentContext());
6593*67e74705SXin Li assert(CurrentLSI->CallOperator == S.CurContext &&
6594*67e74705SXin Li "The current call operator must be synchronized with Sema's CurContext");
6595*67e74705SXin Li
6596*67e74705SXin Li const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
6597*67e74705SXin Li
6598*67e74705SXin Li ArrayRef<const FunctionScopeInfo *> FunctionScopesArrayRef(
6599*67e74705SXin Li S.FunctionScopes.data(), S.FunctionScopes.size());
6600*67e74705SXin Li
6601*67e74705SXin Li // All the potentially captureable variables in the current nested
6602*67e74705SXin Li // lambda (within a generic outer lambda), must be captured by an
6603*67e74705SXin Li // outer lambda that is enclosed within a non-dependent context.
6604*67e74705SXin Li const unsigned NumPotentialCaptures =
6605*67e74705SXin Li CurrentLSI->getNumPotentialVariableCaptures();
6606*67e74705SXin Li for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
6607*67e74705SXin Li Expr *VarExpr = nullptr;
6608*67e74705SXin Li VarDecl *Var = nullptr;
6609*67e74705SXin Li CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
6610*67e74705SXin Li // If the variable is clearly identified as non-odr-used and the full
6611*67e74705SXin Li // expression is not instantiation dependent, only then do we not
6612*67e74705SXin Li // need to check enclosing lambda's for speculative captures.
6613*67e74705SXin Li // For e.g.:
6614*67e74705SXin Li // Even though 'x' is not odr-used, it should be captured.
6615*67e74705SXin Li // int test() {
6616*67e74705SXin Li // const int x = 10;
6617*67e74705SXin Li // auto L = [=](auto a) {
6618*67e74705SXin Li // (void) +x + a;
6619*67e74705SXin Li // };
6620*67e74705SXin Li // }
6621*67e74705SXin Li if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
6622*67e74705SXin Li !IsFullExprInstantiationDependent)
6623*67e74705SXin Li continue;
6624*67e74705SXin Li
6625*67e74705SXin Li // If we have a capture-capable lambda for the variable, go ahead and
6626*67e74705SXin Li // capture the variable in that lambda (and all its enclosing lambdas).
6627*67e74705SXin Li if (const Optional<unsigned> Index =
6628*67e74705SXin Li getStackIndexOfNearestEnclosingCaptureCapableLambda(
6629*67e74705SXin Li FunctionScopesArrayRef, Var, S)) {
6630*67e74705SXin Li const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
6631*67e74705SXin Li MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
6632*67e74705SXin Li &FunctionScopeIndexOfCapturableLambda);
6633*67e74705SXin Li }
6634*67e74705SXin Li const bool IsVarNeverAConstantExpression =
6635*67e74705SXin Li VariableCanNeverBeAConstantExpression(Var, S.Context);
6636*67e74705SXin Li if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
6637*67e74705SXin Li // This full expression is not instantiation dependent or the variable
6638*67e74705SXin Li // can not be used in a constant expression - which means
6639*67e74705SXin Li // this variable must be odr-used here, so diagnose a
6640*67e74705SXin Li // capture violation early, if the variable is un-captureable.
6641*67e74705SXin Li // This is purely for diagnosing errors early. Otherwise, this
6642*67e74705SXin Li // error would get diagnosed when the lambda becomes capture ready.
6643*67e74705SXin Li QualType CaptureType, DeclRefType;
6644*67e74705SXin Li SourceLocation ExprLoc = VarExpr->getExprLoc();
6645*67e74705SXin Li if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
6646*67e74705SXin Li /*EllipsisLoc*/ SourceLocation(),
6647*67e74705SXin Li /*BuildAndDiagnose*/false, CaptureType,
6648*67e74705SXin Li DeclRefType, nullptr)) {
6649*67e74705SXin Li // We will never be able to capture this variable, and we need
6650*67e74705SXin Li // to be able to in any and all instantiations, so diagnose it.
6651*67e74705SXin Li S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
6652*67e74705SXin Li /*EllipsisLoc*/ SourceLocation(),
6653*67e74705SXin Li /*BuildAndDiagnose*/true, CaptureType,
6654*67e74705SXin Li DeclRefType, nullptr);
6655*67e74705SXin Li }
6656*67e74705SXin Li }
6657*67e74705SXin Li }
6658*67e74705SXin Li
6659*67e74705SXin Li // Check if 'this' needs to be captured.
6660*67e74705SXin Li if (CurrentLSI->hasPotentialThisCapture()) {
6661*67e74705SXin Li // If we have a capture-capable lambda for 'this', go ahead and capture
6662*67e74705SXin Li // 'this' in that lambda (and all its enclosing lambdas).
6663*67e74705SXin Li if (const Optional<unsigned> Index =
6664*67e74705SXin Li getStackIndexOfNearestEnclosingCaptureCapableLambda(
6665*67e74705SXin Li FunctionScopesArrayRef, /*0 is 'this'*/ nullptr, S)) {
6666*67e74705SXin Li const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
6667*67e74705SXin Li S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
6668*67e74705SXin Li /*Explicit*/ false, /*BuildAndDiagnose*/ true,
6669*67e74705SXin Li &FunctionScopeIndexOfCapturableLambda);
6670*67e74705SXin Li }
6671*67e74705SXin Li }
6672*67e74705SXin Li
6673*67e74705SXin Li // Reset all the potential captures at the end of each full-expression.
6674*67e74705SXin Li CurrentLSI->clearPotentialCaptures();
6675*67e74705SXin Li }
6676*67e74705SXin Li
attemptRecovery(Sema & SemaRef,const TypoCorrectionConsumer & Consumer,const TypoCorrection & TC)6677*67e74705SXin Li static ExprResult attemptRecovery(Sema &SemaRef,
6678*67e74705SXin Li const TypoCorrectionConsumer &Consumer,
6679*67e74705SXin Li const TypoCorrection &TC) {
6680*67e74705SXin Li LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
6681*67e74705SXin Li Consumer.getLookupResult().getLookupKind());
6682*67e74705SXin Li const CXXScopeSpec *SS = Consumer.getSS();
6683*67e74705SXin Li CXXScopeSpec NewSS;
6684*67e74705SXin Li
6685*67e74705SXin Li // Use an approprate CXXScopeSpec for building the expr.
6686*67e74705SXin Li if (auto *NNS = TC.getCorrectionSpecifier())
6687*67e74705SXin Li NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
6688*67e74705SXin Li else if (SS && !TC.WillReplaceSpecifier())
6689*67e74705SXin Li NewSS = *SS;
6690*67e74705SXin Li
6691*67e74705SXin Li if (auto *ND = TC.getFoundDecl()) {
6692*67e74705SXin Li R.setLookupName(ND->getDeclName());
6693*67e74705SXin Li R.addDecl(ND);
6694*67e74705SXin Li if (ND->isCXXClassMember()) {
6695*67e74705SXin Li // Figure out the correct naming class to add to the LookupResult.
6696*67e74705SXin Li CXXRecordDecl *Record = nullptr;
6697*67e74705SXin Li if (auto *NNS = TC.getCorrectionSpecifier())
6698*67e74705SXin Li Record = NNS->getAsType()->getAsCXXRecordDecl();
6699*67e74705SXin Li if (!Record)
6700*67e74705SXin Li Record =
6701*67e74705SXin Li dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
6702*67e74705SXin Li if (Record)
6703*67e74705SXin Li R.setNamingClass(Record);
6704*67e74705SXin Li
6705*67e74705SXin Li // Detect and handle the case where the decl might be an implicit
6706*67e74705SXin Li // member.
6707*67e74705SXin Li bool MightBeImplicitMember;
6708*67e74705SXin Li if (!Consumer.isAddressOfOperand())
6709*67e74705SXin Li MightBeImplicitMember = true;
6710*67e74705SXin Li else if (!NewSS.isEmpty())
6711*67e74705SXin Li MightBeImplicitMember = false;
6712*67e74705SXin Li else if (R.isOverloadedResult())
6713*67e74705SXin Li MightBeImplicitMember = false;
6714*67e74705SXin Li else if (R.isUnresolvableResult())
6715*67e74705SXin Li MightBeImplicitMember = true;
6716*67e74705SXin Li else
6717*67e74705SXin Li MightBeImplicitMember = isa<FieldDecl>(ND) ||
6718*67e74705SXin Li isa<IndirectFieldDecl>(ND) ||
6719*67e74705SXin Li isa<MSPropertyDecl>(ND);
6720*67e74705SXin Li
6721*67e74705SXin Li if (MightBeImplicitMember)
6722*67e74705SXin Li return SemaRef.BuildPossibleImplicitMemberExpr(
6723*67e74705SXin Li NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
6724*67e74705SXin Li /*TemplateArgs*/ nullptr, /*S*/ nullptr);
6725*67e74705SXin Li } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
6726*67e74705SXin Li return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
6727*67e74705SXin Li Ivar->getIdentifier());
6728*67e74705SXin Li }
6729*67e74705SXin Li }
6730*67e74705SXin Li
6731*67e74705SXin Li return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
6732*67e74705SXin Li /*AcceptInvalidDecl*/ true);
6733*67e74705SXin Li }
6734*67e74705SXin Li
6735*67e74705SXin Li namespace {
6736*67e74705SXin Li class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
6737*67e74705SXin Li llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
6738*67e74705SXin Li
6739*67e74705SXin Li public:
FindTypoExprs(llvm::SmallSetVector<TypoExpr *,2> & TypoExprs)6740*67e74705SXin Li explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
6741*67e74705SXin Li : TypoExprs(TypoExprs) {}
VisitTypoExpr(TypoExpr * TE)6742*67e74705SXin Li bool VisitTypoExpr(TypoExpr *TE) {
6743*67e74705SXin Li TypoExprs.insert(TE);
6744*67e74705SXin Li return true;
6745*67e74705SXin Li }
6746*67e74705SXin Li };
6747*67e74705SXin Li
6748*67e74705SXin Li class TransformTypos : public TreeTransform<TransformTypos> {
6749*67e74705SXin Li typedef TreeTransform<TransformTypos> BaseTransform;
6750*67e74705SXin Li
6751*67e74705SXin Li VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
6752*67e74705SXin Li // process of being initialized.
6753*67e74705SXin Li llvm::function_ref<ExprResult(Expr *)> ExprFilter;
6754*67e74705SXin Li llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
6755*67e74705SXin Li llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
6756*67e74705SXin Li llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
6757*67e74705SXin Li
6758*67e74705SXin Li /// \brief Emit diagnostics for all of the TypoExprs encountered.
6759*67e74705SXin Li /// If the TypoExprs were successfully corrected, then the diagnostics should
6760*67e74705SXin Li /// suggest the corrections. Otherwise the diagnostics will not suggest
6761*67e74705SXin Li /// anything (having been passed an empty TypoCorrection).
EmitAllDiagnostics()6762*67e74705SXin Li void EmitAllDiagnostics() {
6763*67e74705SXin Li for (auto E : TypoExprs) {
6764*67e74705SXin Li TypoExpr *TE = cast<TypoExpr>(E);
6765*67e74705SXin Li auto &State = SemaRef.getTypoExprState(TE);
6766*67e74705SXin Li if (State.DiagHandler) {
6767*67e74705SXin Li TypoCorrection TC = State.Consumer->getCurrentCorrection();
6768*67e74705SXin Li ExprResult Replacement = TransformCache[TE];
6769*67e74705SXin Li
6770*67e74705SXin Li // Extract the NamedDecl from the transformed TypoExpr and add it to the
6771*67e74705SXin Li // TypoCorrection, replacing the existing decls. This ensures the right
6772*67e74705SXin Li // NamedDecl is used in diagnostics e.g. in the case where overload
6773*67e74705SXin Li // resolution was used to select one from several possible decls that
6774*67e74705SXin Li // had been stored in the TypoCorrection.
6775*67e74705SXin Li if (auto *ND = getDeclFromExpr(
6776*67e74705SXin Li Replacement.isInvalid() ? nullptr : Replacement.get()))
6777*67e74705SXin Li TC.setCorrectionDecl(ND);
6778*67e74705SXin Li
6779*67e74705SXin Li State.DiagHandler(TC);
6780*67e74705SXin Li }
6781*67e74705SXin Li SemaRef.clearDelayedTypo(TE);
6782*67e74705SXin Li }
6783*67e74705SXin Li }
6784*67e74705SXin Li
6785*67e74705SXin Li /// \brief If corrections for the first TypoExpr have been exhausted for a
6786*67e74705SXin Li /// given combination of the other TypoExprs, retry those corrections against
6787*67e74705SXin Li /// the next combination of substitutions for the other TypoExprs by advancing
6788*67e74705SXin Li /// to the next potential correction of the second TypoExpr. For the second
6789*67e74705SXin Li /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
6790*67e74705SXin Li /// the stream is reset and the next TypoExpr's stream is advanced by one (a
6791*67e74705SXin Li /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
6792*67e74705SXin Li /// TransformCache). Returns true if there is still any untried combinations
6793*67e74705SXin Li /// of corrections.
CheckAndAdvanceTypoExprCorrectionStreams()6794*67e74705SXin Li bool CheckAndAdvanceTypoExprCorrectionStreams() {
6795*67e74705SXin Li for (auto TE : TypoExprs) {
6796*67e74705SXin Li auto &State = SemaRef.getTypoExprState(TE);
6797*67e74705SXin Li TransformCache.erase(TE);
6798*67e74705SXin Li if (!State.Consumer->finished())
6799*67e74705SXin Li return true;
6800*67e74705SXin Li State.Consumer->resetCorrectionStream();
6801*67e74705SXin Li }
6802*67e74705SXin Li return false;
6803*67e74705SXin Li }
6804*67e74705SXin Li
getDeclFromExpr(Expr * E)6805*67e74705SXin Li NamedDecl *getDeclFromExpr(Expr *E) {
6806*67e74705SXin Li if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
6807*67e74705SXin Li E = OverloadResolution[OE];
6808*67e74705SXin Li
6809*67e74705SXin Li if (!E)
6810*67e74705SXin Li return nullptr;
6811*67e74705SXin Li if (auto *DRE = dyn_cast<DeclRefExpr>(E))
6812*67e74705SXin Li return DRE->getFoundDecl();
6813*67e74705SXin Li if (auto *ME = dyn_cast<MemberExpr>(E))
6814*67e74705SXin Li return ME->getFoundDecl();
6815*67e74705SXin Li // FIXME: Add any other expr types that could be be seen by the delayed typo
6816*67e74705SXin Li // correction TreeTransform for which the corresponding TypoCorrection could
6817*67e74705SXin Li // contain multiple decls.
6818*67e74705SXin Li return nullptr;
6819*67e74705SXin Li }
6820*67e74705SXin Li
TryTransform(Expr * E)6821*67e74705SXin Li ExprResult TryTransform(Expr *E) {
6822*67e74705SXin Li Sema::SFINAETrap Trap(SemaRef);
6823*67e74705SXin Li ExprResult Res = TransformExpr(E);
6824*67e74705SXin Li if (Trap.hasErrorOccurred() || Res.isInvalid())
6825*67e74705SXin Li return ExprError();
6826*67e74705SXin Li
6827*67e74705SXin Li return ExprFilter(Res.get());
6828*67e74705SXin Li }
6829*67e74705SXin Li
6830*67e74705SXin Li public:
TransformTypos(Sema & SemaRef,VarDecl * InitDecl,llvm::function_ref<ExprResult (Expr *)> Filter)6831*67e74705SXin Li TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
6832*67e74705SXin Li : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
6833*67e74705SXin Li
RebuildCallExpr(Expr * Callee,SourceLocation LParenLoc,MultiExprArg Args,SourceLocation RParenLoc,Expr * ExecConfig=nullptr)6834*67e74705SXin Li ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
6835*67e74705SXin Li MultiExprArg Args,
6836*67e74705SXin Li SourceLocation RParenLoc,
6837*67e74705SXin Li Expr *ExecConfig = nullptr) {
6838*67e74705SXin Li auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
6839*67e74705SXin Li RParenLoc, ExecConfig);
6840*67e74705SXin Li if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
6841*67e74705SXin Li if (Result.isUsable()) {
6842*67e74705SXin Li Expr *ResultCall = Result.get();
6843*67e74705SXin Li if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
6844*67e74705SXin Li ResultCall = BE->getSubExpr();
6845*67e74705SXin Li if (auto *CE = dyn_cast<CallExpr>(ResultCall))
6846*67e74705SXin Li OverloadResolution[OE] = CE->getCallee();
6847*67e74705SXin Li }
6848*67e74705SXin Li }
6849*67e74705SXin Li return Result;
6850*67e74705SXin Li }
6851*67e74705SXin Li
TransformLambdaExpr(LambdaExpr * E)6852*67e74705SXin Li ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
6853*67e74705SXin Li
TransformBlockExpr(BlockExpr * E)6854*67e74705SXin Li ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
6855*67e74705SXin Li
TransformObjCPropertyRefExpr(ObjCPropertyRefExpr * E)6856*67e74705SXin Li ExprResult TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
6857*67e74705SXin Li return Owned(E);
6858*67e74705SXin Li }
6859*67e74705SXin Li
TransformObjCIvarRefExpr(ObjCIvarRefExpr * E)6860*67e74705SXin Li ExprResult TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
6861*67e74705SXin Li return Owned(E);
6862*67e74705SXin Li }
6863*67e74705SXin Li
Transform(Expr * E)6864*67e74705SXin Li ExprResult Transform(Expr *E) {
6865*67e74705SXin Li ExprResult Res;
6866*67e74705SXin Li while (true) {
6867*67e74705SXin Li Res = TryTransform(E);
6868*67e74705SXin Li
6869*67e74705SXin Li // Exit if either the transform was valid or if there were no TypoExprs
6870*67e74705SXin Li // to transform that still have any untried correction candidates..
6871*67e74705SXin Li if (!Res.isInvalid() ||
6872*67e74705SXin Li !CheckAndAdvanceTypoExprCorrectionStreams())
6873*67e74705SXin Li break;
6874*67e74705SXin Li }
6875*67e74705SXin Li
6876*67e74705SXin Li // Ensure none of the TypoExprs have multiple typo correction candidates
6877*67e74705SXin Li // with the same edit length that pass all the checks and filters.
6878*67e74705SXin Li // TODO: Properly handle various permutations of possible corrections when
6879*67e74705SXin Li // there is more than one potentially ambiguous typo correction.
6880*67e74705SXin Li // Also, disable typo correction while attempting the transform when
6881*67e74705SXin Li // handling potentially ambiguous typo corrections as any new TypoExprs will
6882*67e74705SXin Li // have been introduced by the application of one of the correction
6883*67e74705SXin Li // candidates and add little to no value if corrected.
6884*67e74705SXin Li SemaRef.DisableTypoCorrection = true;
6885*67e74705SXin Li while (!AmbiguousTypoExprs.empty()) {
6886*67e74705SXin Li auto TE = AmbiguousTypoExprs.back();
6887*67e74705SXin Li auto Cached = TransformCache[TE];
6888*67e74705SXin Li auto &State = SemaRef.getTypoExprState(TE);
6889*67e74705SXin Li State.Consumer->saveCurrentPosition();
6890*67e74705SXin Li TransformCache.erase(TE);
6891*67e74705SXin Li if (!TryTransform(E).isInvalid()) {
6892*67e74705SXin Li State.Consumer->resetCorrectionStream();
6893*67e74705SXin Li TransformCache.erase(TE);
6894*67e74705SXin Li Res = ExprError();
6895*67e74705SXin Li break;
6896*67e74705SXin Li }
6897*67e74705SXin Li AmbiguousTypoExprs.remove(TE);
6898*67e74705SXin Li State.Consumer->restoreSavedPosition();
6899*67e74705SXin Li TransformCache[TE] = Cached;
6900*67e74705SXin Li }
6901*67e74705SXin Li SemaRef.DisableTypoCorrection = false;
6902*67e74705SXin Li
6903*67e74705SXin Li // Ensure that all of the TypoExprs within the current Expr have been found.
6904*67e74705SXin Li if (!Res.isUsable())
6905*67e74705SXin Li FindTypoExprs(TypoExprs).TraverseStmt(E);
6906*67e74705SXin Li
6907*67e74705SXin Li EmitAllDiagnostics();
6908*67e74705SXin Li
6909*67e74705SXin Li return Res;
6910*67e74705SXin Li }
6911*67e74705SXin Li
TransformTypoExpr(TypoExpr * E)6912*67e74705SXin Li ExprResult TransformTypoExpr(TypoExpr *E) {
6913*67e74705SXin Li // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
6914*67e74705SXin Li // cached transformation result if there is one and the TypoExpr isn't the
6915*67e74705SXin Li // first one that was encountered.
6916*67e74705SXin Li auto &CacheEntry = TransformCache[E];
6917*67e74705SXin Li if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
6918*67e74705SXin Li return CacheEntry;
6919*67e74705SXin Li }
6920*67e74705SXin Li
6921*67e74705SXin Li auto &State = SemaRef.getTypoExprState(E);
6922*67e74705SXin Li assert(State.Consumer && "Cannot transform a cleared TypoExpr");
6923*67e74705SXin Li
6924*67e74705SXin Li // For the first TypoExpr and an uncached TypoExpr, find the next likely
6925*67e74705SXin Li // typo correction and return it.
6926*67e74705SXin Li while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
6927*67e74705SXin Li if (InitDecl && TC.getFoundDecl() == InitDecl)
6928*67e74705SXin Li continue;
6929*67e74705SXin Li ExprResult NE = State.RecoveryHandler ?
6930*67e74705SXin Li State.RecoveryHandler(SemaRef, E, TC) :
6931*67e74705SXin Li attemptRecovery(SemaRef, *State.Consumer, TC);
6932*67e74705SXin Li if (!NE.isInvalid()) {
6933*67e74705SXin Li // Check whether there may be a second viable correction with the same
6934*67e74705SXin Li // edit distance; if so, remember this TypoExpr may have an ambiguous
6935*67e74705SXin Li // correction so it can be more thoroughly vetted later.
6936*67e74705SXin Li TypoCorrection Next;
6937*67e74705SXin Li if ((Next = State.Consumer->peekNextCorrection()) &&
6938*67e74705SXin Li Next.getEditDistance(false) == TC.getEditDistance(false)) {
6939*67e74705SXin Li AmbiguousTypoExprs.insert(E);
6940*67e74705SXin Li } else {
6941*67e74705SXin Li AmbiguousTypoExprs.remove(E);
6942*67e74705SXin Li }
6943*67e74705SXin Li assert(!NE.isUnset() &&
6944*67e74705SXin Li "Typo was transformed into a valid-but-null ExprResult");
6945*67e74705SXin Li return CacheEntry = NE;
6946*67e74705SXin Li }
6947*67e74705SXin Li }
6948*67e74705SXin Li return CacheEntry = ExprError();
6949*67e74705SXin Li }
6950*67e74705SXin Li };
6951*67e74705SXin Li }
6952*67e74705SXin Li
6953*67e74705SXin Li ExprResult
CorrectDelayedTyposInExpr(Expr * E,VarDecl * InitDecl,llvm::function_ref<ExprResult (Expr *)> Filter)6954*67e74705SXin Li Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
6955*67e74705SXin Li llvm::function_ref<ExprResult(Expr *)> Filter) {
6956*67e74705SXin Li // If the current evaluation context indicates there are uncorrected typos
6957*67e74705SXin Li // and the current expression isn't guaranteed to not have typos, try to
6958*67e74705SXin Li // resolve any TypoExpr nodes that might be in the expression.
6959*67e74705SXin Li if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
6960*67e74705SXin Li (E->isTypeDependent() || E->isValueDependent() ||
6961*67e74705SXin Li E->isInstantiationDependent())) {
6962*67e74705SXin Li auto TyposInContext = ExprEvalContexts.back().NumTypos;
6963*67e74705SXin Li assert(TyposInContext < ~0U && "Recursive call of CorrectDelayedTyposInExpr");
6964*67e74705SXin Li ExprEvalContexts.back().NumTypos = ~0U;
6965*67e74705SXin Li auto TyposResolved = DelayedTypos.size();
6966*67e74705SXin Li auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
6967*67e74705SXin Li ExprEvalContexts.back().NumTypos = TyposInContext;
6968*67e74705SXin Li TyposResolved -= DelayedTypos.size();
6969*67e74705SXin Li if (Result.isInvalid() || Result.get() != E) {
6970*67e74705SXin Li ExprEvalContexts.back().NumTypos -= TyposResolved;
6971*67e74705SXin Li return Result;
6972*67e74705SXin Li }
6973*67e74705SXin Li assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
6974*67e74705SXin Li }
6975*67e74705SXin Li return E;
6976*67e74705SXin Li }
6977*67e74705SXin Li
ActOnFinishFullExpr(Expr * FE,SourceLocation CC,bool DiscardedValue,bool IsConstexpr,bool IsLambdaInitCaptureInitializer)6978*67e74705SXin Li ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
6979*67e74705SXin Li bool DiscardedValue,
6980*67e74705SXin Li bool IsConstexpr,
6981*67e74705SXin Li bool IsLambdaInitCaptureInitializer) {
6982*67e74705SXin Li ExprResult FullExpr = FE;
6983*67e74705SXin Li
6984*67e74705SXin Li if (!FullExpr.get())
6985*67e74705SXin Li return ExprError();
6986*67e74705SXin Li
6987*67e74705SXin Li // If we are an init-expression in a lambdas init-capture, we should not
6988*67e74705SXin Li // diagnose an unexpanded pack now (will be diagnosed once lambda-expr
6989*67e74705SXin Li // containing full-expression is done).
6990*67e74705SXin Li // template<class ... Ts> void test(Ts ... t) {
6991*67e74705SXin Li // test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now.
6992*67e74705SXin Li // return a;
6993*67e74705SXin Li // }() ...);
6994*67e74705SXin Li // }
6995*67e74705SXin Li // FIXME: This is a hack. It would be better if we pushed the lambda scope
6996*67e74705SXin Li // when we parse the lambda introducer, and teach capturing (but not
6997*67e74705SXin Li // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a
6998*67e74705SXin Li // corresponding class yet (that is, have LambdaScopeInfo either represent a
6999*67e74705SXin Li // lambda where we've entered the introducer but not the body, or represent a
7000*67e74705SXin Li // lambda where we've entered the body, depending on where the
7001*67e74705SXin Li // parser/instantiation has got to).
7002*67e74705SXin Li if (!IsLambdaInitCaptureInitializer &&
7003*67e74705SXin Li DiagnoseUnexpandedParameterPack(FullExpr.get()))
7004*67e74705SXin Li return ExprError();
7005*67e74705SXin Li
7006*67e74705SXin Li // Top-level expressions default to 'id' when we're in a debugger.
7007*67e74705SXin Li if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
7008*67e74705SXin Li FullExpr.get()->getType() == Context.UnknownAnyTy) {
7009*67e74705SXin Li FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
7010*67e74705SXin Li if (FullExpr.isInvalid())
7011*67e74705SXin Li return ExprError();
7012*67e74705SXin Li }
7013*67e74705SXin Li
7014*67e74705SXin Li if (DiscardedValue) {
7015*67e74705SXin Li FullExpr = CheckPlaceholderExpr(FullExpr.get());
7016*67e74705SXin Li if (FullExpr.isInvalid())
7017*67e74705SXin Li return ExprError();
7018*67e74705SXin Li
7019*67e74705SXin Li FullExpr = IgnoredValueConversions(FullExpr.get());
7020*67e74705SXin Li if (FullExpr.isInvalid())
7021*67e74705SXin Li return ExprError();
7022*67e74705SXin Li }
7023*67e74705SXin Li
7024*67e74705SXin Li FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
7025*67e74705SXin Li if (FullExpr.isInvalid())
7026*67e74705SXin Li return ExprError();
7027*67e74705SXin Li
7028*67e74705SXin Li CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
7029*67e74705SXin Li
7030*67e74705SXin Li // At the end of this full expression (which could be a deeply nested
7031*67e74705SXin Li // lambda), if there is a potential capture within the nested lambda,
7032*67e74705SXin Li // have the outer capture-able lambda try and capture it.
7033*67e74705SXin Li // Consider the following code:
7034*67e74705SXin Li // void f(int, int);
7035*67e74705SXin Li // void f(const int&, double);
7036*67e74705SXin Li // void foo() {
7037*67e74705SXin Li // const int x = 10, y = 20;
7038*67e74705SXin Li // auto L = [=](auto a) {
7039*67e74705SXin Li // auto M = [=](auto b) {
7040*67e74705SXin Li // f(x, b); <-- requires x to be captured by L and M
7041*67e74705SXin Li // f(y, a); <-- requires y to be captured by L, but not all Ms
7042*67e74705SXin Li // };
7043*67e74705SXin Li // };
7044*67e74705SXin Li // }
7045*67e74705SXin Li
7046*67e74705SXin Li // FIXME: Also consider what happens for something like this that involves
7047*67e74705SXin Li // the gnu-extension statement-expressions or even lambda-init-captures:
7048*67e74705SXin Li // void f() {
7049*67e74705SXin Li // const int n = 0;
7050*67e74705SXin Li // auto L = [&](auto a) {
7051*67e74705SXin Li // +n + ({ 0; a; });
7052*67e74705SXin Li // };
7053*67e74705SXin Li // }
7054*67e74705SXin Li //
7055*67e74705SXin Li // Here, we see +n, and then the full-expression 0; ends, so we don't
7056*67e74705SXin Li // capture n (and instead remove it from our list of potential captures),
7057*67e74705SXin Li // and then the full-expression +n + ({ 0; }); ends, but it's too late
7058*67e74705SXin Li // for us to see that we need to capture n after all.
7059*67e74705SXin Li
7060*67e74705SXin Li LambdaScopeInfo *const CurrentLSI = getCurLambda();
7061*67e74705SXin Li // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
7062*67e74705SXin Li // even if CurContext is not a lambda call operator. Refer to that Bug Report
7063*67e74705SXin Li // for an example of the code that might cause this asynchrony.
7064*67e74705SXin Li // By ensuring we are in the context of a lambda's call operator
7065*67e74705SXin Li // we can fix the bug (we only need to check whether we need to capture
7066*67e74705SXin Li // if we are within a lambda's body); but per the comments in that
7067*67e74705SXin Li // PR, a proper fix would entail :
7068*67e74705SXin Li // "Alternative suggestion:
7069*67e74705SXin Li // - Add to Sema an integer holding the smallest (outermost) scope
7070*67e74705SXin Li // index that we are *lexically* within, and save/restore/set to
7071*67e74705SXin Li // FunctionScopes.size() in InstantiatingTemplate's
7072*67e74705SXin Li // constructor/destructor.
7073*67e74705SXin Li // - Teach the handful of places that iterate over FunctionScopes to
7074*67e74705SXin Li // stop at the outermost enclosing lexical scope."
7075*67e74705SXin Li const bool IsInLambdaDeclContext = isLambdaCallOperator(CurContext);
7076*67e74705SXin Li if (IsInLambdaDeclContext && CurrentLSI &&
7077*67e74705SXin Li CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
7078*67e74705SXin Li CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
7079*67e74705SXin Li *this);
7080*67e74705SXin Li return MaybeCreateExprWithCleanups(FullExpr);
7081*67e74705SXin Li }
7082*67e74705SXin Li
ActOnFinishFullStmt(Stmt * FullStmt)7083*67e74705SXin Li StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
7084*67e74705SXin Li if (!FullStmt) return StmtError();
7085*67e74705SXin Li
7086*67e74705SXin Li return MaybeCreateStmtWithCleanups(FullStmt);
7087*67e74705SXin Li }
7088*67e74705SXin Li
7089*67e74705SXin Li Sema::IfExistsResult
CheckMicrosoftIfExistsSymbol(Scope * S,CXXScopeSpec & SS,const DeclarationNameInfo & TargetNameInfo)7090*67e74705SXin Li Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
7091*67e74705SXin Li CXXScopeSpec &SS,
7092*67e74705SXin Li const DeclarationNameInfo &TargetNameInfo) {
7093*67e74705SXin Li DeclarationName TargetName = TargetNameInfo.getName();
7094*67e74705SXin Li if (!TargetName)
7095*67e74705SXin Li return IER_DoesNotExist;
7096*67e74705SXin Li
7097*67e74705SXin Li // If the name itself is dependent, then the result is dependent.
7098*67e74705SXin Li if (TargetName.isDependentName())
7099*67e74705SXin Li return IER_Dependent;
7100*67e74705SXin Li
7101*67e74705SXin Li // Do the redeclaration lookup in the current scope.
7102*67e74705SXin Li LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
7103*67e74705SXin Li Sema::NotForRedeclaration);
7104*67e74705SXin Li LookupParsedName(R, S, &SS);
7105*67e74705SXin Li R.suppressDiagnostics();
7106*67e74705SXin Li
7107*67e74705SXin Li switch (R.getResultKind()) {
7108*67e74705SXin Li case LookupResult::Found:
7109*67e74705SXin Li case LookupResult::FoundOverloaded:
7110*67e74705SXin Li case LookupResult::FoundUnresolvedValue:
7111*67e74705SXin Li case LookupResult::Ambiguous:
7112*67e74705SXin Li return IER_Exists;
7113*67e74705SXin Li
7114*67e74705SXin Li case LookupResult::NotFound:
7115*67e74705SXin Li return IER_DoesNotExist;
7116*67e74705SXin Li
7117*67e74705SXin Li case LookupResult::NotFoundInCurrentInstantiation:
7118*67e74705SXin Li return IER_Dependent;
7119*67e74705SXin Li }
7120*67e74705SXin Li
7121*67e74705SXin Li llvm_unreachable("Invalid LookupResult Kind!");
7122*67e74705SXin Li }
7123*67e74705SXin Li
7124*67e74705SXin Li Sema::IfExistsResult
CheckMicrosoftIfExistsSymbol(Scope * S,SourceLocation KeywordLoc,bool IsIfExists,CXXScopeSpec & SS,UnqualifiedId & Name)7125*67e74705SXin Li Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
7126*67e74705SXin Li bool IsIfExists, CXXScopeSpec &SS,
7127*67e74705SXin Li UnqualifiedId &Name) {
7128*67e74705SXin Li DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7129*67e74705SXin Li
7130*67e74705SXin Li // Check for unexpanded parameter packs.
7131*67e74705SXin Li SmallVector<UnexpandedParameterPack, 4> Unexpanded;
7132*67e74705SXin Li collectUnexpandedParameterPacks(SS, Unexpanded);
7133*67e74705SXin Li collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
7134*67e74705SXin Li if (!Unexpanded.empty()) {
7135*67e74705SXin Li DiagnoseUnexpandedParameterPacks(KeywordLoc,
7136*67e74705SXin Li IsIfExists? UPPC_IfExists
7137*67e74705SXin Li : UPPC_IfNotExists,
7138*67e74705SXin Li Unexpanded);
7139*67e74705SXin Li return IER_Error;
7140*67e74705SXin Li }
7141*67e74705SXin Li
7142*67e74705SXin Li return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
7143*67e74705SXin Li }
7144