blob: 79e6d3a646dae705e912d1f5df03a49830842e79 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall2a7fb272010-08-25 05:32:35 +000015#include "clang/Sema/DeclSpec.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
John McCall2a7fb272010-08-25 05:32:35 +000018#include "clang/Sema/ParsedTemplate.h"
John McCall469a1eb2011-02-02 13:00:07 +000019#include "clang/Sema/ScopeInfo.h"
John McCall2a7fb272010-08-25 05:32:35 +000020#include "clang/Sema/TemplateDeduction.h"
Steve Naroff210679c2007-08-25 14:02:58 +000021#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000024#include "clang/AST/ExprCXX.h"
Fariborz Jahaniand4266622010-06-16 18:56:04 +000025#include "clang/AST/ExprObjC.h"
Douglas Gregorb57fb492010-02-24 22:38:50 +000026#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000027#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000028#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000029#include "clang/Lex/Preprocessor.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000030#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000031using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000032using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000033
John McCallb3d87482010-08-24 05:47:05 +000034ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000035 IdentifierInfo &II,
John McCallb3d87482010-08-24 05:47:05 +000036 SourceLocation NameLoc,
37 Scope *S, CXXScopeSpec &SS,
38 ParsedType ObjectTypePtr,
39 bool EnteringContext) {
Douglas Gregor124b8782010-02-16 19:09:40 +000040 // Determine where to perform name lookup.
41
42 // FIXME: This area of the standard is very messy, and the current
43 // wording is rather unclear about which scopes we search for the
44 // destructor name; see core issues 399 and 555. Issue 399 in
45 // particular shows where the current description of destructor name
46 // lookup is completely out of line with existing practice, e.g.,
47 // this appears to be ill-formed:
48 //
49 // namespace N {
50 // template <typename T> struct S {
51 // ~S();
52 // };
53 // }
54 //
55 // void f(N::S<int>* s) {
56 // s->N::S<int>::~S();
57 // }
58 //
Douglas Gregor93649fd2010-02-23 00:15:22 +000059 // See also PR6358 and PR6359.
Sebastian Redlc0fee502010-07-07 23:17:38 +000060 // For this reason, we're currently only doing the C++03 version of this
61 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregor124b8782010-02-16 19:09:40 +000062 QualType SearchType;
63 DeclContext *LookupCtx = 0;
64 bool isDependent = false;
65 bool LookInScope = false;
66
67 // If we have an object type, it's because we are in a
68 // pseudo-destructor-expression or a member access expression, and
69 // we know what type we're looking for.
70 if (ObjectTypePtr)
71 SearchType = GetTypeFromParser(ObjectTypePtr);
72
73 if (SS.isSet()) {
Douglas Gregor93649fd2010-02-23 00:15:22 +000074 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000075
Douglas Gregor93649fd2010-02-23 00:15:22 +000076 bool AlreadySearched = false;
77 bool LookAtPrefix = true;
Sebastian Redlc0fee502010-07-07 23:17:38 +000078 // C++ [basic.lookup.qual]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000079 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redlc0fee502010-07-07 23:17:38 +000080 // the type-names are looked up as types in the scope designated by the
81 // nested-name-specifier. In a qualified-id of the form:
NAKAMURA Takumi00995302011-01-27 07:09:49 +000082 //
83 // ::[opt] nested-name-specifier ~ class-name
Sebastian Redlc0fee502010-07-07 23:17:38 +000084 //
85 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth5e895a82010-02-21 10:19:54 +000086 // a qualified-id of the form:
Douglas Gregor124b8782010-02-16 19:09:40 +000087 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +000088 // ::opt nested-name-specifier class-name :: ~ class-name
Douglas Gregor124b8782010-02-16 19:09:40 +000089 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000090 // the class-names are looked up as types in the scope designated by
Sebastian Redlc0fee502010-07-07 23:17:38 +000091 // the nested-name-specifier.
Douglas Gregor124b8782010-02-16 19:09:40 +000092 //
Sebastian Redlc0fee502010-07-07 23:17:38 +000093 // Here, we check the first case (completely) and determine whether the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000094 // code below is permitted to look at the prefix of the
Sebastian Redlc0fee502010-07-07 23:17:38 +000095 // nested-name-specifier.
96 DeclContext *DC = computeDeclContext(SS, EnteringContext);
97 if (DC && DC->isFileContext()) {
98 AlreadySearched = true;
99 LookupCtx = DC;
100 isDependent = false;
101 } else if (DC && isa<CXXRecordDecl>(DC))
102 LookAtPrefix = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000103
Sebastian Redlc0fee502010-07-07 23:17:38 +0000104 // The second case from the C++03 rules quoted further above.
Douglas Gregor93649fd2010-02-23 00:15:22 +0000105 NestedNameSpecifier *Prefix = 0;
106 if (AlreadySearched) {
107 // Nothing left to do.
108 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
109 CXXScopeSpec PrefixSS;
Douglas Gregor7e384942011-02-25 16:07:42 +0000110 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor93649fd2010-02-23 00:15:22 +0000111 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
112 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000113 } else if (ObjectTypePtr) {
Douglas Gregor124b8782010-02-16 19:09:40 +0000114 LookupCtx = computeDeclContext(SearchType);
115 isDependent = SearchType->isDependentType();
116 } else {
117 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000118 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregor124b8782010-02-16 19:09:40 +0000119 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000120
Douglas Gregoredc90502010-02-25 04:46:04 +0000121 LookInScope = false;
Douglas Gregor124b8782010-02-16 19:09:40 +0000122 } else if (ObjectTypePtr) {
123 // C++ [basic.lookup.classref]p3:
124 // If the unqualified-id is ~type-name, the type-name is looked up
125 // in the context of the entire postfix-expression. If the type T
126 // of the object expression is of a class type C, the type-name is
127 // also looked up in the scope of class C. At least one of the
128 // lookups shall find a name that refers to (possibly
129 // cv-qualified) T.
130 LookupCtx = computeDeclContext(SearchType);
131 isDependent = SearchType->isDependentType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000132 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregor124b8782010-02-16 19:09:40 +0000133 "Caller should have completed object type");
134
135 LookInScope = true;
136 } else {
137 // Perform lookup into the current scope (only).
138 LookInScope = true;
139 }
140
141 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
142 for (unsigned Step = 0; Step != 2; ++Step) {
143 // Look for the name first in the computed lookup context (if we
144 // have one) and, if that fails to find a match, in the sope (if
145 // we're allowed to look there).
146 Found.clear();
147 if (Step == 0 && LookupCtx)
148 LookupQualifiedName(Found, LookupCtx);
Douglas Gregora2e7dd22010-02-25 01:56:36 +0000149 else if (Step == 1 && LookInScope && S)
Douglas Gregor124b8782010-02-16 19:09:40 +0000150 LookupName(Found, S);
151 else
152 continue;
153
154 // FIXME: Should we be suppressing ambiguities here?
155 if (Found.isAmbiguous())
John McCallb3d87482010-08-24 05:47:05 +0000156 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000157
158 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
159 QualType T = Context.getTypeDeclType(Type);
Douglas Gregor124b8782010-02-16 19:09:40 +0000160
161 if (SearchType.isNull() || SearchType->isDependentType() ||
162 Context.hasSameUnqualifiedType(T, SearchType)) {
163 // We found our type!
164
John McCallb3d87482010-08-24 05:47:05 +0000165 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000166 }
167 }
168
169 // If the name that we found is a class template name, and it is
170 // the same name as the template name in the last part of the
171 // nested-name-specifier (if present) or the object type, then
172 // this is the destructor for that class.
173 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000174 // issue 399, for which there isn't even an obvious direction.
Douglas Gregor124b8782010-02-16 19:09:40 +0000175 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
176 QualType MemberOfType;
177 if (SS.isSet()) {
178 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
179 // Figure out the type of the context, if it has one.
John McCall3cb0ebd2010-03-10 03:28:59 +0000180 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
181 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregor124b8782010-02-16 19:09:40 +0000182 }
183 }
184 if (MemberOfType.isNull())
185 MemberOfType = SearchType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000186
Douglas Gregor124b8782010-02-16 19:09:40 +0000187 if (MemberOfType.isNull())
188 continue;
189
190 // We're referring into a class template specialization. If the
191 // class template we found is the same as the template being
192 // specialized, we found what we are looking for.
193 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
194 if (ClassTemplateSpecializationDecl *Spec
195 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
196 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
197 Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000198 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000199 }
200
201 continue;
202 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000203
Douglas Gregor124b8782010-02-16 19:09:40 +0000204 // We're referring to an unresolved class template
205 // specialization. Determine whether we class template we found
206 // is the same as the template being specialized or, if we don't
207 // know which template is being specialized, that it at least
208 // has the same name.
209 if (const TemplateSpecializationType *SpecType
210 = MemberOfType->getAs<TemplateSpecializationType>()) {
211 TemplateName SpecName = SpecType->getTemplateName();
212
213 // The class template we found is the same template being
214 // specialized.
215 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
216 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000217 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000218
219 continue;
220 }
221
222 // The class template we found has the same name as the
223 // (dependent) template name being specialized.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000224 if (DependentTemplateName *DepTemplate
Douglas Gregor124b8782010-02-16 19:09:40 +0000225 = SpecName.getAsDependentTemplateName()) {
226 if (DepTemplate->isIdentifier() &&
227 DepTemplate->getIdentifier() == Template->getIdentifier())
John McCallb3d87482010-08-24 05:47:05 +0000228 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000229
230 continue;
231 }
232 }
233 }
234 }
235
236 if (isDependent) {
237 // We didn't find our type, but that's okay: it's dependent
238 // anyway.
Douglas Gregore29425b2011-02-28 22:42:13 +0000239
240 // FIXME: What if we have no nested-name-specifier?
241 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
242 SS.getWithLocInContext(Context),
243 II, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000244 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000245 }
246
247 if (ObjectTypePtr)
248 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000249 << &II;
Douglas Gregor124b8782010-02-16 19:09:40 +0000250 else
251 Diag(NameLoc, diag::err_destructor_class_name);
252
John McCallb3d87482010-08-24 05:47:05 +0000253 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000254}
255
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000256/// \brief Build a C++ typeid expression with a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000257ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000258 SourceLocation TypeidLoc,
259 TypeSourceInfo *Operand,
260 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000261 // C++ [expr.typeid]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000262 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000263 // that is the operand of typeid are always ignored.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000264 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000265 // type, the class shall be completely-defined.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000266 Qualifiers Quals;
267 QualType T
268 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
269 Quals);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000270 if (T->getAs<RecordType>() &&
271 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
272 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000273
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000274 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
275 Operand,
276 SourceRange(TypeidLoc, RParenLoc)));
277}
278
279/// \brief Build a C++ typeid expression with an expression operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000280ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000281 SourceLocation TypeidLoc,
282 Expr *E,
283 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000284 bool isUnevaluatedOperand = true;
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000285 if (E && !E->isTypeDependent()) {
286 QualType T = E->getType();
287 if (const RecordType *RecordT = T->getAs<RecordType>()) {
288 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
289 // C++ [expr.typeid]p3:
290 // [...] If the type of the expression is a class type, the class
291 // shall be completely-defined.
292 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
293 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000294
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000295 // C++ [expr.typeid]p3:
Sebastian Redl906082e2010-07-20 04:20:21 +0000296 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000297 // polymorphic class type [...] [the] expression is an unevaluated
298 // operand. [...]
Sebastian Redl906082e2010-07-20 04:20:21 +0000299 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000300 isUnevaluatedOperand = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000301
302 // We require a vtable to query the type at run time.
303 MarkVTableUsed(TypeidLoc, RecordD);
304 }
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000305 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000306
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000307 // C++ [expr.typeid]p4:
308 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000309 // cv-qualified type, the result of the typeid expression refers to a
310 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000311 // type.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000312 Qualifiers Quals;
313 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
314 if (!Context.hasSameType(T, UnqualT)) {
315 T = UnqualT;
John McCall2de56d12010-08-25 11:45:40 +0000316 ImpCastExprToType(E, UnqualT, CK_NoOp, CastCategory(E));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000317 }
318 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000319
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000320 // If this is an unevaluated operand, clear out the set of
321 // declaration references we have been computing and eliminate any
322 // temporaries introduced in its computation.
323 if (isUnevaluatedOperand)
324 ExprEvalContexts.back().Context = Unevaluated;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000325
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000326 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCall9ae2f072010-08-23 23:25:46 +0000327 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000328 SourceRange(TypeidLoc, RParenLoc)));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000329}
330
331/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCall60d7b3a2010-08-24 06:29:42 +0000332ExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000333Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
334 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000335 // Find the std::type_info type.
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000336 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000337 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000338
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000339 if (!CXXTypeInfoDecl) {
340 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
341 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
342 LookupQualifiedName(R, getStdNamespace());
343 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
344 if (!CXXTypeInfoDecl)
345 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
346 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000347
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000348 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000349
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000350 if (isType) {
351 // The operand is a type; handle it as such.
352 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +0000353 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
354 &TInfo);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000355 if (T.isNull())
356 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000357
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000358 if (!TInfo)
359 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000360
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000361 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000362 }
Mike Stump1eb44332009-09-09 15:08:12 +0000363
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000364 // The operand is an expression.
John McCall9ae2f072010-08-23 23:25:46 +0000365 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000366}
367
Francois Pichet6915c522010-12-27 01:32:00 +0000368/// Retrieve the UuidAttr associated with QT.
369static UuidAttr *GetUuidAttrOfType(QualType QT) {
370 // Optionally remove one level of pointer, reference or array indirection.
John McCallf4c73712011-01-19 06:33:43 +0000371 const Type *Ty = QT.getTypePtr();;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000372 if (QT->isPointerType() || QT->isReferenceType())
373 Ty = QT->getPointeeType().getTypePtr();
374 else if (QT->isArrayType())
375 Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
376
Francois Pichet6915c522010-12-27 01:32:00 +0000377 // Loop all class definition and declaration looking for an uuid attribute.
378 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
379 while (RD) {
380 if (UuidAttr *Uuid = RD->getAttr<UuidAttr>())
381 return Uuid;
382 RD = RD->getPreviousDeclaration();
383 }
384 return 0;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000385}
386
Francois Pichet01b7c302010-09-08 12:20:18 +0000387/// \brief Build a Microsoft __uuidof expression with a type operand.
388ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
389 SourceLocation TypeidLoc,
390 TypeSourceInfo *Operand,
391 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000392 if (!Operand->getType()->isDependentType()) {
393 if (!GetUuidAttrOfType(Operand->getType()))
394 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
395 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000396
Francois Pichet01b7c302010-09-08 12:20:18 +0000397 // FIXME: add __uuidof semantic analysis for type operand.
398 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
399 Operand,
400 SourceRange(TypeidLoc, RParenLoc)));
401}
402
403/// \brief Build a Microsoft __uuidof expression with an expression operand.
404ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
405 SourceLocation TypeidLoc,
406 Expr *E,
407 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000408 if (!E->getType()->isDependentType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000409 if (!GetUuidAttrOfType(E->getType()) &&
Francois Pichet6915c522010-12-27 01:32:00 +0000410 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
411 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
412 }
413 // FIXME: add __uuidof semantic analysis for type operand.
Francois Pichet01b7c302010-09-08 12:20:18 +0000414 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
415 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000416 SourceRange(TypeidLoc, RParenLoc)));
Francois Pichet01b7c302010-09-08 12:20:18 +0000417}
418
419/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
420ExprResult
421Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
422 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000423 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet01b7c302010-09-08 12:20:18 +0000424 if (!MSVCGuidDecl) {
425 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
426 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
427 LookupQualifiedName(R, Context.getTranslationUnitDecl());
428 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
429 if (!MSVCGuidDecl)
430 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000431 }
432
Francois Pichet01b7c302010-09-08 12:20:18 +0000433 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000434
Francois Pichet01b7c302010-09-08 12:20:18 +0000435 if (isType) {
436 // The operand is a type; handle it as such.
437 TypeSourceInfo *TInfo = 0;
438 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
439 &TInfo);
440 if (T.isNull())
441 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000442
Francois Pichet01b7c302010-09-08 12:20:18 +0000443 if (!TInfo)
444 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
445
446 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
447 }
448
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000449 // The operand is an expression.
Francois Pichet01b7c302010-09-08 12:20:18 +0000450 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
451}
452
Steve Naroff1b273c42007-09-16 14:56:35 +0000453/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCall60d7b3a2010-08-24 06:29:42 +0000454ExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000455Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000456 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000457 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000458 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
459 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000460}
Chris Lattner50dd2892008-02-26 00:51:44 +0000461
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000462/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCall60d7b3a2010-08-24 06:29:42 +0000463ExprResult
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000464Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
465 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
466}
467
Chris Lattner50dd2892008-02-26 00:51:44 +0000468/// ActOnCXXThrow - Parse throw expressions.
John McCall60d7b3a2010-08-24 06:29:42 +0000469ExprResult
John McCall9ae2f072010-08-23 23:25:46 +0000470Sema::ActOnCXXThrow(SourceLocation OpLoc, Expr *Ex) {
Anders Carlsson729b8532011-02-23 03:46:46 +0000471 // Don't report an error if 'throw' is used in system headers.
Anders Carlsson15348ae2011-02-28 02:27:16 +0000472 if (!getLangOptions().CXXExceptions &&
Anders Carlsson729b8532011-02-23 03:46:46 +0000473 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb1fba312011-02-19 21:53:09 +0000474 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Anders Carlsson7f11d9c2011-02-19 19:26:44 +0000475
Sebastian Redl972041f2009-04-27 20:27:31 +0000476 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
477 return ExprError();
478 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
479}
480
481/// CheckCXXThrowOperand - Validate the operand of a throw.
482bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
483 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000484 // A throw-expression initializes a temporary object, called the exception
485 // object, the type of which is determined by removing any top-level
486 // cv-qualifiers from the static type of the operand of throw and adjusting
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000487 // the type from "array of T" or "function returning T" to "pointer to T"
Douglas Gregor154fe982009-12-23 22:04:40 +0000488 // or "pointer to function returning T", [...]
489 if (E->getType().hasQualifiers())
John McCall2de56d12010-08-25 11:45:40 +0000490 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
Sebastian Redl906082e2010-07-20 04:20:21 +0000491 CastCategory(E));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000492
Sebastian Redl972041f2009-04-27 20:27:31 +0000493 DefaultFunctionArrayConversion(E);
494
495 // If the type of the exception would be an incomplete type or a pointer
496 // to an incomplete type other than (cv) void the program is ill-formed.
497 QualType Ty = E->getType();
John McCallac418162010-04-22 01:10:34 +0000498 bool isPointer = false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000499 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000500 Ty = Ptr->getPointeeType();
John McCallac418162010-04-22 01:10:34 +0000501 isPointer = true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000502 }
503 if (!isPointer || !Ty->isVoidType()) {
504 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000505 PDiag(isPointer ? diag::err_throw_incomplete_ptr
506 : diag::err_throw_incomplete)
507 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000508 return true;
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000509
Douglas Gregorbf422f92010-04-15 18:05:39 +0000510 if (RequireNonAbstractType(ThrowLoc, E->getType(),
511 PDiag(diag::err_throw_abstract_type)
512 << E->getSourceRange()))
513 return true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000514 }
515
John McCallac418162010-04-22 01:10:34 +0000516 // Initialize the exception result. This implicitly weeds out
517 // abstract types or types with inaccessible copy constructors.
Douglas Gregor72dfa272011-01-21 22:46:35 +0000518 const VarDecl *NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
519
Douglas Gregorf5d8f462011-01-21 18:05:27 +0000520 // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p32.
John McCallac418162010-04-22 01:10:34 +0000521 InitializedEntity Entity =
Douglas Gregor72dfa272011-01-21 22:46:35 +0000522 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
523 /*NRVO=*/false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000524 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
Douglas Gregor72dfa272011-01-21 22:46:35 +0000525 QualType(), E);
John McCallac418162010-04-22 01:10:34 +0000526 if (Res.isInvalid())
527 return true;
528 E = Res.takeAs<Expr>();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000529
Eli Friedman5ed9b932010-06-03 20:39:03 +0000530 // If the exception has class type, we need additional handling.
531 const RecordType *RecordTy = Ty->getAs<RecordType>();
532 if (!RecordTy)
533 return false;
534 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
535
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000536 // If we are throwing a polymorphic class type or pointer thereof,
537 // exception handling will make use of the vtable.
Eli Friedman5ed9b932010-06-03 20:39:03 +0000538 MarkVTableUsed(ThrowLoc, RD);
539
Eli Friedman98efb9f2010-10-12 20:32:36 +0000540 // If a pointer is thrown, the referenced object will not be destroyed.
541 if (isPointer)
542 return false;
543
Eli Friedman5ed9b932010-06-03 20:39:03 +0000544 // If the class has a non-trivial destructor, we must be able to call it.
545 if (RD->hasTrivialDestructor())
546 return false;
547
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000548 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +0000549 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman5ed9b932010-06-03 20:39:03 +0000550 if (!Destructor)
551 return false;
552
553 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
554 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregored8abf12010-07-08 06:14:04 +0000555 PDiag(diag::err_access_dtor_exception) << Ty);
Sebastian Redl972041f2009-04-27 20:27:31 +0000556 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000557}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000558
John McCall5808ce42011-02-03 08:15:49 +0000559CXXMethodDecl *Sema::tryCaptureCXXThis() {
560 // Ignore block scopes: we can capture through them.
561 // Ignore nested enum scopes: we'll diagnose non-constant expressions
562 // where they're invalid, and other uses are legitimate.
563 // Don't ignore nested class scopes: you can't use 'this' in a local class.
John McCall469a1eb2011-02-02 13:00:07 +0000564 DeclContext *DC = CurContext;
John McCall5808ce42011-02-03 08:15:49 +0000565 while (true) {
566 if (isa<BlockDecl>(DC)) DC = cast<BlockDecl>(DC)->getDeclContext();
567 else if (isa<EnumDecl>(DC)) DC = cast<EnumDecl>(DC)->getDeclContext();
568 else break;
569 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000570
John McCall5808ce42011-02-03 08:15:49 +0000571 // If we're not in an instance method, error out.
John McCall469a1eb2011-02-02 13:00:07 +0000572 CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC);
573 if (!method || !method->isInstance())
John McCall5808ce42011-02-03 08:15:49 +0000574 return 0;
John McCall469a1eb2011-02-02 13:00:07 +0000575
576 // Mark that we're closing on 'this' in all the block scopes, if applicable.
577 for (unsigned idx = FunctionScopes.size() - 1;
578 isa<BlockScopeInfo>(FunctionScopes[idx]);
579 --idx)
580 cast<BlockScopeInfo>(FunctionScopes[idx])->CapturesCXXThis = true;
581
John McCall5808ce42011-02-03 08:15:49 +0000582 return method;
583}
584
585ExprResult Sema::ActOnCXXThis(SourceLocation loc) {
586 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
587 /// is a non-lvalue expression whose value is the address of the object for
588 /// which the function is called.
589
590 CXXMethodDecl *method = tryCaptureCXXThis();
591 if (!method) return Diag(loc, diag::err_invalid_this_use);
592
593 return Owned(new (Context) CXXThisExpr(loc, method->getThisType(Context),
John McCall469a1eb2011-02-02 13:00:07 +0000594 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000595}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000596
John McCall60d7b3a2010-08-24 06:29:42 +0000597ExprResult
Douglas Gregorab6677e2010-09-08 00:15:04 +0000598Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000599 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000600 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000601 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000602 if (!TypeRep)
603 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000604
John McCall9d125032010-01-15 18:39:57 +0000605 TypeSourceInfo *TInfo;
606 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
607 if (!TInfo)
608 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregorab6677e2010-09-08 00:15:04 +0000609
610 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
611}
612
613/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
614/// Can be interpreted either as function-style casting ("int(x)")
615/// or class type construction ("ClassType(x,y,z)")
616/// or creation of a value-initialized type ("int()").
617ExprResult
618Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
619 SourceLocation LParenLoc,
620 MultiExprArg exprs,
621 SourceLocation RParenLoc) {
622 QualType Ty = TInfo->getType();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000623 unsigned NumExprs = exprs.size();
624 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000625 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000626 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
627
Sebastian Redlf53597f2009-03-15 17:47:39 +0000628 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000629 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000630 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000631
Douglas Gregorab6677e2010-09-08 00:15:04 +0000632 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000633 LParenLoc,
634 Exprs, NumExprs,
635 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000636 }
637
Anders Carlssonbb60a502009-08-27 03:53:50 +0000638 if (Ty->isArrayType())
639 return ExprError(Diag(TyBeginLoc,
640 diag::err_value_init_for_array_type) << FullRange);
641 if (!Ty->isVoidType() &&
642 RequireCompleteType(TyBeginLoc, Ty,
643 PDiag(diag::err_invalid_incomplete_type_use)
644 << FullRange))
645 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000646
Anders Carlssonbb60a502009-08-27 03:53:50 +0000647 if (RequireNonAbstractType(TyBeginLoc, Ty,
648 diag::err_allocation_of_abstract_type))
649 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000650
651
Douglas Gregor506ae412009-01-16 18:33:17 +0000652 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000653 // If the expression list is a single expression, the type conversion
654 // expression is equivalent (in definedness, and if defined in meaning) to the
655 // corresponding cast expression.
656 //
657 if (NumExprs == 1) {
John McCalldaa8e4e2010-11-15 09:13:47 +0000658 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +0000659 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +0000660 CXXCastPath BasePath;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000661 if (CheckCastTypes(TInfo->getTypeLoc().getSourceRange(), Ty, Exprs[0],
John McCallf89e55a2010-11-18 06:31:45 +0000662 Kind, VK, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000663 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000664 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000665
666 exprs.release();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000667
John McCallf871d0c2010-08-07 06:22:56 +0000668 return Owned(CXXFunctionalCastExpr::Create(Context,
Douglas Gregorab6677e2010-09-08 00:15:04 +0000669 Ty.getNonLValueExprType(Context),
John McCallf89e55a2010-11-18 06:31:45 +0000670 VK, TInfo, TyBeginLoc, Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000671 Exprs[0], &BasePath,
672 RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000673 }
674
Douglas Gregor19311e72010-09-08 21:40:08 +0000675 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
676 InitializationKind Kind
677 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
678 LParenLoc, RParenLoc)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000679 : InitializationKind::CreateValue(TyBeginLoc,
Douglas Gregor19311e72010-09-08 21:40:08 +0000680 LParenLoc, RParenLoc);
681 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
682 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redlf53597f2009-03-15 17:47:39 +0000683
Douglas Gregor19311e72010-09-08 21:40:08 +0000684 // FIXME: Improve AST representation?
685 return move(Result);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000686}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000687
John McCall6ec278d2011-01-27 09:37:56 +0000688/// doesUsualArrayDeleteWantSize - Answers whether the usual
689/// operator delete[] for the given type has a size_t parameter.
690static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
691 QualType allocType) {
692 const RecordType *record =
693 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
694 if (!record) return false;
695
696 // Try to find an operator delete[] in class scope.
697
698 DeclarationName deleteName =
699 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
700 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
701 S.LookupQualifiedName(ops, record->getDecl());
702
703 // We're just doing this for information.
704 ops.suppressDiagnostics();
705
706 // Very likely: there's no operator delete[].
707 if (ops.empty()) return false;
708
709 // If it's ambiguous, it should be illegal to call operator delete[]
710 // on this thing, so it doesn't matter if we allocate extra space or not.
711 if (ops.isAmbiguous()) return false;
712
713 LookupResult::Filter filter = ops.makeFilter();
714 while (filter.hasNext()) {
715 NamedDecl *del = filter.next()->getUnderlyingDecl();
716
717 // C++0x [basic.stc.dynamic.deallocation]p2:
718 // A template instance is never a usual deallocation function,
719 // regardless of its signature.
720 if (isa<FunctionTemplateDecl>(del)) {
721 filter.erase();
722 continue;
723 }
724
725 // C++0x [basic.stc.dynamic.deallocation]p2:
726 // If class T does not declare [an operator delete[] with one
727 // parameter] but does declare a member deallocation function
728 // named operator delete[] with exactly two parameters, the
729 // second of which has type std::size_t, then this function
730 // is a usual deallocation function.
731 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
732 filter.erase();
733 continue;
734 }
735 }
736 filter.done();
737
738 if (!ops.isSingleResult()) return false;
739
740 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
741 return (del->getNumParams() == 2);
742}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000743
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000744/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
745/// @code new (memory) int[size][4] @endcode
746/// or
747/// @code ::new Foo(23, "hello") @endcode
748/// For the interpretation of this heap of arguments, consult the base version.
John McCall60d7b3a2010-08-24 06:29:42 +0000749ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000750Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000751 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000752 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000753 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000754 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000755 SourceLocation ConstructorRParen) {
Richard Smith34b41d92011-02-20 03:19:35 +0000756 bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
757
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000758 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000759 // If the specified type is an array, unwrap it and save the expression.
760 if (D.getNumTypeObjects() > 0 &&
761 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
762 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smith34b41d92011-02-20 03:19:35 +0000763 if (TypeContainsAuto)
764 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
765 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000766 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000767 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
768 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000769 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000770 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
771 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000772
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000773 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000774 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000775 }
776
Douglas Gregor043cad22009-09-11 00:18:58 +0000777 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000778 if (ArraySize) {
779 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000780 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
781 break;
782
783 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
784 if (Expr *NumElts = (Expr *)Array.NumElts) {
785 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
786 !NumElts->isIntegerConstantExpr(Context)) {
787 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
788 << NumElts->getSourceRange();
789 return ExprError();
790 }
791 }
792 }
793 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000794
Richard Smith34b41d92011-02-20 03:19:35 +0000795 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0, /*OwnedDecl=*/0,
796 /*AllowAuto=*/true);
John McCallbf1a0282010-06-04 23:28:52 +0000797 QualType AllocType = TInfo->getType();
Chris Lattnereaaebc72009-04-25 08:06:05 +0000798 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000799 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000800
Mike Stump1eb44332009-09-09 15:08:12 +0000801 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000802 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000803 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000804 PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000805 TypeIdParens,
Mike Stump1eb44332009-09-09 15:08:12 +0000806 AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000807 TInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000808 ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000809 ConstructorLParen,
810 move(ConstructorArgs),
Richard Smith34b41d92011-02-20 03:19:35 +0000811 ConstructorRParen,
812 TypeContainsAuto);
Douglas Gregor3433cf72009-05-21 00:00:09 +0000813}
814
John McCall60d7b3a2010-08-24 06:29:42 +0000815ExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000816Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
817 SourceLocation PlacementLParen,
818 MultiExprArg PlacementArgs,
819 SourceLocation PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000820 SourceRange TypeIdParens,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000821 QualType AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000822 TypeSourceInfo *AllocTypeInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000823 Expr *ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000824 SourceLocation ConstructorLParen,
825 MultiExprArg ConstructorArgs,
Richard Smith34b41d92011-02-20 03:19:35 +0000826 SourceLocation ConstructorRParen,
827 bool TypeMayContainAuto) {
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000828 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000829
Richard Smith34b41d92011-02-20 03:19:35 +0000830 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
831 if (TypeMayContainAuto && AllocType->getContainedAutoType()) {
832 if (ConstructorArgs.size() == 0)
833 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
834 << AllocType << TypeRange);
835 if (ConstructorArgs.size() != 1) {
836 Expr *FirstBad = ConstructorArgs.get()[1];
837 return ExprError(Diag(FirstBad->getSourceRange().getBegin(),
838 diag::err_auto_new_ctor_multiple_expressions)
839 << AllocType << TypeRange);
840 }
841 QualType DeducedType;
842 if (!DeduceAutoType(AllocType, ConstructorArgs.get()[0], DeducedType))
843 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
844 << AllocType
845 << ConstructorArgs.get()[0]->getType()
846 << TypeRange
847 << ConstructorArgs.get()[0]->getSourceRange());
848
849 AllocType = DeducedType;
850 AllocTypeInfo = Context.getTrivialTypeSourceInfo(AllocType, StartLoc);
851 }
852
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000853 // Per C++0x [expr.new]p5, the type being constructed may be a
854 // typedef of an array type.
John McCall9ae2f072010-08-23 23:25:46 +0000855 if (!ArraySize) {
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000856 if (const ConstantArrayType *Array
857 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000858 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
859 Context.getSizeType(),
860 TypeRange.getEnd());
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000861 AllocType = Array->getElementType();
862 }
863 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000864
Douglas Gregora0750762010-10-06 16:00:31 +0000865 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
866 return ExprError();
867
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000868 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000869
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000870 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
871 // or enumeration type with a non-negative value."
Sebastian Redl28507842009-02-26 14:39:58 +0000872 if (ArraySize && !ArraySize->isTypeDependent()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000873
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000874 QualType SizeType = ArraySize->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000875
John McCall60d7b3a2010-08-24 06:29:42 +0000876 ExprResult ConvertedSize
John McCall9ae2f072010-08-23 23:25:46 +0000877 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000878 PDiag(diag::err_array_size_not_integral),
879 PDiag(diag::err_array_size_incomplete_type)
880 << ArraySize->getSourceRange(),
881 PDiag(diag::err_array_size_explicit_conversion),
882 PDiag(diag::note_array_size_conversion),
883 PDiag(diag::err_array_size_ambiguous_conversion),
884 PDiag(diag::note_array_size_conversion),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000885 PDiag(getLangOptions().CPlusPlus0x? 0
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000886 : diag::ext_array_size_conversion));
887 if (ConvertedSize.isInvalid())
888 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000889
John McCall9ae2f072010-08-23 23:25:46 +0000890 ArraySize = ConvertedSize.take();
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000891 SizeType = ArraySize->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000892 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000893 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000894
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000895 // Let's see if this is a constant < 0. If so, we reject it out of hand.
896 // We don't care about special rules, so we tell the machinery it's not
897 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000898 if (!ArraySize->isValueDependent()) {
899 llvm::APSInt Value;
900 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
901 if (Value < llvm::APSInt(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000902 llvm::APInt::getNullValue(Value.getBitWidth()),
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000903 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000904 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +0000905 diag::err_typecheck_negative_array_size)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000906 << ArraySize->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000907
Douglas Gregor2767ce22010-08-18 00:39:00 +0000908 if (!AllocType->isDependentType()) {
909 unsigned ActiveSizeBits
910 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
911 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000912 Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +0000913 diag::err_array_too_large)
914 << Value.toString(10)
915 << ArraySize->getSourceRange();
916 return ExprError();
917 }
918 }
Douglas Gregor4bd40312010-07-13 15:54:32 +0000919 } else if (TypeIdParens.isValid()) {
920 // Can't have dynamic array size when the type-id is in parentheses.
921 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
922 << ArraySize->getSourceRange()
923 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
924 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000925
Douglas Gregor4bd40312010-07-13 15:54:32 +0000926 TypeIdParens = SourceRange();
Sebastian Redl28507842009-02-26 14:39:58 +0000927 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000928 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000929
Eli Friedman73c39ab2009-10-20 08:27:19 +0000930 ImpCastExprToType(ArraySize, Context.getSizeType(),
John McCall2de56d12010-08-25 11:45:40 +0000931 CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000932 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000933
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000934 FunctionDecl *OperatorNew = 0;
935 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000936 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
937 unsigned NumPlaceArgs = PlacementArgs.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000938
Sebastian Redl28507842009-02-26 14:39:58 +0000939 if (!AllocType->isDependentType() &&
940 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
941 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000942 SourceRange(PlacementLParen, PlacementRParen),
943 UseGlobal, AllocType, ArraySize, PlaceArgs,
944 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000945 return ExprError();
John McCall6ec278d2011-01-27 09:37:56 +0000946
947 // If this is an array allocation, compute whether the usual array
948 // deallocation function for the type has a size_t parameter.
949 bool UsualArrayDeleteWantsSize = false;
950 if (ArraySize && !AllocType->isDependentType())
951 UsualArrayDeleteWantsSize
952 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
953
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000954 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000955 if (OperatorNew) {
956 // Add default arguments, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000957 const FunctionProtoType *Proto =
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000958 OperatorNew->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000959 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000960 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000961
Anders Carlsson28e94832010-05-03 02:07:56 +0000962 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000963 Proto, 1, PlaceArgs, NumPlaceArgs,
Anders Carlsson28e94832010-05-03 02:07:56 +0000964 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000965 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000966
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000967 NumPlaceArgs = AllPlaceArgs.size();
968 if (NumPlaceArgs > 0)
969 PlaceArgs = &AllPlaceArgs[0];
970 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000971
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000972 bool Init = ConstructorLParen.isValid();
973 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000974 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000975 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
976 unsigned NumConsArgs = ConstructorArgs.size();
John McCallca0408f2010-08-23 06:44:23 +0000977 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000978
Anders Carlsson48c95012010-05-03 15:45:23 +0000979 // Array 'new' can't have any initializers.
Anders Carlsson55cbd6e2010-05-16 16:24:20 +0000980 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlsson48c95012010-05-03 15:45:23 +0000981 SourceRange InitRange(ConsArgs[0]->getLocStart(),
982 ConsArgs[NumConsArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000983
Anders Carlsson48c95012010-05-03 15:45:23 +0000984 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
985 return ExprError();
986 }
987
Douglas Gregor99a2e602009-12-16 01:38:02 +0000988 if (!AllocType->isDependentType() &&
989 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
990 // C++0x [expr.new]p15:
991 // A new-expression that creates an object of type T initializes that
992 // object as follows:
993 InitializationKind Kind
994 // - If the new-initializer is omitted, the object is default-
995 // initialized (8.5); if no initialization is performed,
996 // the object has indeterminate value
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000997 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000998 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor99a2e602009-12-16 01:38:02 +0000999 // initialization rules of 8.5 for direct-initialization.
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001000 : InitializationKind::CreateDirect(TypeRange.getBegin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001001 ConstructorLParen,
Douglas Gregor99a2e602009-12-16 01:38:02 +00001002 ConstructorRParen);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001003
Douglas Gregor99a2e602009-12-16 01:38:02 +00001004 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00001005 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001006 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001007 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor99a2e602009-12-16 01:38:02 +00001008 move(ConstructorArgs));
1009 if (FullInit.isInvalid())
1010 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001011
1012 // FullInit is our initializer; walk through it to determine if it's a
Douglas Gregor99a2e602009-12-16 01:38:02 +00001013 // constructor call, which CXXNewExpr handles directly.
1014 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
1015 if (CXXBindTemporaryExpr *Binder
1016 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
1017 FullInitExpr = Binder->getSubExpr();
1018 if (CXXConstructExpr *Construct
1019 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
1020 Constructor = Construct->getConstructor();
1021 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
1022 AEnd = Construct->arg_end();
1023 A != AEnd; ++A)
John McCall3fa5cae2010-10-26 07:05:15 +00001024 ConvertedConstructorArgs.push_back(*A);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001025 } else {
1026 // Take the converted initializer.
1027 ConvertedConstructorArgs.push_back(FullInit.release());
1028 }
1029 } else {
1030 // No initialization required.
1031 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001032
Douglas Gregor99a2e602009-12-16 01:38:02 +00001033 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +00001034 NumConsArgs = ConvertedConstructorArgs.size();
1035 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001036 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001037
Douglas Gregor6d908702010-02-26 05:06:18 +00001038 // Mark the new and delete operators as referenced.
1039 if (OperatorNew)
1040 MarkDeclarationReferenced(StartLoc, OperatorNew);
1041 if (OperatorDelete)
1042 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1043
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001044 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001045
Sebastian Redlf53597f2009-03-15 17:47:39 +00001046 PlacementArgs.release();
1047 ConstructorArgs.release();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001048
Ted Kremenekad7fe862010-02-11 22:51:03 +00001049 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregor4bd40312010-07-13 15:54:32 +00001050 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001051 ArraySize, Constructor, Init,
1052 ConsArgs, NumConsArgs, OperatorDelete,
John McCall6ec278d2011-01-27 09:37:56 +00001053 UsualArrayDeleteWantsSize,
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001054 ResultType, AllocTypeInfo,
1055 StartLoc,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001056 Init ? ConstructorRParen :
Chandler Carruth428edaf2010-10-25 08:47:36 +00001057 TypeRange.getEnd(),
1058 ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001059}
1060
1061/// CheckAllocatedType - Checks that a type is suitable as the allocated type
1062/// in a new-expression.
1063/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +00001064bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00001065 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001066 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1067 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +00001068 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001069 return Diag(Loc, diag::err_bad_new_type)
1070 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001071 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001072 return Diag(Loc, diag::err_bad_new_type)
1073 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001074 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +00001075 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001076 PDiag(diag::err_new_incomplete_type)
1077 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001078 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +00001079 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +00001080 diag::err_allocation_of_abstract_type))
1081 return true;
Douglas Gregora0750762010-10-06 16:00:31 +00001082 else if (AllocType->isVariablyModifiedType())
1083 return Diag(Loc, diag::err_variably_modified_new_type)
1084 << AllocType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001085
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001086 return false;
1087}
1088
Douglas Gregor6d908702010-02-26 05:06:18 +00001089/// \brief Determine whether the given function is a non-placement
1090/// deallocation function.
1091static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1092 if (FD->isInvalidDecl())
1093 return false;
1094
1095 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1096 return Method->isUsualDeallocationFunction();
1097
1098 return ((FD->getOverloadedOperator() == OO_Delete ||
1099 FD->getOverloadedOperator() == OO_Array_Delete) &&
1100 FD->getNumParams() == 1);
1101}
1102
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001103/// FindAllocationFunctions - Finds the overloads of operator new and delete
1104/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001105bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1106 bool UseGlobal, QualType AllocType,
1107 bool IsArray, Expr **PlaceArgs,
1108 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001109 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +00001110 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001111 // --- Choosing an allocation function ---
1112 // C++ 5.3.4p8 - 14 & 18
1113 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1114 // in the scope of the allocated class.
1115 // 2) If an array size is given, look for operator new[], else look for
1116 // operator new.
1117 // 3) The first argument is always size_t. Append the arguments from the
1118 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001119
1120 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
1121 // We don't care about the actual value of this argument.
1122 // FIXME: Should the Sema create the expression and embed it in the syntax
1123 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00001124 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Anders Carlssond67c4c32009-08-16 20:29:29 +00001125 Context.Target.getPointerWidth(0)),
1126 Context.getSizeType(),
1127 SourceLocation());
1128 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001129 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1130
Douglas Gregor6d908702010-02-26 05:06:18 +00001131 // C++ [expr.new]p8:
1132 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001133 // function's name is operator new and the deallocation function's
Douglas Gregor6d908702010-02-26 05:06:18 +00001134 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001135 // type, the allocation function's name is operator new[] and the
1136 // deallocation function's name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001137 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1138 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +00001139 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1140 IsArray ? OO_Array_Delete : OO_Delete);
1141
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001142 QualType AllocElemType = Context.getBaseElementType(AllocType);
1143
1144 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +00001145 CXXRecordDecl *Record
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001146 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +00001147 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001148 AllocArgs.size(), Record, /*AllowMissing=*/true,
1149 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001150 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001151 }
1152 if (!OperatorNew) {
1153 // Didn't find a member overload. Look for a global one.
1154 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +00001155 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +00001156 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001157 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1158 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001159 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001160 }
1161
John McCall9c82afc2010-04-20 02:18:25 +00001162 // We don't need an operator delete if we're running under
1163 // -fno-exceptions.
1164 if (!getLangOptions().Exceptions) {
1165 OperatorDelete = 0;
1166 return false;
1167 }
1168
Anders Carlssond9583892009-05-31 20:26:12 +00001169 // FindAllocationOverload can change the passed in arguments, so we need to
1170 // copy them back.
1171 if (NumPlaceArgs > 0)
1172 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001173
Douglas Gregor6d908702010-02-26 05:06:18 +00001174 // C++ [expr.new]p19:
1175 //
1176 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001177 // deallocation function's name is looked up in the global
Douglas Gregor6d908702010-02-26 05:06:18 +00001178 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001179 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6d908702010-02-26 05:06:18 +00001180 // the scope of T. If this lookup fails to find the name, or if
1181 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001182 // deallocation function's name is looked up in the global scope.
Douglas Gregor6d908702010-02-26 05:06:18 +00001183 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001184 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001185 CXXRecordDecl *RD
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001186 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6d908702010-02-26 05:06:18 +00001187 LookupQualifiedName(FoundDelete, RD);
1188 }
John McCall90c8c572010-03-18 08:19:33 +00001189 if (FoundDelete.isAmbiguous())
1190 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +00001191
1192 if (FoundDelete.empty()) {
1193 DeclareGlobalNewDelete();
1194 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1195 }
1196
1197 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +00001198
1199 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1200
John McCalledeb6c92010-09-14 21:34:24 +00001201 // Whether we're looking for a placement operator delete is dictated
1202 // by whether we selected a placement operator new, not by whether
1203 // we had explicit placement arguments. This matters for things like
1204 // struct A { void *operator new(size_t, int = 0); ... };
1205 // A *a = new A()
1206 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1207
1208 if (isPlacementNew) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001209 // C++ [expr.new]p20:
1210 // A declaration of a placement deallocation function matches the
1211 // declaration of a placement allocation function if it has the
1212 // same number of parameters and, after parameter transformations
1213 // (8.3.5), all parameter types except the first are
1214 // identical. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001215 //
Douglas Gregor6d908702010-02-26 05:06:18 +00001216 // To perform this comparison, we compute the function type that
1217 // the deallocation function should have, and use that type both
1218 // for template argument deduction and for comparison purposes.
John McCalle23cf432010-12-14 08:05:40 +00001219 //
1220 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6d908702010-02-26 05:06:18 +00001221 QualType ExpectedFunctionType;
1222 {
1223 const FunctionProtoType *Proto
1224 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00001225
Douglas Gregor6d908702010-02-26 05:06:18 +00001226 llvm::SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001227 ArgTypes.push_back(Context.VoidPtrTy);
Douglas Gregor6d908702010-02-26 05:06:18 +00001228 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1229 ArgTypes.push_back(Proto->getArgType(I));
1230
John McCalle23cf432010-12-14 08:05:40 +00001231 FunctionProtoType::ExtProtoInfo EPI;
1232 EPI.Variadic = Proto->isVariadic();
1233
Douglas Gregor6d908702010-02-26 05:06:18 +00001234 ExpectedFunctionType
1235 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
John McCalle23cf432010-12-14 08:05:40 +00001236 ArgTypes.size(), EPI);
Douglas Gregor6d908702010-02-26 05:06:18 +00001237 }
1238
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001239 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001240 DEnd = FoundDelete.end();
1241 D != DEnd; ++D) {
1242 FunctionDecl *Fn = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001243 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6d908702010-02-26 05:06:18 +00001244 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1245 // Perform template argument deduction to try to match the
1246 // expected function type.
1247 TemplateDeductionInfo Info(Context, StartLoc);
1248 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1249 continue;
1250 } else
1251 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1252
1253 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001254 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001255 }
1256 } else {
1257 // C++ [expr.new]p20:
1258 // [...] Any non-placement deallocation function matches a
1259 // non-placement allocation function. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001260 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001261 DEnd = FoundDelete.end();
1262 D != DEnd; ++D) {
1263 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1264 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001265 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001266 }
1267 }
1268
1269 // C++ [expr.new]p20:
1270 // [...] If the lookup finds a single matching deallocation
1271 // function, that function will be called; otherwise, no
1272 // deallocation function will be called.
1273 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001274 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001275
1276 // C++0x [expr.new]p20:
1277 // If the lookup finds the two-parameter form of a usual
1278 // deallocation function (3.7.4.2) and that function, considered
1279 // as a placement deallocation function, would have been
1280 // selected as a match for the allocation function, the program
1281 // is ill-formed.
1282 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1283 isNonPlacementDeallocationFunction(OperatorDelete)) {
1284 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001285 << SourceRange(PlaceArgs[0]->getLocStart(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001286 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1287 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1288 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001289 } else {
1290 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001291 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001292 }
1293 }
1294
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001295 return false;
1296}
1297
Sebastian Redl7f662392008-12-04 22:20:51 +00001298/// FindAllocationOverload - Find an fitting overload for the allocation
1299/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001300bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1301 DeclarationName Name, Expr** Args,
1302 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +00001303 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001304 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1305 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001306 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001307 if (AllowMissing)
1308 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001309 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001310 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001311 }
1312
John McCall90c8c572010-03-18 08:19:33 +00001313 if (R.isAmbiguous())
1314 return true;
1315
1316 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001317
John McCall5769d612010-02-08 23:07:23 +00001318 OverloadCandidateSet Candidates(StartLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001319 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001320 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001321 // Even member operator new/delete are implicitly treated as
1322 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001323 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001324
John McCall9aa472c2010-03-19 07:35:19 +00001325 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1326 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001327 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1328 Candidates,
1329 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001330 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001331 }
1332
John McCall9aa472c2010-03-19 07:35:19 +00001333 FunctionDecl *Fn = cast<FunctionDecl>(D);
1334 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001335 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001336 }
1337
1338 // Do the resolution.
1339 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00001340 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001341 case OR_Success: {
1342 // Got one!
1343 FunctionDecl *FnDecl = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00001344 MarkDeclarationReferenced(StartLoc, FnDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001345 // The first argument is size_t, and the first parameter must be size_t,
1346 // too. This is checked on declaration and can be assumed. (It can't be
1347 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001348 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001349 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1350 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
John McCall60d7b3a2010-08-24 06:29:42 +00001351 ExprResult Result
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001352 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001353 Context,
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001354 FnDecl->getParamDecl(i)),
1355 SourceLocation(),
John McCall3fa5cae2010-10-26 07:05:15 +00001356 Owned(Args[i]));
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001357 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001358 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001359
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001360 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001361 }
1362 Operator = FnDecl;
John McCall9aa472c2010-03-19 07:35:19 +00001363 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001364 return false;
1365 }
1366
1367 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +00001368 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001369 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001370 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001371 return true;
1372
1373 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +00001374 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +00001375 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001376 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001377 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001378
1379 case OR_Deleted:
1380 Diag(StartLoc, diag::err_ovl_deleted_call)
1381 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00001382 << Name
1383 << Best->Function->getMessageUnavailableAttr(
1384 !Best->Function->isDeleted())
1385 << Range;
John McCall120d63c2010-08-24 20:38:10 +00001386 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001387 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001388 }
1389 assert(false && "Unreachable, bad result from BestViableFunction");
1390 return true;
1391}
1392
1393
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001394/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1395/// delete. These are:
1396/// @code
1397/// void* operator new(std::size_t) throw(std::bad_alloc);
1398/// void* operator new[](std::size_t) throw(std::bad_alloc);
1399/// void operator delete(void *) throw();
1400/// void operator delete[](void *) throw();
1401/// @endcode
1402/// Note that the placement and nothrow forms of new are *not* implicitly
1403/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001404void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001405 if (GlobalNewDeleteDeclared)
1406 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001407
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001408 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001409 // [...] The following allocation and deallocation functions (18.4) are
1410 // implicitly declared in global scope in each translation unit of a
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001411 // program
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001412 //
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001413 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001414 // void* operator new[](std::size_t) throw(std::bad_alloc);
1415 // void operator delete(void*) throw();
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001416 // void operator delete[](void*) throw();
1417 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001418 // These implicit declarations introduce only the function names operator
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001419 // new, operator new[], operator delete, operator delete[].
1420 //
1421 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1422 // "std" or "bad_alloc" as necessary to form the exception specification.
1423 // However, we do not make these implicit declarations visible to name
1424 // lookup.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001425 if (!StdBadAlloc) {
1426 // The "std::bad_alloc" class has not yet been declared, so build it
1427 // implicitly.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001428 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1429 getOrCreateStdNamespace(),
1430 SourceLocation(),
1431 &PP.getIdentifierTable().get("bad_alloc"),
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001432 SourceLocation(), 0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001433 getStdBadAlloc()->setImplicit(true);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001434 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001435
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001436 GlobalNewDeleteDeclared = true;
1437
1438 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1439 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001440 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001441
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001442 DeclareGlobalAllocationFunction(
1443 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001444 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001445 DeclareGlobalAllocationFunction(
1446 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001447 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001448 DeclareGlobalAllocationFunction(
1449 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1450 Context.VoidTy, VoidPtr);
1451 DeclareGlobalAllocationFunction(
1452 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1453 Context.VoidTy, VoidPtr);
1454}
1455
1456/// DeclareGlobalAllocationFunction - Declares a single implicit global
1457/// allocation function if it doesn't already exist.
1458void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001459 QualType Return, QualType Argument,
1460 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001461 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1462
1463 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001464 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001465 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001466 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001467 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001468 // Only look at non-template functions, as it is the predefined,
1469 // non-templated allocation function we are trying to declare here.
1470 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1471 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001472 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001473 Func->getParamDecl(0)->getType().getUnqualifiedType());
1474 // FIXME: Do we need to check for default arguments here?
Douglas Gregor7b868622010-08-18 15:06:25 +00001475 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1476 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00001477 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001478 return;
Douglas Gregor7b868622010-08-18 15:06:25 +00001479 }
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001480 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001481 }
1482 }
1483
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001484 QualType BadAllocType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001485 bool HasBadAllocExceptionSpec
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001486 = (Name.getCXXOverloadedOperator() == OO_New ||
1487 Name.getCXXOverloadedOperator() == OO_Array_New);
1488 if (HasBadAllocExceptionSpec) {
1489 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001490 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001491 }
John McCalle23cf432010-12-14 08:05:40 +00001492
1493 FunctionProtoType::ExtProtoInfo EPI;
1494 EPI.HasExceptionSpec = true;
1495 if (HasBadAllocExceptionSpec) {
1496 EPI.NumExceptions = 1;
1497 EPI.Exceptions = &BadAllocType;
1498 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001499
John McCalle23cf432010-12-14 08:05:40 +00001500 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001501 FunctionDecl *Alloc =
1502 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCalld931b082010-08-26 03:08:43 +00001503 FnType, /*TInfo=*/0, SC_None,
1504 SC_None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001505 Alloc->setImplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001506
Nuno Lopesfc284482009-12-16 16:59:22 +00001507 if (AddMallocAttr)
Sean Huntcf807c42010-08-18 23:23:40 +00001508 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001509
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001510 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00001511 0, Argument, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00001512 SC_None,
1513 SC_None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00001514 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001515
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001516 // FIXME: Also add this declaration to the IdentifierResolver, but
1517 // make sure it is at the end of the chain to coincide with the
1518 // global scope.
John McCall5f1e0942010-08-24 08:50:51 +00001519 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001520}
1521
Anders Carlsson78f74552009-11-15 18:45:20 +00001522bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1523 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00001524 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001525 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001526 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001527 LookupQualifiedName(Found, RD);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001528
John McCalla24dc2e2009-11-17 02:14:36 +00001529 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001530 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001531
Chandler Carruth23893242010-06-28 00:30:51 +00001532 Found.suppressDiagnostics();
1533
John McCall046a7462010-08-04 00:31:26 +00001534 llvm::SmallVector<DeclAccessPair,4> Matches;
Anders Carlsson78f74552009-11-15 18:45:20 +00001535 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1536 F != FEnd; ++F) {
Chandler Carruth09556fd2010-08-08 07:04:00 +00001537 NamedDecl *ND = (*F)->getUnderlyingDecl();
1538
1539 // Ignore template operator delete members from the check for a usual
1540 // deallocation function.
1541 if (isa<FunctionTemplateDecl>(ND))
1542 continue;
1543
1544 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall046a7462010-08-04 00:31:26 +00001545 Matches.push_back(F.getPair());
1546 }
1547
1548 // There's exactly one suitable operator; pick it.
1549 if (Matches.size() == 1) {
1550 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
1551 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1552 Matches[0]);
1553 return false;
1554
1555 // We found multiple suitable operators; complain about the ambiguity.
1556 } else if (!Matches.empty()) {
1557 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1558 << Name << RD;
1559
1560 for (llvm::SmallVectorImpl<DeclAccessPair>::iterator
1561 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1562 Diag((*F)->getUnderlyingDecl()->getLocation(),
1563 diag::note_member_declared_here) << Name;
1564 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001565 }
1566
1567 // We did find operator delete/operator delete[] declarations, but
1568 // none of them were suitable.
1569 if (!Found.empty()) {
1570 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1571 << Name << RD;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001572
Anders Carlsson78f74552009-11-15 18:45:20 +00001573 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
John McCall046a7462010-08-04 00:31:26 +00001574 F != FEnd; ++F)
1575 Diag((*F)->getUnderlyingDecl()->getLocation(),
1576 diag::note_member_declared_here) << Name;
Anders Carlsson78f74552009-11-15 18:45:20 +00001577
1578 return true;
1579 }
1580
1581 // Look for a global declaration.
1582 DeclareGlobalNewDelete();
1583 DeclContext *TUDecl = Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001584
Anders Carlsson78f74552009-11-15 18:45:20 +00001585 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1586 Expr* DeallocArgs[1];
1587 DeallocArgs[0] = &Null;
1588 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1589 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1590 Operator))
1591 return true;
1592
1593 assert(Operator && "Did not find a deallocation function!");
1594 return false;
1595}
1596
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001597/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1598/// @code ::delete ptr; @endcode
1599/// or
1600/// @code delete [] ptr; @endcode
John McCall60d7b3a2010-08-24 06:29:42 +00001601ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001602Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John McCall9ae2f072010-08-23 23:25:46 +00001603 bool ArrayForm, Expr *Ex) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001604 // C++ [expr.delete]p1:
1605 // The operand shall have a pointer type, or a class type having a single
1606 // conversion function to a pointer type. The result has type void.
1607 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001608 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1609
Anders Carlssond67c4c32009-08-16 20:29:29 +00001610 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001611 bool ArrayFormAsWritten = ArrayForm;
John McCall6ec278d2011-01-27 09:37:56 +00001612 bool UsualArrayDeleteWantsSize = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001613
Sebastian Redl28507842009-02-26 14:39:58 +00001614 if (!Ex->isTypeDependent()) {
1615 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001616
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001617 if (const RecordType *Record = Type->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001618 if (RequireCompleteType(StartLoc, Type,
Douglas Gregor254a9422010-07-29 14:44:35 +00001619 PDiag(diag::err_delete_incomplete_class_type)))
1620 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001621
John McCall32daa422010-03-31 01:36:47 +00001622 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1623
Fariborz Jahanian53462782009-09-11 21:44:33 +00001624 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001625 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001626 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001627 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001628 NamedDecl *D = I.getDecl();
1629 if (isa<UsingShadowDecl>(D))
1630 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1631
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001632 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001633 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001634 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001635
John McCall32daa422010-03-31 01:36:47 +00001636 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001637
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001638 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1639 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedman13578692010-08-05 02:49:48 +00001640 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001641 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001642 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001643 if (ObjectPtrConversions.size() == 1) {
1644 // We have a single conversion to a pointer-to-object type. Perform
1645 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001646 // TODO: don't redo the conversion calculation.
John McCall32daa422010-03-31 01:36:47 +00001647 if (!PerformImplicitConversion(Ex,
1648 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +00001649 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001650 Type = Ex->getType();
1651 }
1652 }
1653 else if (ObjectPtrConversions.size() > 1) {
1654 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1655 << Type << Ex->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001656 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1657 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001658 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001659 }
Sebastian Redl28507842009-02-26 14:39:58 +00001660 }
1661
Sebastian Redlf53597f2009-03-15 17:47:39 +00001662 if (!Type->isPointerType())
1663 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1664 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001665
Ted Kremenek6217b802009-07-29 21:53:49 +00001666 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor94a61572010-05-24 17:01:56 +00001667 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001668 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregor94a61572010-05-24 17:01:56 +00001669 // effectively bans deletion of "void*". However, most compilers support
1670 // this, so we treat it as a warning unless we're in a SFINAE context.
1671 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1672 << Type << Ex->getSourceRange();
1673 } else if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001674 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1675 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001676 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001677 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +00001678 PDiag(diag::warn_delete_incomplete)
1679 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001680 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +00001681
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001682 // C++ [expr.delete]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001683 // [Note: a pointer to a const type can be the operand of a
1684 // delete-expression; it is not necessary to cast away the constness
1685 // (5.2.11) of the pointer expression before it is used as the operand
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001686 // of the delete-expression. ]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001687 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
John McCall2de56d12010-08-25 11:45:40 +00001688 CK_NoOp);
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001689
1690 if (Pointee->isArrayType() && !ArrayForm) {
1691 Diag(StartLoc, diag::warn_delete_array_type)
1692 << Type << Ex->getSourceRange()
1693 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1694 ArrayForm = true;
1695 }
1696
Anders Carlssond67c4c32009-08-16 20:29:29 +00001697 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1698 ArrayForm ? OO_Array_Delete : OO_Delete);
1699
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001700 QualType PointeeElem = Context.getBaseElementType(Pointee);
1701 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001702 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1703
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001704 if (!UseGlobal &&
Anders Carlsson78f74552009-11-15 18:45:20 +00001705 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001706 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001707
John McCall6ec278d2011-01-27 09:37:56 +00001708 // If we're allocating an array of records, check whether the
1709 // usual operator delete[] has a size_t parameter.
1710 if (ArrayForm) {
1711 // If the user specifically asked to use the global allocator,
1712 // we'll need to do the lookup into the class.
1713 if (UseGlobal)
1714 UsualArrayDeleteWantsSize =
1715 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
1716
1717 // Otherwise, the usual operator delete[] should be the
1718 // function we just found.
1719 else if (isa<CXXMethodDecl>(OperatorDelete))
1720 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
1721 }
1722
Anders Carlsson78f74552009-11-15 18:45:20 +00001723 if (!RD->hasTrivialDestructor())
Douglas Gregor9b623632010-10-12 23:32:35 +00001724 if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001725 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001726 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor9b623632010-10-12 23:32:35 +00001727 DiagnoseUseOfDecl(Dtor, StartLoc);
1728 }
Anders Carlssond67c4c32009-08-16 20:29:29 +00001729 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001730
Anders Carlssond67c4c32009-08-16 20:29:29 +00001731 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001732 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001733 DeclareGlobalNewDelete();
1734 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001735 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +00001736 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001737 OperatorDelete))
1738 return ExprError();
1739 }
Mike Stump1eb44332009-09-09 15:08:12 +00001740
John McCall9c82afc2010-04-20 02:18:25 +00001741 MarkDeclarationReferenced(StartLoc, OperatorDelete);
John McCall6ec278d2011-01-27 09:37:56 +00001742
Douglas Gregord880f522011-02-01 15:50:11 +00001743 // Check access and ambiguity of operator delete and destructor.
1744 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
1745 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1746 if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
1747 CheckDestructorAccess(Ex->getExprLoc(), Dtor,
1748 PDiag(diag::err_access_dtor) << PointeeElem);
1749 }
1750 }
1751
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001752 }
1753
Sebastian Redlf53597f2009-03-15 17:47:39 +00001754 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
John McCall6ec278d2011-01-27 09:37:56 +00001755 ArrayFormAsWritten,
1756 UsualArrayDeleteWantsSize,
1757 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001758}
1759
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001760/// \brief Check the use of the given variable as a C++ condition in an if,
1761/// while, do-while, or switch statement.
John McCall60d7b3a2010-08-24 06:29:42 +00001762ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCallf89e55a2010-11-18 06:31:45 +00001763 SourceLocation StmtLoc,
1764 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001765 QualType T = ConditionVar->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001766
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001767 // C++ [stmt.select]p2:
1768 // The declarator shall not specify a function or an array.
1769 if (T->isFunctionType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001770 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001771 diag::err_invalid_use_of_function_type)
1772 << ConditionVar->getSourceRange());
1773 else if (T->isArrayType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001774 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001775 diag::err_invalid_use_of_array_type)
1776 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001777
Douglas Gregor40d96a62011-02-28 21:54:11 +00001778 Expr *Condition = DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1779 ConditionVar,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001780 ConditionVar->getLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00001781 ConditionVar->getType().getNonReferenceType(),
John McCall09431682010-11-18 19:01:18 +00001782 VK_LValue);
Douglas Gregorff331c12010-07-25 18:17:45 +00001783 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc))
Douglas Gregor586596f2010-05-06 17:25:47 +00001784 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001785
Douglas Gregor586596f2010-05-06 17:25:47 +00001786 return Owned(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001787}
1788
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001789/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1790bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1791 // C++ 6.4p4:
1792 // The value of a condition that is an initialized declaration in a statement
1793 // other than a switch statement is the value of the declared variable
1794 // implicitly converted to type bool. If that conversion is ill-formed, the
1795 // program is ill-formed.
1796 // The value of a condition that is an expression is the value of the
1797 // expression, implicitly converted to bool.
1798 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001799 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001800}
Douglas Gregor77a52232008-09-12 00:47:35 +00001801
1802/// Helper function to determine whether this is the (deprecated) C++
1803/// conversion from a string literal to a pointer to non-const char or
1804/// non-const wchar_t (for narrow and wide string literals,
1805/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001806bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001807Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1808 // Look inside the implicit cast, if it exists.
1809 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1810 From = Cast->getSubExpr();
1811
1812 // A string literal (2.13.4) that is not a wide string literal can
1813 // be converted to an rvalue of type "pointer to char"; a wide
1814 // string literal can be converted to an rvalue of type "pointer
1815 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00001816 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00001817 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001818 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001819 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001820 // This conversion is considered only when there is an
1821 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001822 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001823 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1824 (!StrLit->isWide() &&
1825 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1826 ToPointeeType->getKind() == BuiltinType::Char_S))))
1827 return true;
1828 }
1829
1830 return false;
1831}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001832
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001833static ExprResult BuildCXXCastArgument(Sema &S,
John McCall2de56d12010-08-25 11:45:40 +00001834 SourceLocation CastLoc,
1835 QualType Ty,
1836 CastKind Kind,
1837 CXXMethodDecl *Method,
Douglas Gregor83eecbe2011-01-20 01:32:05 +00001838 NamedDecl *FoundDecl,
John McCall2de56d12010-08-25 11:45:40 +00001839 Expr *From) {
Douglas Gregorba70ab62010-04-16 22:17:36 +00001840 switch (Kind) {
1841 default: assert(0 && "Unhandled cast kind!");
John McCall2de56d12010-08-25 11:45:40 +00001842 case CK_ConstructorConversion: {
John McCallca0408f2010-08-23 06:44:23 +00001843 ASTOwningVector<Expr*> ConstructorArgs(S);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001844
Douglas Gregorba70ab62010-04-16 22:17:36 +00001845 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
John McCallf312b1e2010-08-26 23:41:50 +00001846 MultiExprArg(&From, 1),
Douglas Gregorba70ab62010-04-16 22:17:36 +00001847 CastLoc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00001848 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001849
1850 ExprResult Result =
1851 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
John McCall7a1fad32010-08-24 07:32:53 +00001852 move_arg(ConstructorArgs),
Chandler Carruth428edaf2010-10-25 08:47:36 +00001853 /*ZeroInit*/ false, CXXConstructExpr::CK_Complete,
1854 SourceRange());
Douglas Gregorba70ab62010-04-16 22:17:36 +00001855 if (Result.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00001856 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001857
Douglas Gregorba70ab62010-04-16 22:17:36 +00001858 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1859 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001860
John McCall2de56d12010-08-25 11:45:40 +00001861 case CK_UserDefinedConversion: {
Douglas Gregorba70ab62010-04-16 22:17:36 +00001862 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001863
Douglas Gregorba70ab62010-04-16 22:17:36 +00001864 // Create an implicit call expr that calls it.
Douglas Gregor83eecbe2011-01-20 01:32:05 +00001865 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00001866 if (Result.isInvalid())
1867 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001868
Douglas Gregorf2ae5262011-01-20 00:18:04 +00001869 return S.MaybeBindToTemporary(Result.get());
Douglas Gregorba70ab62010-04-16 22:17:36 +00001870 }
1871 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001872}
Douglas Gregorba70ab62010-04-16 22:17:36 +00001873
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001874/// PerformImplicitConversion - Perform an implicit conversion of the
1875/// expression From to the type ToType using the pre-computed implicit
1876/// conversion sequence ICS. Returns true if there was an error, false
1877/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001878/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001879/// used in the error message.
1880bool
1881Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1882 const ImplicitConversionSequence &ICS,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001883 AssignmentAction Action, bool CStyle) {
John McCall1d318332010-01-12 00:44:57 +00001884 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001885 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001886 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001887 CStyle))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001888 return true;
1889 break;
1890
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001891 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001892
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001893 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCalldaa8e4e2010-11-15 09:13:47 +00001894 CastKind CastKind;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001895 QualType BeforeToType;
1896 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCall2de56d12010-08-25 11:45:40 +00001897 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001898
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001899 // If the user-defined conversion is specified by a conversion function,
1900 // the initial standard conversion sequence converts the source type to
1901 // the implicit object parameter of the conversion function.
1902 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCall9ec94452010-12-04 09:57:16 +00001903 } else {
1904 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCall2de56d12010-08-25 11:45:40 +00001905 CastKind = CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001906 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001907 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001908 // If the user-defined conversion is specified by a constructor, the
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001909 // initial standard conversion sequence converts the source type to the
1910 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001911 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1912 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001913 }
Douglas Gregora3998bd2010-12-02 21:47:04 +00001914 // Watch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001915 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001916 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001917 ICS.UserDefined.Before, AA_Converting,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001918 CStyle))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001919 return true;
1920 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001921
1922 ExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00001923 = BuildCXXCastArgument(*this,
1924 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00001925 ToType.getNonReferenceType(),
Douglas Gregor83eecbe2011-01-20 01:32:05 +00001926 CastKind, cast<CXXMethodDecl>(FD),
1927 ICS.UserDefined.FoundConversionFunction,
John McCall9ae2f072010-08-23 23:25:46 +00001928 From);
Anders Carlsson0aebc812009-09-09 21:33:21 +00001929
1930 if (CastArg.isInvalid())
1931 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001932
1933 From = CastArg.takeAs<Expr>();
1934
Eli Friedmand8889622009-11-27 04:41:50 +00001935 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001936 AA_Converting, CStyle);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001937 }
John McCall1d318332010-01-12 00:44:57 +00001938
1939 case ImplicitConversionSequence::AmbiguousConversion:
John McCall120d63c2010-08-24 20:38:10 +00001940 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall1d318332010-01-12 00:44:57 +00001941 PDiag(diag::err_typecheck_ambiguous_condition)
1942 << From->getSourceRange());
1943 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001944
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001945 case ImplicitConversionSequence::EllipsisConversion:
1946 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001947 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001948
1949 case ImplicitConversionSequence::BadConversion:
1950 return true;
1951 }
1952
1953 // Everything went well.
1954 return false;
1955}
1956
1957/// PerformImplicitConversion - Perform an implicit conversion of the
1958/// expression From to the type ToType by following the standard
1959/// conversion sequence SCS. Returns true if there was an error, false
1960/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001961/// expression. Flavor is the context in which we're performing this
1962/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001963bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001964Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001965 const StandardConversionSequence& SCS,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001966 AssignmentAction Action, bool CStyle) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001967 // Overall FIXME: we are recomputing too many types here and doing far too
1968 // much extra work. What this means is that we need to keep track of more
1969 // information that is computed when we try the implicit conversion initially,
1970 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001971 QualType FromType = From->getType();
1972
Douglas Gregor225c41e2008-11-03 19:09:14 +00001973 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001974 // FIXME: When can ToType be a reference type?
1975 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001976 if (SCS.Second == ICK_Derived_To_Base) {
John McCallca0408f2010-08-23 06:44:23 +00001977 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001978 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCallca0408f2010-08-23 06:44:23 +00001979 MultiExprArg(*this, &From, 1),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001980 /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001981 ConstructorArgs))
1982 return true;
John McCall60d7b3a2010-08-24 06:29:42 +00001983 ExprResult FromResult =
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001984 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1985 ToType, SCS.CopyConstructor,
John McCall7a1fad32010-08-24 07:32:53 +00001986 move_arg(ConstructorArgs),
1987 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00001988 CXXConstructExpr::CK_Complete,
1989 SourceRange());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001990 if (FromResult.isInvalid())
1991 return true;
1992 From = FromResult.takeAs<Expr>();
1993 return false;
1994 }
John McCall60d7b3a2010-08-24 06:29:42 +00001995 ExprResult FromResult =
Mike Stump1eb44332009-09-09 15:08:12 +00001996 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1997 ToType, SCS.CopyConstructor,
John McCall7a1fad32010-08-24 07:32:53 +00001998 MultiExprArg(*this, &From, 1),
1999 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00002000 CXXConstructExpr::CK_Complete,
2001 SourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +00002002
Anders Carlssonda3f4e22009-08-25 05:12:04 +00002003 if (FromResult.isInvalid())
2004 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002005
Anders Carlssonda3f4e22009-08-25 05:12:04 +00002006 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00002007 return false;
2008 }
2009
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002010 // Resolve overloaded function references.
2011 if (Context.hasSameType(FromType, Context.OverloadTy)) {
2012 DeclAccessPair Found;
2013 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2014 true, Found);
2015 if (!Fn)
2016 return true;
2017
2018 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
2019 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002020
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002021 From = FixOverloadedFunctionReference(From, Found, Fn);
2022 FromType = From->getType();
2023 }
2024
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002025 // Perform the first implicit conversion.
2026 switch (SCS.First) {
2027 case ICK_Identity:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002028 // Nothing to do.
2029 break;
2030
John McCallf6a16482010-12-04 03:47:34 +00002031 case ICK_Lvalue_To_Rvalue:
2032 // Should this get its own ICK?
2033 if (From->getObjectKind() == OK_ObjCProperty) {
2034 ConvertPropertyForRValue(From);
John McCall241d5582010-12-07 22:54:16 +00002035 if (!From->isGLValue()) break;
John McCallf6a16482010-12-04 03:47:34 +00002036 }
2037
Chandler Carruth35001ca2011-02-17 21:10:52 +00002038 // Check for trivial buffer overflows.
2039 if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(From))
2040 CheckArrayAccess(AE);
2041
John McCallf6a16482010-12-04 03:47:34 +00002042 FromType = FromType.getUnqualifiedType();
2043 From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
2044 From, 0, VK_RValue);
2045 break;
2046
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002047 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002048 FromType = Context.getArrayDecayedType(FromType);
John McCall2de56d12010-08-25 11:45:40 +00002049 ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002050 break;
2051
2052 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002053 FromType = Context.getPointerType(FromType);
John McCall2de56d12010-08-25 11:45:40 +00002054 ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002055 break;
2056
2057 default:
2058 assert(false && "Improper first standard conversion");
2059 break;
2060 }
2061
2062 // Perform the second implicit conversion
2063 switch (SCS.Second) {
2064 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002065 // If both sides are functions (or pointers/references to them), there could
2066 // be incompatible exception declarations.
2067 if (CheckExceptionSpecCompatibility(From, ToType))
2068 return true;
2069 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002070 break;
2071
Douglas Gregor43c79c22009-12-09 00:47:37 +00002072 case ICK_NoReturn_Adjustment:
2073 // If both sides are functions (or pointers/references to them), there could
2074 // be incompatible exception declarations.
2075 if (CheckExceptionSpecCompatibility(From, ToType))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002076 return true;
2077
John McCalle6a365d2010-12-19 02:44:49 +00002078 ImpCastExprToType(From, ToType, CK_NoOp);
Douglas Gregor43c79c22009-12-09 00:47:37 +00002079 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002080
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002081 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002082 case ICK_Integral_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00002083 ImpCastExprToType(From, ToType, CK_IntegralCast);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002084 break;
2085
2086 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002087 case ICK_Floating_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00002088 ImpCastExprToType(From, ToType, CK_FloatingCast);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002089 break;
2090
2091 case ICK_Complex_Promotion:
John McCalldaa8e4e2010-11-15 09:13:47 +00002092 case ICK_Complex_Conversion: {
2093 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2094 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2095 CastKind CK;
2096 if (FromEl->isRealFloatingType()) {
2097 if (ToEl->isRealFloatingType())
2098 CK = CK_FloatingComplexCast;
2099 else
2100 CK = CK_FloatingComplexToIntegralComplex;
2101 } else if (ToEl->isRealFloatingType()) {
2102 CK = CK_IntegralComplexToFloatingComplex;
2103 } else {
2104 CK = CK_IntegralComplexCast;
2105 }
2106 ImpCastExprToType(From, ToType, CK);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002107 break;
John McCalldaa8e4e2010-11-15 09:13:47 +00002108 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00002109
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002110 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00002111 if (ToType->isRealFloatingType())
John McCall2de56d12010-08-25 11:45:40 +00002112 ImpCastExprToType(From, ToType, CK_IntegralToFloating);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002113 else
John McCall2de56d12010-08-25 11:45:40 +00002114 ImpCastExprToType(From, ToType, CK_FloatingToIntegral);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002115 break;
2116
Douglas Gregorf9201e02009-02-11 23:02:49 +00002117 case ICK_Compatible_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00002118 ImpCastExprToType(From, ToType, CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002119 break;
2120
Anders Carlsson61faec12009-09-12 04:46:44 +00002121 case ICK_Pointer_Conversion: {
Douglas Gregora3998bd2010-12-02 21:47:04 +00002122 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor45920e82008-12-19 17:40:08 +00002123 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00002124 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00002125 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00002126 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00002127 << From->getSourceRange();
2128 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002129
John McCalldaa8e4e2010-11-15 09:13:47 +00002130 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002131 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002132 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002133 return true;
John McCall5baba9d2010-08-25 10:28:54 +00002134 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002135 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00002136 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002137
Anders Carlsson61faec12009-09-12 04:46:44 +00002138 case ICK_Pointer_Member: {
John McCalldaa8e4e2010-11-15 09:13:47 +00002139 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002140 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002141 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
Anders Carlsson61faec12009-09-12 04:46:44 +00002142 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002143 if (CheckExceptionSpecCompatibility(From, ToType))
2144 return true;
John McCall5baba9d2010-08-25 10:28:54 +00002145 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
Anders Carlsson61faec12009-09-12 04:46:44 +00002146 break;
2147 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00002148 case ICK_Boolean_Conversion: {
John McCalldaa8e4e2010-11-15 09:13:47 +00002149 CastKind Kind = CK_Invalid;
2150 switch (FromType->getScalarTypeKind()) {
2151 case Type::STK_Pointer: Kind = CK_PointerToBoolean; break;
2152 case Type::STK_MemberPointer: Kind = CK_MemberPointerToBoolean; break;
2153 case Type::STK_Bool: llvm_unreachable("bool -> bool conversion?");
2154 case Type::STK_Integral: Kind = CK_IntegralToBoolean; break;
2155 case Type::STK_Floating: Kind = CK_FloatingToBoolean; break;
2156 case Type::STK_IntegralComplex: Kind = CK_IntegralComplexToBoolean; break;
2157 case Type::STK_FloatingComplex: Kind = CK_FloatingComplexToBoolean; break;
2158 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002159
Anders Carlssonbc0e0782009-11-23 20:04:44 +00002160 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002161 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00002162 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002163
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002164 case ICK_Derived_To_Base: {
John McCallf871d0c2010-08-07 06:22:56 +00002165 CXXCastPath BasePath;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002166 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002167 ToType.getNonReferenceType(),
2168 From->getLocStart(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002169 From->getSourceRange(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002170 &BasePath,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002171 CStyle))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002172 return true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002173
Sebastian Redl906082e2010-07-20 04:20:21 +00002174 ImpCastExprToType(From, ToType.getNonReferenceType(),
John McCall2de56d12010-08-25 11:45:40 +00002175 CK_DerivedToBase, CastCategory(From),
John McCallf871d0c2010-08-07 06:22:56 +00002176 &BasePath);
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002177 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002178 }
2179
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002180 case ICK_Vector_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00002181 ImpCastExprToType(From, ToType, CK_BitCast);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002182 break;
2183
2184 case ICK_Vector_Splat:
John McCall2de56d12010-08-25 11:45:40 +00002185 ImpCastExprToType(From, ToType, CK_VectorSplat);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002186 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002187
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002188 case ICK_Complex_Real:
John McCalldaa8e4e2010-11-15 09:13:47 +00002189 // Case 1. x -> _Complex y
2190 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2191 QualType ElType = ToComplex->getElementType();
2192 bool isFloatingComplex = ElType->isRealFloatingType();
2193
2194 // x -> y
2195 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2196 // do nothing
2197 } else if (From->getType()->isRealFloatingType()) {
2198 ImpCastExprToType(From, ElType,
2199 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral);
2200 } else {
2201 assert(From->getType()->isIntegerType());
2202 ImpCastExprToType(From, ElType,
2203 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast);
2204 }
2205 // y -> _Complex y
2206 ImpCastExprToType(From, ToType,
2207 isFloatingComplex ? CK_FloatingRealToComplex
2208 : CK_IntegralRealToComplex);
2209
2210 // Case 2. _Complex x -> y
2211 } else {
2212 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2213 assert(FromComplex);
2214
2215 QualType ElType = FromComplex->getElementType();
2216 bool isFloatingComplex = ElType->isRealFloatingType();
2217
2218 // _Complex x -> x
2219 ImpCastExprToType(From, ElType,
2220 isFloatingComplex ? CK_FloatingComplexToReal
2221 : CK_IntegralComplexToReal);
2222
2223 // x -> y
2224 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2225 // do nothing
2226 } else if (ToType->isRealFloatingType()) {
2227 ImpCastExprToType(From, ToType,
2228 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating);
2229 } else {
2230 assert(ToType->isIntegerType());
2231 ImpCastExprToType(From, ToType,
2232 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast);
2233 }
2234 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002235 break;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002236
2237 case ICK_Block_Pointer_Conversion: {
2238 ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast, VK_RValue);
2239 break;
2240 }
2241
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002242 case ICK_Lvalue_To_Rvalue:
2243 case ICK_Array_To_Pointer:
2244 case ICK_Function_To_Pointer:
2245 case ICK_Qualification:
2246 case ICK_Num_Conversion_Kinds:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002247 assert(false && "Improper second standard conversion");
2248 break;
2249 }
2250
2251 switch (SCS.Third) {
2252 case ICK_Identity:
2253 // Nothing to do.
2254 break;
2255
Sebastian Redl906082e2010-07-20 04:20:21 +00002256 case ICK_Qualification: {
2257 // The qualification keeps the category of the inner expression, unless the
2258 // target type isn't a reference.
John McCall5baba9d2010-08-25 10:28:54 +00002259 ExprValueKind VK = ToType->isReferenceType() ?
2260 CastCategory(From) : VK_RValue;
Douglas Gregor63982352010-07-13 18:40:04 +00002261 ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
John McCall2de56d12010-08-25 11:45:40 +00002262 CK_NoOp, VK);
Douglas Gregora9bff302010-02-28 18:30:25 +00002263
2264 if (SCS.DeprecatedStringLiteralToCharPtr)
2265 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2266 << ToType.getNonReferenceType();
2267
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002268 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002269 }
2270
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002271 default:
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002272 assert(false && "Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002273 break;
2274 }
2275
2276 return false;
2277}
2278
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002279ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002280 SourceLocation KWLoc,
2281 ParsedType Ty,
2282 SourceLocation RParen) {
2283 TypeSourceInfo *TSInfo;
2284 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002285
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002286 if (!TSInfo)
2287 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002288 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002289}
2290
Sebastian Redlf8aca862010-09-14 23:40:14 +00002291static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT, QualType T,
2292 SourceLocation KeyLoc) {
Douglas Gregora0506182011-01-27 20:35:44 +00002293 // FIXME: For many of these traits, we need a complete type before we can
2294 // check these properties.
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002295 assert(!T->isDependentType() &&
2296 "Cannot evaluate traits for dependent types.");
2297 ASTContext &C = Self.Context;
2298 switch(UTT) {
2299 default: assert(false && "Unknown type trait or not implemented");
2300 case UTT_IsPOD: return T->isPODType();
2301 case UTT_IsLiteral: return T->isLiteralType();
2302 case UTT_IsClass: // Fallthrough
2303 case UTT_IsUnion:
2304 if (const RecordType *Record = T->getAs<RecordType>()) {
2305 bool Union = Record->getDecl()->isUnion();
2306 return UTT == UTT_IsUnion ? Union : !Union;
2307 }
2308 return false;
2309 case UTT_IsEnum: return T->isEnumeralType();
2310 case UTT_IsPolymorphic:
2311 if (const RecordType *Record = T->getAs<RecordType>()) {
2312 // Type traits are only parsed in C++, so we've got CXXRecords.
2313 return cast<CXXRecordDecl>(Record->getDecl())->isPolymorphic();
2314 }
2315 return false;
2316 case UTT_IsAbstract:
2317 if (const RecordType *RT = T->getAs<RecordType>())
2318 return cast<CXXRecordDecl>(RT->getDecl())->isAbstract();
2319 return false;
2320 case UTT_IsEmpty:
2321 if (const RecordType *Record = T->getAs<RecordType>()) {
2322 return !Record->getDecl()->isUnion()
2323 && cast<CXXRecordDecl>(Record->getDecl())->isEmpty();
2324 }
2325 return false;
2326 case UTT_HasTrivialConstructor:
2327 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2328 // If __is_pod (type) is true then the trait is true, else if type is
2329 // a cv class or union type (or array thereof) with a trivial default
2330 // constructor ([class.ctor]) then the trait is true, else it is false.
2331 if (T->isPODType())
2332 return true;
2333 if (const RecordType *RT =
2334 C.getBaseElementType(T)->getAs<RecordType>())
2335 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialConstructor();
2336 return false;
2337 case UTT_HasTrivialCopy:
2338 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2339 // If __is_pod (type) is true or type is a reference type then
2340 // the trait is true, else if type is a cv class or union type
2341 // with a trivial copy constructor ([class.copy]) then the trait
2342 // is true, else it is false.
2343 if (T->isPODType() || T->isReferenceType())
2344 return true;
2345 if (const RecordType *RT = T->getAs<RecordType>())
2346 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2347 return false;
2348 case UTT_HasTrivialAssign:
2349 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2350 // If type is const qualified or is a reference type then the
2351 // trait is false. Otherwise if __is_pod (type) is true then the
2352 // trait is true, else if type is a cv class or union type with
2353 // a trivial copy assignment ([class.copy]) then the trait is
2354 // true, else it is false.
2355 // Note: the const and reference restrictions are interesting,
2356 // given that const and reference members don't prevent a class
2357 // from having a trivial copy assignment operator (but do cause
2358 // errors if the copy assignment operator is actually used, q.v.
2359 // [class.copy]p12).
2360
2361 if (C.getBaseElementType(T).isConstQualified())
2362 return false;
2363 if (T->isPODType())
2364 return true;
2365 if (const RecordType *RT = T->getAs<RecordType>())
2366 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2367 return false;
2368 case UTT_HasTrivialDestructor:
2369 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2370 // If __is_pod (type) is true or type is a reference type
2371 // then the trait is true, else if type is a cv class or union
2372 // type (or array thereof) with a trivial destructor
2373 // ([class.dtor]) then the trait is true, else it is
2374 // false.
2375 if (T->isPODType() || T->isReferenceType())
2376 return true;
2377 if (const RecordType *RT =
2378 C.getBaseElementType(T)->getAs<RecordType>())
2379 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2380 return false;
2381 // TODO: Propagate nothrowness for implicitly declared special members.
2382 case UTT_HasNothrowAssign:
2383 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2384 // If type is const qualified or is a reference type then the
2385 // trait is false. Otherwise if __has_trivial_assign (type)
2386 // is true then the trait is true, else if type is a cv class
2387 // or union type with copy assignment operators that are known
2388 // not to throw an exception then the trait is true, else it is
2389 // false.
2390 if (C.getBaseElementType(T).isConstQualified())
2391 return false;
2392 if (T->isReferenceType())
2393 return false;
2394 if (T->isPODType())
2395 return true;
2396 if (const RecordType *RT = T->getAs<RecordType>()) {
2397 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2398 if (RD->hasTrivialCopyAssignment())
2399 return true;
2400
2401 bool FoundAssign = false;
2402 bool AllNoThrow = true;
2403 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redlf8aca862010-09-14 23:40:14 +00002404 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2405 Sema::LookupOrdinaryName);
2406 if (Self.LookupQualifiedName(Res, RD)) {
2407 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2408 Op != OpEnd; ++Op) {
2409 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2410 if (Operator->isCopyAssignmentOperator()) {
2411 FoundAssign = true;
2412 const FunctionProtoType *CPT
2413 = Operator->getType()->getAs<FunctionProtoType>();
2414 if (!CPT->hasEmptyExceptionSpec()) {
2415 AllNoThrow = false;
2416 break;
2417 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002418 }
2419 }
2420 }
2421
2422 return FoundAssign && AllNoThrow;
2423 }
2424 return false;
2425 case UTT_HasNothrowCopy:
2426 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2427 // If __has_trivial_copy (type) is true then the trait is true, else
2428 // if type is a cv class or union type with copy constructors that are
2429 // known not to throw an exception then the trait is true, else it is
2430 // false.
2431 if (T->isPODType() || T->isReferenceType())
2432 return true;
2433 if (const RecordType *RT = T->getAs<RecordType>()) {
2434 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2435 if (RD->hasTrivialCopyConstructor())
2436 return true;
2437
2438 bool FoundConstructor = false;
2439 bool AllNoThrow = true;
2440 unsigned FoundTQs;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002441 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl5f4e8992010-09-13 21:10:20 +00002442 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002443 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002444 // A template constructor is never a copy constructor.
2445 // FIXME: However, it may actually be selected at the actual overload
2446 // resolution point.
2447 if (isa<FunctionTemplateDecl>(*Con))
2448 continue;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002449 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2450 if (Constructor->isCopyConstructor(FoundTQs)) {
2451 FoundConstructor = true;
2452 const FunctionProtoType *CPT
2453 = Constructor->getType()->getAs<FunctionProtoType>();
Sebastian Redl751025d2010-09-13 22:02:47 +00002454 // TODO: check whether evaluating default arguments can throw.
2455 // For now, we'll be conservative and assume that they can throw.
2456 if (!CPT->hasEmptyExceptionSpec() || CPT->getNumArgs() > 1) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002457 AllNoThrow = false;
2458 break;
2459 }
2460 }
2461 }
2462
2463 return FoundConstructor && AllNoThrow;
2464 }
2465 return false;
2466 case UTT_HasNothrowConstructor:
2467 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2468 // If __has_trivial_constructor (type) is true then the trait is
2469 // true, else if type is a cv class or union type (or array
2470 // thereof) with a default constructor that is known not to
2471 // throw an exception then the trait is true, else it is false.
2472 if (T->isPODType())
2473 return true;
2474 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
2475 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2476 if (RD->hasTrivialConstructor())
2477 return true;
2478
Sebastian Redl751025d2010-09-13 22:02:47 +00002479 DeclContext::lookup_const_iterator Con, ConEnd;
2480 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2481 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002482 // FIXME: In C++0x, a constructor template can be a default constructor.
2483 if (isa<FunctionTemplateDecl>(*Con))
2484 continue;
Sebastian Redl751025d2010-09-13 22:02:47 +00002485 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2486 if (Constructor->isDefaultConstructor()) {
2487 const FunctionProtoType *CPT
2488 = Constructor->getType()->getAs<FunctionProtoType>();
2489 // TODO: check whether evaluating default arguments can throw.
2490 // For now, we'll be conservative and assume that they can throw.
2491 return CPT->hasEmptyExceptionSpec() && CPT->getNumArgs() == 0;
2492 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002493 }
2494 }
2495 return false;
2496 case UTT_HasVirtualDestructor:
2497 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2498 // If type is a class type with a virtual destructor ([class.dtor])
2499 // then the trait is true, else it is false.
2500 if (const RecordType *Record = T->getAs<RecordType>()) {
2501 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redlf8aca862010-09-14 23:40:14 +00002502 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002503 return Destructor->isVirtual();
2504 }
2505 return false;
2506 }
2507}
2508
2509ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002510 SourceLocation KWLoc,
2511 TypeSourceInfo *TSInfo,
2512 SourceLocation RParen) {
2513 QualType T = TSInfo->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002514
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002515 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
2516 // all traits except __is_class, __is_enum and __is_union require a the type
Sebastian Redl607a1782010-09-08 00:48:43 +00002517 // to be complete, an array of unknown bound, or void.
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002518 if (UTT != UTT_IsClass && UTT != UTT_IsEnum && UTT != UTT_IsUnion) {
Sebastian Redl607a1782010-09-08 00:48:43 +00002519 QualType E = T;
2520 if (T->isIncompleteArrayType())
2521 E = Context.getAsArrayType(T)->getElementType();
2522 if (!T->isVoidType() &&
2523 RequireCompleteType(KWLoc, E,
Anders Carlssond497ba72009-08-26 22:59:12 +00002524 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002525 return ExprError();
2526 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00002527
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002528 bool Value = false;
2529 if (!T->isDependentType())
Sebastian Redlf8aca862010-09-14 23:40:14 +00002530 Value = EvaluateUnaryTypeTrait(*this, UTT, T, KWLoc);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002531
2532 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002533 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00002534}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002535
Francois Pichet6ad6f282010-12-07 00:08:36 +00002536ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
2537 SourceLocation KWLoc,
2538 ParsedType LhsTy,
2539 ParsedType RhsTy,
2540 SourceLocation RParen) {
2541 TypeSourceInfo *LhsTSInfo;
2542 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
2543 if (!LhsTSInfo)
2544 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
2545
2546 TypeSourceInfo *RhsTSInfo;
2547 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
2548 if (!RhsTSInfo)
2549 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
2550
2551 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
2552}
2553
2554static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
2555 QualType LhsT, QualType RhsT,
2556 SourceLocation KeyLoc) {
2557 assert((!LhsT->isDependentType() || RhsT->isDependentType()) &&
2558 "Cannot evaluate traits for dependent types.");
2559
2560 switch(BTT) {
John McCalld89d30f2011-01-28 22:02:36 +00002561 case BTT_IsBaseOf: {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002562 // C++0x [meta.rel]p2
John McCalld89d30f2011-01-28 22:02:36 +00002563 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet6ad6f282010-12-07 00:08:36 +00002564 // Base and Derived are not unions and name the same class type without
2565 // regard to cv-qualifiers.
Francois Pichet6ad6f282010-12-07 00:08:36 +00002566
John McCalld89d30f2011-01-28 22:02:36 +00002567 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
2568 if (!lhsRecord) return false;
2569
2570 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
2571 if (!rhsRecord) return false;
2572
2573 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
2574 == (lhsRecord == rhsRecord));
2575
2576 if (lhsRecord == rhsRecord)
2577 return !lhsRecord->getDecl()->isUnion();
2578
2579 // C++0x [meta.rel]p2:
2580 // If Base and Derived are class types and are different types
2581 // (ignoring possible cv-qualifiers) then Derived shall be a
2582 // complete type.
2583 if (Self.RequireCompleteType(KeyLoc, RhsT,
2584 diag::err_incomplete_type_used_in_type_trait_expr))
2585 return false;
2586
2587 return cast<CXXRecordDecl>(rhsRecord->getDecl())
2588 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
2589 }
2590
Francois Pichetf1872372010-12-08 22:35:30 +00002591 case BTT_TypeCompatible:
2592 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
2593 RhsT.getUnqualifiedType());
Douglas Gregor9f361132011-01-27 20:28:01 +00002594
2595 case BTT_IsConvertibleTo: {
2596 // C++0x [meta.rel]p4:
2597 // Given the following function prototype:
2598 //
2599 // template <class T>
2600 // typename add_rvalue_reference<T>::type create();
2601 //
2602 // the predicate condition for a template specialization
2603 // is_convertible<From, To> shall be satisfied if and only if
2604 // the return expression in the following code would be
2605 // well-formed, including any implicit conversions to the return
2606 // type of the function:
2607 //
2608 // To test() {
2609 // return create<From>();
2610 // }
2611 //
2612 // Access checking is performed as if in a context unrelated to To and
2613 // From. Only the validity of the immediate context of the expression
2614 // of the return-statement (including conversions to the return type)
2615 // is considered.
2616 //
2617 // We model the initialization as a copy-initialization of a temporary
2618 // of the appropriate type, which for this expression is identical to the
2619 // return statement (since NRVO doesn't apply).
2620 if (LhsT->isObjectType() || LhsT->isFunctionType())
2621 LhsT = Self.Context.getRValueReferenceType(LhsT);
2622
2623 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorb608b982011-01-28 02:26:04 +00002624 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor9f361132011-01-27 20:28:01 +00002625 Expr::getValueKindForType(LhsT));
2626 Expr *FromPtr = &From;
2627 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
2628 SourceLocation()));
2629
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00002630 // Perform the initialization within a SFINAE trap at translation unit
2631 // scope.
2632 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
2633 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Douglas Gregor9f361132011-01-27 20:28:01 +00002634 InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
2635 if (Init.getKind() == InitializationSequence::FailedSequence)
2636 return false;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00002637
Douglas Gregor9f361132011-01-27 20:28:01 +00002638 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
2639 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
2640 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00002641 }
2642 llvm_unreachable("Unknown type trait or not implemented");
2643}
2644
2645ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
2646 SourceLocation KWLoc,
2647 TypeSourceInfo *LhsTSInfo,
2648 TypeSourceInfo *RhsTSInfo,
2649 SourceLocation RParen) {
2650 QualType LhsT = LhsTSInfo->getType();
2651 QualType RhsT = RhsTSInfo->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002652
John McCalld89d30f2011-01-28 22:02:36 +00002653 if (BTT == BTT_TypeCompatible) {
Francois Pichetf1872372010-12-08 22:35:30 +00002654 if (getLangOptions().CPlusPlus) {
2655 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
2656 << SourceRange(KWLoc, RParen);
2657 return ExprError();
2658 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00002659 }
2660
2661 bool Value = false;
2662 if (!LhsT->isDependentType() && !RhsT->isDependentType())
2663 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
2664
Francois Pichetf1872372010-12-08 22:35:30 +00002665 // Select trait result type.
2666 QualType ResultType;
2667 switch (BTT) {
Francois Pichetf1872372010-12-08 22:35:30 +00002668 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
2669 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
Douglas Gregor9f361132011-01-27 20:28:01 +00002670 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00002671 }
2672
Francois Pichet6ad6f282010-12-07 00:08:36 +00002673 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
2674 RhsTSInfo, Value, RParen,
Francois Pichetf1872372010-12-08 22:35:30 +00002675 ResultType));
Francois Pichet6ad6f282010-12-07 00:08:36 +00002676}
2677
John McCallf89e55a2010-11-18 06:31:45 +00002678QualType Sema::CheckPointerToMemberOperands(Expr *&lex, Expr *&rex,
2679 ExprValueKind &VK,
2680 SourceLocation Loc,
2681 bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002682 const char *OpSpelling = isIndirect ? "->*" : ".*";
2683 // C++ 5.5p2
2684 // The binary operator .* [p3: ->*] binds its second operand, which shall
2685 // be of type "pointer to member of T" (where T is a completely-defined
2686 // class type) [...]
2687 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002688 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00002689 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002690 Diag(Loc, diag::err_bad_memptr_rhs)
2691 << OpSpelling << RType << rex->getSourceRange();
2692 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00002693 }
Douglas Gregore7450f52009-03-24 19:52:54 +00002694
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002695 QualType Class(MemPtr->getClass(), 0);
2696
Douglas Gregor7d520ba2010-10-13 20:41:14 +00002697 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
2698 // member pointer points must be completely-defined. However, there is no
2699 // reason for this semantic distinction, and the rule is not enforced by
2700 // other compilers. Therefore, we do not check this property, as it is
2701 // likely to be considered a defect.
Sebastian Redl59fc2692010-04-10 10:14:54 +00002702
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002703 // C++ 5.5p2
2704 // [...] to its first operand, which shall be of class T or of a class of
2705 // which T is an unambiguous and accessible base class. [p3: a pointer to
2706 // such a class]
2707 QualType LType = lex->getType();
2708 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002709 if (const PointerType *Ptr = LType->getAs<PointerType>())
John McCallf89e55a2010-11-18 06:31:45 +00002710 LType = Ptr->getPointeeType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002711 else {
2712 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00002713 << OpSpelling << 1 << LType
Douglas Gregor849b2432010-03-31 17:46:05 +00002714 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002715 return QualType();
2716 }
2717 }
2718
Douglas Gregora4923eb2009-11-16 21:35:15 +00002719 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00002720 // If we want to check the hierarchy, we need a complete type.
2721 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
2722 << OpSpelling << (int)isIndirect)) {
2723 return QualType();
2724 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002725 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002726 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00002727 // FIXME: Would it be useful to print full ambiguity paths, or is that
2728 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002729 if (!IsDerivedFrom(LType, Class, Paths) ||
2730 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
2731 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00002732 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002733 return QualType();
2734 }
Eli Friedman3005efe2010-01-16 00:00:48 +00002735 // Cast LHS to type of use.
2736 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
John McCall5baba9d2010-08-25 10:28:54 +00002737 ExprValueKind VK =
2738 isIndirect ? VK_RValue : CastCategory(lex);
Sebastian Redl906082e2010-07-20 04:20:21 +00002739
John McCallf871d0c2010-08-07 06:22:56 +00002740 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002741 BuildBasePathArray(Paths, BasePath);
John McCall5baba9d2010-08-25 10:28:54 +00002742 ImpCastExprToType(lex, UseType, CK_DerivedToBase, VK, &BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002743 }
2744
Douglas Gregored8abf12010-07-08 06:14:04 +00002745 if (isa<CXXScalarValueInitExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00002746 // Diagnose use of pointer-to-member type which when used as
2747 // the functional cast in a pointer-to-member expression.
2748 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
2749 return QualType();
2750 }
John McCallf89e55a2010-11-18 06:31:45 +00002751
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002752 // C++ 5.5p2
2753 // The result is an object or a function of the type specified by the
2754 // second operand.
2755 // The cv qualifiers are the union of those in the pointer and the left side,
2756 // in accordance with 5.5p5 and 5.2.5.
2757 // FIXME: This returns a dereferenced member function pointer as a normal
2758 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00002759 // calling them. There's also a GCC extension to get a function pointer to the
2760 // thing, which is another complication, because this type - unlike the type
2761 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002762 // argument.
2763 // We probably need a "MemberFunctionClosureType" or something like that.
2764 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00002765 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
John McCallf89e55a2010-11-18 06:31:45 +00002766
Douglas Gregor6b4df912011-01-26 16:40:18 +00002767 // C++0x [expr.mptr.oper]p6:
2768 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002769 // ill-formed if the second operand is a pointer to member function with
2770 // ref-qualifier &. In a ->* expression or in a .* expression whose object
2771 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor6b4df912011-01-26 16:40:18 +00002772 // is a pointer to member function with ref-qualifier &&.
2773 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
2774 switch (Proto->getRefQualifier()) {
2775 case RQ_None:
2776 // Do nothing
2777 break;
2778
2779 case RQ_LValue:
2780 if (!isIndirect && !lex->Classify(Context).isLValue())
2781 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
2782 << RType << 1 << lex->getSourceRange();
2783 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002784
Douglas Gregor6b4df912011-01-26 16:40:18 +00002785 case RQ_RValue:
2786 if (isIndirect || !lex->Classify(Context).isRValue())
2787 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
2788 << RType << 0 << lex->getSourceRange();
2789 break;
2790 }
2791 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002792
John McCallf89e55a2010-11-18 06:31:45 +00002793 // C++ [expr.mptr.oper]p6:
2794 // The result of a .* expression whose second operand is a pointer
2795 // to a data member is of the same value category as its
2796 // first operand. The result of a .* expression whose second
2797 // operand is a pointer to a member function is a prvalue. The
2798 // result of an ->* expression is an lvalue if its second operand
2799 // is a pointer to data member and a prvalue otherwise.
2800 if (Result->isFunctionType())
2801 VK = VK_RValue;
2802 else if (isIndirect)
2803 VK = VK_LValue;
2804 else
2805 VK = lex->getValueKind();
2806
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002807 return Result;
2808}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002809
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002810/// \brief Try to convert a type to another according to C++0x 5.16p3.
2811///
2812/// This is part of the parameter validation for the ? operator. If either
2813/// value operand is a class type, the two operands are attempted to be
2814/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002815/// It returns true if the program is ill-formed and has already been diagnosed
2816/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002817static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
2818 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00002819 bool &HaveConversion,
2820 QualType &ToType) {
2821 HaveConversion = false;
2822 ToType = To->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002823
2824 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00002825 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002826 // C++0x 5.16p3
2827 // The process for determining whether an operand expression E1 of type T1
2828 // can be converted to match an operand expression E2 of type T2 is defined
2829 // as follows:
2830 // -- If E2 is an lvalue:
John McCall7eb0a9e2010-11-24 05:12:34 +00002831 bool ToIsLvalue = To->isLValue();
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002832 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002833 // E1 can be converted to match E2 if E1 can be implicitly converted to
2834 // type "lvalue reference to T2", subject to the constraint that in the
2835 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002836 QualType T = Self.Context.getLValueReferenceType(ToType);
2837 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002838
Douglas Gregorb70cf442010-03-26 20:14:36 +00002839 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2840 if (InitSeq.isDirectReferenceBinding()) {
2841 ToType = T;
2842 HaveConversion = true;
2843 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002844 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002845
Douglas Gregorb70cf442010-03-26 20:14:36 +00002846 if (InitSeq.isAmbiguous())
2847 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002848 }
John McCallb1bdc622010-02-25 01:37:24 +00002849
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002850 // -- If E2 is an rvalue, or if the conversion above cannot be done:
2851 // -- if E1 and E2 have class type, and the underlying class types are
2852 // the same or one is a base class of the other:
2853 QualType FTy = From->getType();
2854 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002855 const RecordType *FRec = FTy->getAs<RecordType>();
2856 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002857 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00002858 Self.IsDerivedFrom(FTy, TTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002859 if (FRec && TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00002860 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002861 // E1 can be converted to match E2 if the class of T2 is the
2862 // same type as, or a base class of, the class of T1, and
2863 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00002864 if (FRec == TRec || FDerivedFromT) {
2865 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002866 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2867 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2868 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2869 HaveConversion = true;
2870 return false;
2871 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002872
Douglas Gregorb70cf442010-03-26 20:14:36 +00002873 if (InitSeq.isAmbiguous())
2874 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002875 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002876 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002877
Douglas Gregorb70cf442010-03-26 20:14:36 +00002878 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002879 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002880
Douglas Gregorb70cf442010-03-26 20:14:36 +00002881 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2882 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002883 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002884 // an rvalue).
2885 //
2886 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2887 // to the array-to-pointer or function-to-pointer conversions.
2888 if (!TTy->getAs<TagType>())
2889 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002890
Douglas Gregorb70cf442010-03-26 20:14:36 +00002891 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2892 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002893 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002894 ToType = TTy;
2895 if (InitSeq.isAmbiguous())
2896 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2897
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002898 return false;
2899}
2900
2901/// \brief Try to find a common type for two according to C++0x 5.16p5.
2902///
2903/// This is part of the parameter validation for the ? operator. If either
2904/// value operand is a class type, overload resolution is used to find a
2905/// conversion to a common type.
2906static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
Chandler Carruth82214a82011-02-18 23:54:50 +00002907 SourceLocation QuestionLoc) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002908 Expr *Args[2] = { LHS, RHS };
Chandler Carruth82214a82011-02-18 23:54:50 +00002909 OverloadCandidateSet CandidateSet(QuestionLoc);
2910 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
2911 CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002912
2913 OverloadCandidateSet::iterator Best;
Chandler Carruth82214a82011-02-18 23:54:50 +00002914 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002915 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002916 // We found a match. Perform the conversions on the arguments and move on.
2917 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00002918 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002919 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00002920 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002921 break;
Chandler Carruth25ca4212011-02-25 19:41:05 +00002922 if (Best->Function)
2923 Self.MarkDeclarationReferenced(QuestionLoc, Best->Function);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002924 return false;
2925
Douglas Gregor20093b42009-12-09 23:02:17 +00002926 case OR_No_Viable_Function:
Chandler Carruth82214a82011-02-18 23:54:50 +00002927
2928 // Emit a better diagnostic if one of the expressions is a null pointer
2929 // constant and the other is a pointer type. In this case, the user most
2930 // likely forgot to take the address of the other expression.
2931 if (Self.DiagnoseConditionalForNull(LHS, RHS, QuestionLoc))
2932 return true;
2933
2934 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002935 << LHS->getType() << RHS->getType()
2936 << LHS->getSourceRange() << RHS->getSourceRange();
2937 return true;
2938
Douglas Gregor20093b42009-12-09 23:02:17 +00002939 case OR_Ambiguous:
Chandler Carruth82214a82011-02-18 23:54:50 +00002940 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002941 << LHS->getType() << RHS->getType()
2942 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00002943 // FIXME: Print the possible common types by printing the return types of
2944 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002945 break;
2946
Douglas Gregor20093b42009-12-09 23:02:17 +00002947 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002948 assert(false && "Conditional operator has only built-in overloads");
2949 break;
2950 }
2951 return true;
2952}
2953
Sebastian Redl76458502009-04-17 16:30:52 +00002954/// \brief Perform an "extended" implicit conversion as returned by
2955/// TryClassUnification.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002956static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2957 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2958 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2959 SourceLocation());
2960 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
John McCallf312b1e2010-08-26 23:41:50 +00002961 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&E, 1));
Douglas Gregorb70cf442010-03-26 20:14:36 +00002962 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00002963 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002964
Douglas Gregorb70cf442010-03-26 20:14:36 +00002965 E = Result.takeAs<Expr>();
Sebastian Redl76458502009-04-17 16:30:52 +00002966 return false;
2967}
2968
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002969/// \brief Check the operands of ?: under C++ semantics.
2970///
2971/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2972/// extension. In this case, LHS == Cond. (But they're not aliases.)
2973QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
John McCall56ca35d2011-02-17 10:25:35 +00002974 ExprValueKind &VK, ExprObjectKind &OK,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002975 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002976 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2977 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002978
2979 // C++0x 5.16p1
2980 // The first expression is contextually converted to bool.
2981 if (!Cond->isTypeDependent()) {
2982 if (CheckCXXBooleanCondition(Cond))
2983 return QualType();
2984 }
2985
John McCallf89e55a2010-11-18 06:31:45 +00002986 // Assume r-value.
2987 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00002988 OK = OK_Ordinary;
John McCallf89e55a2010-11-18 06:31:45 +00002989
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002990 // Either of the arguments dependent?
2991 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2992 return Context.DependentTy;
2993
2994 // C++0x 5.16p2
2995 // If either the second or the third operand has type (cv) void, ...
2996 QualType LTy = LHS->getType();
2997 QualType RTy = RHS->getType();
2998 bool LVoid = LTy->isVoidType();
2999 bool RVoid = RTy->isVoidType();
3000 if (LVoid || RVoid) {
3001 // ... then the [l2r] conversions are performed on the second and third
3002 // operands ...
Douglas Gregora873dfc2010-02-03 00:27:59 +00003003 DefaultFunctionArrayLvalueConversion(LHS);
3004 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003005 LTy = LHS->getType();
3006 RTy = RHS->getType();
3007
3008 // ... and one of the following shall hold:
3009 // -- The second or the third operand (but not both) is a throw-
3010 // expression; the result is of the type of the other and is an rvalue.
3011 bool LThrow = isa<CXXThrowExpr>(LHS);
3012 bool RThrow = isa<CXXThrowExpr>(RHS);
3013 if (LThrow && !RThrow)
3014 return RTy;
3015 if (RThrow && !LThrow)
3016 return LTy;
3017
3018 // -- Both the second and third operands have type void; the result is of
3019 // type void and is an rvalue.
3020 if (LVoid && RVoid)
3021 return Context.VoidTy;
3022
3023 // Neither holds, error.
3024 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
3025 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
3026 << LHS->getSourceRange() << RHS->getSourceRange();
3027 return QualType();
3028 }
3029
3030 // Neither is void.
3031
3032 // C++0x 5.16p3
3033 // Otherwise, if the second and third operand have different types, and
3034 // either has (cv) class type, and attempt is made to convert each of those
3035 // operands to the other.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003036 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003037 (LTy->isRecordType() || RTy->isRecordType())) {
3038 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
3039 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003040 QualType L2RType, R2LType;
3041 bool HaveL2R, HaveR2L;
3042 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003043 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00003044 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003045 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003046
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003047 // If both can be converted, [...] the program is ill-formed.
3048 if (HaveL2R && HaveR2L) {
3049 Diag(QuestionLoc, diag::err_conditional_ambiguous)
3050 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
3051 return QualType();
3052 }
3053
3054 // If exactly one conversion is possible, that conversion is applied to
3055 // the chosen operand and the converted operands are used in place of the
3056 // original operands for the remainder of this section.
3057 if (HaveL2R) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003058 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003059 return QualType();
3060 LTy = LHS->getType();
3061 } else if (HaveR2L) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003062 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003063 return QualType();
3064 RTy = RHS->getType();
3065 }
3066 }
3067
3068 // C++0x 5.16p4
John McCallf89e55a2010-11-18 06:31:45 +00003069 // If the second and third operands are glvalues of the same value
3070 // category and have the same type, the result is of that type and
3071 // value category and it is a bit-field if the second or the third
3072 // operand is a bit-field, or if both are bit-fields.
John McCall09431682010-11-18 19:01:18 +00003073 // We only extend this to bitfields, not to the crazy other kinds of
3074 // l-values.
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003075 bool Same = Context.hasSameType(LTy, RTy);
John McCallf89e55a2010-11-18 06:31:45 +00003076 if (Same &&
John McCall56ca35d2011-02-17 10:25:35 +00003077 LHS->isGLValue() &&
John McCallf89e55a2010-11-18 06:31:45 +00003078 LHS->getValueKind() == RHS->getValueKind() &&
John McCall56ca35d2011-02-17 10:25:35 +00003079 LHS->isOrdinaryOrBitFieldObject() &&
3080 RHS->isOrdinaryOrBitFieldObject()) {
John McCallf89e55a2010-11-18 06:31:45 +00003081 VK = LHS->getValueKind();
John McCall09431682010-11-18 19:01:18 +00003082 if (LHS->getObjectKind() == OK_BitField ||
3083 RHS->getObjectKind() == OK_BitField)
3084 OK = OK_BitField;
John McCallf89e55a2010-11-18 06:31:45 +00003085 return LTy;
Fariborz Jahanian3911a1a2010-09-25 01:08:05 +00003086 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003087
3088 // C++0x 5.16p5
3089 // Otherwise, the result is an rvalue. If the second and third operands
3090 // do not have the same type, and either has (cv) class type, ...
3091 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
3092 // ... overload resolution is used to determine the conversions (if any)
3093 // to be applied to the operands. If the overload resolution fails, the
3094 // program is ill-formed.
3095 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
3096 return QualType();
3097 }
3098
3099 // C++0x 5.16p6
3100 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
3101 // conversions are performed on the second and third operands.
Douglas Gregora873dfc2010-02-03 00:27:59 +00003102 DefaultFunctionArrayLvalueConversion(LHS);
3103 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003104 LTy = LHS->getType();
3105 RTy = RHS->getType();
3106
3107 // After those conversions, one of the following shall hold:
3108 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00003109 // is of that type. If the operands have class type, the result
3110 // is a prvalue temporary of the result type, which is
3111 // copy-initialized from either the second operand or the third
3112 // operand depending on the value of the first operand.
3113 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
3114 if (LTy->isRecordType()) {
3115 // The operands have class type. Make a temporary copy.
3116 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003117 ExprResult LHSCopy = PerformCopyInitialization(Entity,
3118 SourceLocation(),
John McCallf6a16482010-12-04 03:47:34 +00003119 Owned(LHS));
Douglas Gregorb65a4582010-05-19 23:40:50 +00003120 if (LHSCopy.isInvalid())
3121 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003122
3123 ExprResult RHSCopy = PerformCopyInitialization(Entity,
3124 SourceLocation(),
John McCallf6a16482010-12-04 03:47:34 +00003125 Owned(RHS));
Douglas Gregorb65a4582010-05-19 23:40:50 +00003126 if (RHSCopy.isInvalid())
3127 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003128
Douglas Gregorb65a4582010-05-19 23:40:50 +00003129 LHS = LHSCopy.takeAs<Expr>();
3130 RHS = RHSCopy.takeAs<Expr>();
3131 }
3132
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003133 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00003134 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003135
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003136 // Extension: conditional operator involving vector types.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003137 if (LTy->isVectorType() || RTy->isVectorType())
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003138 return CheckVectorOperands(QuestionLoc, LHS, RHS);
3139
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003140 // -- The second and third operands have arithmetic or enumeration type;
3141 // the usual arithmetic conversions are performed to bring them to a
3142 // common type, and the result is of that type.
3143 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
3144 UsualArithmeticConversions(LHS, RHS);
3145 return LHS->getType();
3146 }
3147
3148 // -- The second and third operands have pointer type, or one has pointer
3149 // type and the other is a null pointer constant; pointer conversions
3150 // and qualification conversions are performed to bring them to their
3151 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00003152 // -- The second and third operands have pointer to member type, or one has
3153 // pointer to member type and the other is a null pointer constant;
3154 // pointer to member conversions and qualification conversions are
3155 // performed to bring them to a common type, whose cv-qualification
3156 // shall match the cv-qualification of either the second or the third
3157 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003158 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003159 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003160 isSFINAEContext()? 0 : &NonStandardCompositeType);
3161 if (!Composite.isNull()) {
3162 if (NonStandardCompositeType)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003163 Diag(QuestionLoc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003164 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
3165 << LTy << RTy << Composite
3166 << LHS->getSourceRange() << RHS->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003167
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003168 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003169 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003170
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003171 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00003172 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
3173 if (!Composite.isNull())
3174 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003175
Chandler Carruth7ef93242011-02-19 00:13:59 +00003176 // Check if we are using a null with a non-pointer type.
3177 if (DiagnoseConditionalForNull(LHS, RHS, QuestionLoc))
3178 return QualType();
3179
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003180 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3181 << LHS->getType() << RHS->getType()
3182 << LHS->getSourceRange() << RHS->getSourceRange();
3183 return QualType();
3184}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003185
3186/// \brief Find a merged pointer type and convert the two expressions to it.
3187///
Douglas Gregor20b3e992009-08-24 17:42:35 +00003188/// This finds the composite pointer type (or member pointer type) for @p E1
3189/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
3190/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003191/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003192///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003193/// \param Loc The location of the operator requiring these two expressions to
3194/// be converted to the composite pointer type.
3195///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003196/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
3197/// a non-standard (but still sane) composite type to which both expressions
3198/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
3199/// will be set true.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003200QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003201 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003202 bool *NonStandardCompositeType) {
3203 if (NonStandardCompositeType)
3204 *NonStandardCompositeType = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003205
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003206 assert(getLangOptions().CPlusPlus && "This function assumes C++");
3207 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003208
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00003209 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
3210 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00003211 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003212
3213 // C++0x 5.9p2
3214 // Pointer conversions and qualification conversions are performed on
3215 // pointer operands to bring them to their composite pointer type. If
3216 // one operand is a null pointer constant, the composite pointer type is
3217 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00003218 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003219 if (T2->isMemberPointerType())
John McCall2de56d12010-08-25 11:45:40 +00003220 ImpCastExprToType(E1, T2, CK_NullToMemberPointer);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003221 else
John McCall404cd162010-11-13 01:35:44 +00003222 ImpCastExprToType(E1, T2, CK_NullToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003223 return T2;
3224 }
Douglas Gregorce940492009-09-25 04:25:58 +00003225 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003226 if (T1->isMemberPointerType())
John McCall2de56d12010-08-25 11:45:40 +00003227 ImpCastExprToType(E2, T1, CK_NullToMemberPointer);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003228 else
John McCall404cd162010-11-13 01:35:44 +00003229 ImpCastExprToType(E2, T1, CK_NullToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003230 return T1;
3231 }
Mike Stump1eb44332009-09-09 15:08:12 +00003232
Douglas Gregor20b3e992009-08-24 17:42:35 +00003233 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003234 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
3235 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003236 return QualType();
3237
3238 // Otherwise, of one of the operands has type "pointer to cv1 void," then
3239 // the other has type "pointer to cv2 T" and the composite pointer type is
3240 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
3241 // Otherwise, the composite pointer type is a pointer type similar to the
3242 // type of one of the operands, with a cv-qualification signature that is
3243 // the union of the cv-qualification signatures of the operand types.
3244 // In practice, the first part here is redundant; it's subsumed by the second.
3245 // What we do here is, we build the two possible composite types, and try the
3246 // conversions in both directions. If only one works, or if the two composite
3247 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00003248 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00003249 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
3250 QualifierVector QualifierUnion;
3251 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
3252 ContainingClassVector;
3253 ContainingClassVector MemberOfClass;
3254 QualType Composite1 = Context.getCanonicalType(T1),
3255 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003256 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00003257 do {
3258 const PointerType *Ptr1, *Ptr2;
3259 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3260 (Ptr2 = Composite2->getAs<PointerType>())) {
3261 Composite1 = Ptr1->getPointeeType();
3262 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003263
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003264 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003265 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003266 if (NonStandardCompositeType &&
3267 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3268 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003269
Douglas Gregor20b3e992009-08-24 17:42:35 +00003270 QualifierUnion.push_back(
3271 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3272 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3273 continue;
3274 }
Mike Stump1eb44332009-09-09 15:08:12 +00003275
Douglas Gregor20b3e992009-08-24 17:42:35 +00003276 const MemberPointerType *MemPtr1, *MemPtr2;
3277 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3278 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3279 Composite1 = MemPtr1->getPointeeType();
3280 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003281
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003282 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003283 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003284 if (NonStandardCompositeType &&
3285 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3286 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003287
Douglas Gregor20b3e992009-08-24 17:42:35 +00003288 QualifierUnion.push_back(
3289 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3290 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
3291 MemPtr2->getClass()));
3292 continue;
3293 }
Mike Stump1eb44332009-09-09 15:08:12 +00003294
Douglas Gregor20b3e992009-08-24 17:42:35 +00003295 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00003296
Douglas Gregor20b3e992009-08-24 17:42:35 +00003297 // Cannot unwrap any more types.
3298 break;
3299 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00003300
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003301 if (NeedConstBefore && NonStandardCompositeType) {
3302 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003303 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003304 // requirements of C++ [conv.qual]p4 bullet 3.
3305 for (unsigned I = 0; I != NeedConstBefore; ++I) {
3306 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
3307 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
3308 *NonStandardCompositeType = true;
3309 }
3310 }
3311 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003312
Douglas Gregor20b3e992009-08-24 17:42:35 +00003313 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003314 ContainingClassVector::reverse_iterator MOC
3315 = MemberOfClass.rbegin();
3316 for (QualifierVector::reverse_iterator
3317 I = QualifierUnion.rbegin(),
3318 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00003319 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00003320 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00003321 if (MOC->first && MOC->second) {
3322 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00003323 Composite1 = Context.getMemberPointerType(
3324 Context.getQualifiedType(Composite1, Quals),
3325 MOC->first);
3326 Composite2 = Context.getMemberPointerType(
3327 Context.getQualifiedType(Composite2, Quals),
3328 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00003329 } else {
3330 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00003331 Composite1
3332 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
3333 Composite2
3334 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00003335 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003336 }
3337
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003338 // Try to convert to the first composite pointer type.
3339 InitializedEntity Entity1
3340 = InitializedEntity::InitializeTemporary(Composite1);
3341 InitializationKind Kind
3342 = InitializationKind::CreateCopy(Loc, SourceLocation());
3343 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
3344 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00003345
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003346 if (E1ToC1 && E2ToC1) {
3347 // Conversion to Composite1 is viable.
3348 if (!Context.hasSameType(Composite1, Composite2)) {
3349 // Composite2 is a different type from Composite1. Check whether
3350 // Composite2 is also viable.
3351 InitializedEntity Entity2
3352 = InitializedEntity::InitializeTemporary(Composite2);
3353 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3354 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3355 if (E1ToC2 && E2ToC2) {
3356 // Both Composite1 and Composite2 are viable and are different;
3357 // this is an ambiguity.
3358 return QualType();
3359 }
3360 }
3361
3362 // Convert E1 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00003363 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00003364 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003365 if (E1Result.isInvalid())
3366 return QualType();
3367 E1 = E1Result.takeAs<Expr>();
3368
3369 // Convert E2 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00003370 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00003371 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003372 if (E2Result.isInvalid())
3373 return QualType();
3374 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003375
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003376 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003377 }
3378
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003379 // Check whether Composite2 is viable.
3380 InitializedEntity Entity2
3381 = InitializedEntity::InitializeTemporary(Composite2);
3382 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3383 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3384 if (!E1ToC2 || !E2ToC2)
3385 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003386
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003387 // Convert E1 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00003388 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00003389 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003390 if (E1Result.isInvalid())
3391 return QualType();
3392 E1 = E1Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003393
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003394 // Convert E2 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00003395 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00003396 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003397 if (E2Result.isInvalid())
3398 return QualType();
3399 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003400
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003401 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003402}
Anders Carlsson165a0a02009-05-17 18:41:29 +00003403
John McCall60d7b3a2010-08-24 06:29:42 +00003404ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor19cc1c72010-11-01 21:10:29 +00003405 if (!E)
3406 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003407
Anders Carlsson089c2602009-08-15 23:41:35 +00003408 if (!Context.getLangOptions().CPlusPlus)
3409 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003410
Douglas Gregor51326552009-12-24 18:51:59 +00003411 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
3412
Ted Kremenek6217b802009-07-29 21:53:49 +00003413 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00003414 if (!RT)
3415 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003416
Douglas Gregor5e6fcd42011-02-08 02:14:35 +00003417 // If the result is a glvalue, we shouldn't bind it.
3418 if (E->Classify(Context).isGLValue())
3419 return Owned(E);
John McCall86ff3082010-02-04 22:26:26 +00003420
3421 // That should be enough to guarantee that this type is complete.
3422 // If it has a trivial destructor, we can avoid the extra copy.
Jeffrey Yasskinb7ee2e52011-01-27 19:17:54 +00003423 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall507384f2010-08-12 02:40:37 +00003424 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall86ff3082010-02-04 22:26:26 +00003425 return Owned(E);
3426
Douglas Gregordb89f282010-07-01 22:47:18 +00003427 CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD));
Anders Carlsson860306e2009-05-30 21:21:49 +00003428 ExprTemporaries.push_back(Temp);
Douglas Gregordb89f282010-07-01 22:47:18 +00003429 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003430 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00003431 CheckDestructorAccess(E->getExprLoc(), Destructor,
3432 PDiag(diag::err_access_dtor_temp)
3433 << E->getType());
3434 }
Anders Carlssondef11992009-05-30 20:36:53 +00003435 // FIXME: Add the temporary to the temporaries vector.
3436 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
3437}
3438
John McCall4765fa02010-12-06 08:20:24 +00003439Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003440 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00003441
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00003442 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3443 assert(ExprTemporaries.size() >= FirstTemporary);
3444 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003445 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003446
John McCall4765fa02010-12-06 08:20:24 +00003447 Expr *E = ExprWithCleanups::Create(Context, SubExpr,
3448 &ExprTemporaries[FirstTemporary],
3449 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00003450 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
3451 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00003452
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003453 return E;
3454}
3455
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003456ExprResult
John McCall4765fa02010-12-06 08:20:24 +00003457Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregor90f93822009-12-22 22:17:25 +00003458 if (SubExpr.isInvalid())
3459 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003460
John McCall4765fa02010-12-06 08:20:24 +00003461 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregor90f93822009-12-22 22:17:25 +00003462}
3463
John McCall4765fa02010-12-06 08:20:24 +00003464Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003465 assert(SubStmt && "sub statement can't be null!");
3466
3467 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3468 assert(ExprTemporaries.size() >= FirstTemporary);
3469 if (ExprTemporaries.size() == FirstTemporary)
3470 return SubStmt;
3471
3472 // FIXME: In order to attach the temporaries, wrap the statement into
3473 // a StmtExpr; currently this is only used for asm statements.
3474 // This is hacky, either create a new CXXStmtWithTemporaries statement or
3475 // a new AsmStmtWithTemporaries.
3476 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
3477 SourceLocation(),
3478 SourceLocation());
3479 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
3480 SourceLocation());
John McCall4765fa02010-12-06 08:20:24 +00003481 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003482}
3483
John McCall60d7b3a2010-08-24 06:29:42 +00003484ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003485Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallb3d87482010-08-24 05:47:05 +00003486 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00003487 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003488 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003489 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003490 if (Result.isInvalid()) return ExprError();
3491 Base = Result.get();
Mike Stump1eb44332009-09-09 15:08:12 +00003492
John McCall9ae2f072010-08-23 23:25:46 +00003493 QualType BaseType = Base->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00003494 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003495 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00003496 // If we have a pointer to a dependent type and are using the -> operator,
3497 // the object type is the type that the pointer points to. We might still
3498 // have enough information about that type to do something useful.
3499 if (OpKind == tok::arrow)
3500 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3501 BaseType = Ptr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003502
John McCallb3d87482010-08-24 05:47:05 +00003503 ObjectType = ParsedType::make(BaseType);
Douglas Gregord4dca082010-02-24 18:44:31 +00003504 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00003505 return Owned(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003506 }
Mike Stump1eb44332009-09-09 15:08:12 +00003507
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003508 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00003509 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003510 // returned, with the original second operand.
3511 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00003512 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00003513 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00003514 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00003515 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003516
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003517 while (BaseType->isRecordType()) {
John McCall9ae2f072010-08-23 23:25:46 +00003518 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
3519 if (Result.isInvalid())
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003520 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00003521 Base = Result.get();
3522 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonde699e52009-10-13 22:55:59 +00003523 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCall9ae2f072010-08-23 23:25:46 +00003524 BaseType = Base->getType();
John McCallc4e83212009-09-30 01:01:30 +00003525 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00003526 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00003527 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00003528 for (unsigned i = 0; i < Locations.size(); i++)
3529 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00003530 return ExprError();
3531 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003532 }
Mike Stump1eb44332009-09-09 15:08:12 +00003533
Douglas Gregor31658df2009-11-20 19:58:21 +00003534 if (BaseType->isPointerType())
3535 BaseType = BaseType->getPointeeType();
3536 }
Mike Stump1eb44332009-09-09 15:08:12 +00003537
3538 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003539 // vector types or Objective-C interfaces. Just return early and let
3540 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00003541 if (!BaseType->isRecordType()) {
3542 // C++ [basic.lookup.classref]p2:
3543 // [...] If the type of the object expression is of pointer to scalar
3544 // type, the unqualified-id is looked up in the context of the complete
3545 // postfix-expression.
Douglas Gregord4dca082010-02-24 18:44:31 +00003546 //
3547 // This also indicates that we should be parsing a
3548 // pseudo-destructor-name.
John McCallb3d87482010-08-24 05:47:05 +00003549 ObjectType = ParsedType();
Douglas Gregord4dca082010-02-24 18:44:31 +00003550 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00003551 return Owned(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00003552 }
Mike Stump1eb44332009-09-09 15:08:12 +00003553
Douglas Gregor03c57052009-11-17 05:17:33 +00003554 // The object type must be complete (or dependent).
3555 if (!BaseType->isDependentType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003556 RequireCompleteType(OpLoc, BaseType,
Douglas Gregor03c57052009-11-17 05:17:33 +00003557 PDiag(diag::err_incomplete_member_access)))
3558 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003559
Douglas Gregorc68afe22009-09-03 21:38:09 +00003560 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00003561 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00003562 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00003563 // type C (or of pointer to a class type C), the unqualified-id is looked
3564 // up in the scope of class C. [...]
John McCallb3d87482010-08-24 05:47:05 +00003565 ObjectType = ParsedType::make(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00003566 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003567}
3568
John McCall60d7b3a2010-08-24 06:29:42 +00003569ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003570 Expr *MemExpr) {
Douglas Gregor77549082010-02-24 21:29:12 +00003571 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCall9ae2f072010-08-23 23:25:46 +00003572 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
3573 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregor849b2432010-03-31 17:46:05 +00003574 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003575
Douglas Gregor77549082010-02-24 21:29:12 +00003576 return ActOnCallExpr(/*Scope*/ 0,
John McCall9ae2f072010-08-23 23:25:46 +00003577 MemExpr,
Douglas Gregor77549082010-02-24 21:29:12 +00003578 /*LPLoc*/ ExpectedLParenLoc,
John McCallf312b1e2010-08-26 23:41:50 +00003579 MultiExprArg(),
Douglas Gregor77549082010-02-24 21:29:12 +00003580 /*RPLoc*/ ExpectedLParenLoc);
3581}
Douglas Gregord4dca082010-02-24 18:44:31 +00003582
John McCall60d7b3a2010-08-24 06:29:42 +00003583ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00003584 SourceLocation OpLoc,
3585 tok::TokenKind OpKind,
3586 const CXXScopeSpec &SS,
3587 TypeSourceInfo *ScopeTypeInfo,
3588 SourceLocation CCLoc,
3589 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003590 PseudoDestructorTypeStorage Destructed,
John McCall2d9f5fa2011-02-25 05:21:17 +00003591 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003592 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003593
Douglas Gregorb57fb492010-02-24 22:38:50 +00003594 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003595 // The left-hand side of the dot operator shall be of scalar type. The
Douglas Gregorb57fb492010-02-24 22:38:50 +00003596 // left-hand side of the arrow operator shall be of pointer to scalar type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003597 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00003598 QualType ObjectType = Base->getType();
Douglas Gregorb57fb492010-02-24 22:38:50 +00003599 if (OpKind == tok::arrow) {
3600 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3601 ObjectType = Ptr->getPointeeType();
John McCall9ae2f072010-08-23 23:25:46 +00003602 } else if (!Base->isTypeDependent()) {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003603 // The user wrote "p->" when she probably meant "p."; fix it.
3604 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3605 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00003606 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb57fb492010-02-24 22:38:50 +00003607 if (isSFINAEContext())
3608 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003609
Douglas Gregorb57fb492010-02-24 22:38:50 +00003610 OpKind = tok::period;
3611 }
3612 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003613
Douglas Gregorb57fb492010-02-24 22:38:50 +00003614 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
3615 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
John McCall9ae2f072010-08-23 23:25:46 +00003616 << ObjectType << Base->getSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00003617 return ExprError();
3618 }
3619
3620 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003621 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb57fb492010-02-24 22:38:50 +00003622 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003623 if (DestructedTypeInfo) {
3624 QualType DestructedType = DestructedTypeInfo->getType();
3625 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003626 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003627 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
3628 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
3629 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00003630 << ObjectType << DestructedType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003631 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003632
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003633 // Recover by setting the destructed type to the object type.
3634 DestructedType = ObjectType;
3635 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
3636 DestructedTypeStart);
3637 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3638 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00003639 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003640
Douglas Gregorb57fb492010-02-24 22:38:50 +00003641 // C++ [expr.pseudo]p2:
3642 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
3643 // form
3644 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003645 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb57fb492010-02-24 22:38:50 +00003646 //
3647 // shall designate the same scalar type.
3648 if (ScopeTypeInfo) {
3649 QualType ScopeType = ScopeTypeInfo->getType();
3650 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00003651 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003652
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003653 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00003654 diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00003655 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003656 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003657
Douglas Gregorb57fb492010-02-24 22:38:50 +00003658 ScopeType = QualType();
3659 ScopeTypeInfo = 0;
3660 }
3661 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003662
John McCall9ae2f072010-08-23 23:25:46 +00003663 Expr *Result
3664 = new (Context) CXXPseudoDestructorExpr(Context, Base,
3665 OpKind == tok::arrow, OpLoc,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00003666 SS.getWithLocInContext(Context),
John McCall9ae2f072010-08-23 23:25:46 +00003667 ScopeTypeInfo,
3668 CCLoc,
3669 TildeLoc,
3670 Destructed);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003671
Douglas Gregorb57fb492010-02-24 22:38:50 +00003672 if (HasTrailingLParen)
John McCall9ae2f072010-08-23 23:25:46 +00003673 return Owned(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003674
John McCall9ae2f072010-08-23 23:25:46 +00003675 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor77549082010-02-24 21:29:12 +00003676}
3677
John McCall60d7b3a2010-08-24 06:29:42 +00003678ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00003679 SourceLocation OpLoc,
3680 tok::TokenKind OpKind,
3681 CXXScopeSpec &SS,
3682 UnqualifiedId &FirstTypeName,
3683 SourceLocation CCLoc,
3684 SourceLocation TildeLoc,
3685 UnqualifiedId &SecondTypeName,
3686 bool HasTrailingLParen) {
Douglas Gregor77549082010-02-24 21:29:12 +00003687 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3688 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3689 "Invalid first type name in pseudo-destructor");
3690 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3691 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3692 "Invalid second type name in pseudo-destructor");
3693
Douglas Gregor77549082010-02-24 21:29:12 +00003694 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003695 // The left-hand side of the dot operator shall be of scalar type. The
Douglas Gregor77549082010-02-24 21:29:12 +00003696 // left-hand side of the arrow operator shall be of pointer to scalar type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003697 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00003698 QualType ObjectType = Base->getType();
Douglas Gregor77549082010-02-24 21:29:12 +00003699 if (OpKind == tok::arrow) {
3700 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3701 ObjectType = Ptr->getPointeeType();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003702 } else if (!ObjectType->isDependentType()) {
Douglas Gregor77549082010-02-24 21:29:12 +00003703 // The user wrote "p->" when she probably meant "p."; fix it.
3704 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003705 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00003706 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor77549082010-02-24 21:29:12 +00003707 if (isSFINAEContext())
3708 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003709
Douglas Gregor77549082010-02-24 21:29:12 +00003710 OpKind = tok::period;
3711 }
3712 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003713
3714 // Compute the object type that we should use for name lookup purposes. Only
3715 // record types and dependent types matter.
John McCallb3d87482010-08-24 05:47:05 +00003716 ParsedType ObjectTypePtrForLookup;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003717 if (!SS.isSet()) {
John McCall2d9f5fa2011-02-25 05:21:17 +00003718 if (ObjectType->isRecordType())
3719 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallb3d87482010-08-24 05:47:05 +00003720 else if (ObjectType->isDependentType())
3721 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003722 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003723
3724 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb57fb492010-02-24 22:38:50 +00003725 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00003726 QualType DestructedType;
3727 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003728 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00003729 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003730 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00003731 SecondTypeName.StartLocation,
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +00003732 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003733 if (!T &&
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003734 ((SS.isSet() && !computeDeclContext(SS, false)) ||
3735 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003736 // The name of the type being destroyed is a dependent name, and we
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003737 // couldn't find anything useful in scope. Just store the identifier and
3738 // it's location, and we'll perform (qualified) name lookup again at
3739 // template instantiation time.
3740 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
3741 SecondTypeName.StartLocation);
3742 } else if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003743 Diag(SecondTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00003744 diag::err_pseudo_dtor_destructor_non_type)
3745 << SecondTypeName.Identifier << ObjectType;
3746 if (isSFINAEContext())
3747 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003748
Douglas Gregor77549082010-02-24 21:29:12 +00003749 // Recover by assuming we had the right type all along.
3750 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003751 } else
Douglas Gregor77549082010-02-24 21:29:12 +00003752 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003753 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003754 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00003755 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003756 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3757 TemplateId->getTemplateArgs(),
3758 TemplateId->NumArgs);
John McCall2b5289b2010-08-23 07:28:44 +00003759 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003760 TemplateId->TemplateNameLoc,
3761 TemplateId->LAngleLoc,
3762 TemplateArgsPtr,
3763 TemplateId->RAngleLoc);
3764 if (T.isInvalid() || !T.get()) {
3765 // Recover by assuming we had the right type all along.
3766 DestructedType = ObjectType;
3767 } else
3768 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003769 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003770
3771 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb57fb492010-02-24 22:38:50 +00003772 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003773 if (!DestructedType.isNull()) {
3774 if (!DestructedTypeInfo)
3775 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003776 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003777 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3778 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003779
Douglas Gregorb57fb492010-02-24 22:38:50 +00003780 // Convert the name of the scope type (the type prior to '::') into a type.
3781 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00003782 QualType ScopeType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003783 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor77549082010-02-24 21:29:12 +00003784 FirstTypeName.Identifier) {
3785 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003786 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00003787 FirstTypeName.StartLocation,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00003788 S, &SS, true, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00003789 if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003790 Diag(FirstTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00003791 diag::err_pseudo_dtor_destructor_non_type)
3792 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003793
Douglas Gregorb57fb492010-02-24 22:38:50 +00003794 if (isSFINAEContext())
3795 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003796
Douglas Gregorb57fb492010-02-24 22:38:50 +00003797 // Just drop this type. It's unnecessary anyway.
3798 ScopeType = QualType();
3799 } else
3800 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003801 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003802 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00003803 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003804 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3805 TemplateId->getTemplateArgs(),
3806 TemplateId->NumArgs);
John McCall2b5289b2010-08-23 07:28:44 +00003807 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003808 TemplateId->TemplateNameLoc,
3809 TemplateId->LAngleLoc,
3810 TemplateArgsPtr,
3811 TemplateId->RAngleLoc);
3812 if (T.isInvalid() || !T.get()) {
3813 // Recover by dropping this type.
3814 ScopeType = QualType();
3815 } else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003816 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003817 }
3818 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003819
Douglas Gregorb4a418f2010-02-24 23:02:30 +00003820 if (!ScopeType.isNull() && !ScopeTypeInfo)
3821 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
3822 FirstTypeName.StartLocation);
3823
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003824
John McCall9ae2f072010-08-23 23:25:46 +00003825 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00003826 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003827 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00003828}
3829
Douglas Gregorf2ae5262011-01-20 00:18:04 +00003830ExprResult Sema::BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
3831 CXXMethodDecl *Method) {
John McCall6bb80172010-03-30 21:47:33 +00003832 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
3833 FoundDecl, Method))
Douglas Gregorf2ae5262011-01-20 00:18:04 +00003834 return true;
Eli Friedman772fffa2009-12-09 04:53:56 +00003835
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003836 MemberExpr *ME =
Abramo Bagnara25777432010-08-11 22:01:17 +00003837 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
John McCallf89e55a2010-11-18 06:31:45 +00003838 SourceLocation(), Method->getType(),
3839 VK_RValue, OK_Ordinary);
3840 QualType ResultType = Method->getResultType();
3841 ExprValueKind VK = Expr::getValueKindForType(ResultType);
3842 ResultType = ResultType.getNonLValueExprType(Context);
3843
Douglas Gregor7edfb692009-11-23 12:27:39 +00003844 MarkDeclarationReferenced(Exp->getLocStart(), Method);
3845 CXXMemberCallExpr *CE =
John McCallf89e55a2010-11-18 06:31:45 +00003846 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
Douglas Gregor7edfb692009-11-23 12:27:39 +00003847 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003848 return CE;
3849}
3850
Sebastian Redl2e156222010-09-10 20:55:43 +00003851ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
3852 SourceLocation RParen) {
Sebastian Redl2e156222010-09-10 20:55:43 +00003853 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
3854 Operand->CanThrow(Context),
3855 KeyLoc, RParen));
3856}
3857
3858ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
3859 Expr *Operand, SourceLocation RParen) {
3860 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl02bc21a2010-09-10 20:55:37 +00003861}
3862
John McCallf6a16482010-12-04 03:47:34 +00003863/// Perform the conversions required for an expression used in a
3864/// context that ignores the result.
3865void Sema::IgnoredValueConversions(Expr *&E) {
John McCalla878cda2010-12-02 02:07:15 +00003866 // C99 6.3.2.1:
3867 // [Except in specific positions,] an lvalue that does not have
3868 // array type is converted to the value stored in the
3869 // designated object (and is no longer an lvalue).
John McCallf6a16482010-12-04 03:47:34 +00003870 if (E->isRValue()) return;
John McCalla878cda2010-12-02 02:07:15 +00003871
John McCallf6a16482010-12-04 03:47:34 +00003872 // We always want to do this on ObjC property references.
3873 if (E->getObjectKind() == OK_ObjCProperty) {
3874 ConvertPropertyForRValue(E);
3875 if (E->isRValue()) return;
3876 }
3877
3878 // Otherwise, this rule does not apply in C++, at least not for the moment.
3879 if (getLangOptions().CPlusPlus) return;
3880
3881 // GCC seems to also exclude expressions of incomplete enum type.
3882 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
3883 if (!T->getDecl()->isComplete()) {
3884 // FIXME: stupid workaround for a codegen bug!
3885 ImpCastExprToType(E, Context.VoidTy, CK_ToVoid);
3886 return;
3887 }
3888 }
3889
3890 DefaultFunctionArrayLvalueConversion(E);
John McCall85515d62010-12-04 12:29:11 +00003891 if (!E->getType()->isVoidType())
3892 RequireCompleteType(E->getExprLoc(), E->getType(),
3893 diag::err_incomplete_type);
John McCallf6a16482010-12-04 03:47:34 +00003894}
3895
3896ExprResult Sema::ActOnFinishFullExpr(Expr *FullExpr) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003897 if (!FullExpr)
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003898 return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00003899
Douglas Gregord0937222010-12-13 22:49:22 +00003900 if (DiagnoseUnexpandedParameterPack(FullExpr))
3901 return ExprError();
3902
John McCallf6a16482010-12-04 03:47:34 +00003903 IgnoredValueConversions(FullExpr);
John McCallb4eb64d2010-10-08 02:01:28 +00003904 CheckImplicitConversions(FullExpr);
John McCall4765fa02010-12-06 08:20:24 +00003905 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson165a0a02009-05-17 18:41:29 +00003906}
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003907
3908StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
3909 if (!FullStmt) return StmtError();
3910
John McCall4765fa02010-12-06 08:20:24 +00003911 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003912}