blob: 0d48741387a1d9c7ef4c90ed1885c982a91f33ba [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;
110 PrefixSS.setScopeRep(Prefix);
111 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.
239 NestedNameSpecifier *NNS = 0;
240 SourceRange Range;
241 if (SS.isSet()) {
242 NNS = (NestedNameSpecifier *)SS.getScopeRep();
243 Range = SourceRange(SS.getRange().getBegin(), NameLoc);
244 } else {
245 NNS = NestedNameSpecifier::Create(Context, &II);
246 Range = SourceRange(NameLoc);
247 }
248
John McCallb3d87482010-08-24 05:47:05 +0000249 QualType T = CheckTypenameType(ETK_None, NNS, II,
250 SourceLocation(),
251 Range, NameLoc);
252 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000253 }
254
255 if (ObjectTypePtr)
256 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000257 << &II;
Douglas Gregor124b8782010-02-16 19:09:40 +0000258 else
259 Diag(NameLoc, diag::err_destructor_class_name);
260
John McCallb3d87482010-08-24 05:47:05 +0000261 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000262}
263
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000264/// \brief Build a C++ typeid expression with a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000265ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000266 SourceLocation TypeidLoc,
267 TypeSourceInfo *Operand,
268 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000269 // C++ [expr.typeid]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000270 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000271 // that is the operand of typeid are always ignored.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000272 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000273 // type, the class shall be completely-defined.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000274 Qualifiers Quals;
275 QualType T
276 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
277 Quals);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000278 if (T->getAs<RecordType>() &&
279 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
280 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000281
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000282 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
283 Operand,
284 SourceRange(TypeidLoc, RParenLoc)));
285}
286
287/// \brief Build a C++ typeid expression with an expression operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000288ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000289 SourceLocation TypeidLoc,
290 Expr *E,
291 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000292 bool isUnevaluatedOperand = true;
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000293 if (E && !E->isTypeDependent()) {
294 QualType T = E->getType();
295 if (const RecordType *RecordT = T->getAs<RecordType>()) {
296 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
297 // C++ [expr.typeid]p3:
298 // [...] If the type of the expression is a class type, the class
299 // shall be completely-defined.
300 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
301 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000302
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000303 // C++ [expr.typeid]p3:
Sebastian Redl906082e2010-07-20 04:20:21 +0000304 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000305 // polymorphic class type [...] [the] expression is an unevaluated
306 // operand. [...]
Sebastian Redl906082e2010-07-20 04:20:21 +0000307 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000308 isUnevaluatedOperand = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000309
310 // We require a vtable to query the type at run time.
311 MarkVTableUsed(TypeidLoc, RecordD);
312 }
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000313 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000314
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000315 // C++ [expr.typeid]p4:
316 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000317 // cv-qualified type, the result of the typeid expression refers to a
318 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000319 // type.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000320 Qualifiers Quals;
321 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
322 if (!Context.hasSameType(T, UnqualT)) {
323 T = UnqualT;
John McCall2de56d12010-08-25 11:45:40 +0000324 ImpCastExprToType(E, UnqualT, CK_NoOp, CastCategory(E));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000325 }
326 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000327
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000328 // If this is an unevaluated operand, clear out the set of
329 // declaration references we have been computing and eliminate any
330 // temporaries introduced in its computation.
331 if (isUnevaluatedOperand)
332 ExprEvalContexts.back().Context = Unevaluated;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000333
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000334 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCall9ae2f072010-08-23 23:25:46 +0000335 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000336 SourceRange(TypeidLoc, RParenLoc)));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000337}
338
339/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCall60d7b3a2010-08-24 06:29:42 +0000340ExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000341Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
342 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000343 // Find the std::type_info type.
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000344 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000345 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000346
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000347 if (!CXXTypeInfoDecl) {
348 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
349 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
350 LookupQualifiedName(R, getStdNamespace());
351 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
352 if (!CXXTypeInfoDecl)
353 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
354 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000355
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000356 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000357
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000358 if (isType) {
359 // The operand is a type; handle it as such.
360 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +0000361 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
362 &TInfo);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000363 if (T.isNull())
364 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000365
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000366 if (!TInfo)
367 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000368
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000369 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000370 }
Mike Stump1eb44332009-09-09 15:08:12 +0000371
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000372 // The operand is an expression.
John McCall9ae2f072010-08-23 23:25:46 +0000373 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000374}
375
Francois Pichet6915c522010-12-27 01:32:00 +0000376/// Retrieve the UuidAttr associated with QT.
377static UuidAttr *GetUuidAttrOfType(QualType QT) {
378 // Optionally remove one level of pointer, reference or array indirection.
John McCallf4c73712011-01-19 06:33:43 +0000379 const Type *Ty = QT.getTypePtr();;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000380 if (QT->isPointerType() || QT->isReferenceType())
381 Ty = QT->getPointeeType().getTypePtr();
382 else if (QT->isArrayType())
383 Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
384
Francois Pichet6915c522010-12-27 01:32:00 +0000385 // Loop all class definition and declaration looking for an uuid attribute.
386 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
387 while (RD) {
388 if (UuidAttr *Uuid = RD->getAttr<UuidAttr>())
389 return Uuid;
390 RD = RD->getPreviousDeclaration();
391 }
392 return 0;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000393}
394
Francois Pichet01b7c302010-09-08 12:20:18 +0000395/// \brief Build a Microsoft __uuidof expression with a type operand.
396ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
397 SourceLocation TypeidLoc,
398 TypeSourceInfo *Operand,
399 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000400 if (!Operand->getType()->isDependentType()) {
401 if (!GetUuidAttrOfType(Operand->getType()))
402 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
403 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000404
Francois Pichet01b7c302010-09-08 12:20:18 +0000405 // FIXME: add __uuidof semantic analysis for type operand.
406 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
407 Operand,
408 SourceRange(TypeidLoc, RParenLoc)));
409}
410
411/// \brief Build a Microsoft __uuidof expression with an expression operand.
412ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
413 SourceLocation TypeidLoc,
414 Expr *E,
415 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000416 if (!E->getType()->isDependentType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000417 if (!GetUuidAttrOfType(E->getType()) &&
Francois Pichet6915c522010-12-27 01:32:00 +0000418 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
419 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
420 }
421 // FIXME: add __uuidof semantic analysis for type operand.
Francois Pichet01b7c302010-09-08 12:20:18 +0000422 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
423 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000424 SourceRange(TypeidLoc, RParenLoc)));
Francois Pichet01b7c302010-09-08 12:20:18 +0000425}
426
427/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
428ExprResult
429Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
430 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000431 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet01b7c302010-09-08 12:20:18 +0000432 if (!MSVCGuidDecl) {
433 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
434 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
435 LookupQualifiedName(R, Context.getTranslationUnitDecl());
436 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
437 if (!MSVCGuidDecl)
438 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000439 }
440
Francois Pichet01b7c302010-09-08 12:20:18 +0000441 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000442
Francois Pichet01b7c302010-09-08 12:20:18 +0000443 if (isType) {
444 // The operand is a type; handle it as such.
445 TypeSourceInfo *TInfo = 0;
446 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
447 &TInfo);
448 if (T.isNull())
449 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000450
Francois Pichet01b7c302010-09-08 12:20:18 +0000451 if (!TInfo)
452 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
453
454 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
455 }
456
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000457 // The operand is an expression.
Francois Pichet01b7c302010-09-08 12:20:18 +0000458 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
459}
460
Steve Naroff1b273c42007-09-16 14:56:35 +0000461/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCall60d7b3a2010-08-24 06:29:42 +0000462ExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000463Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000464 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000465 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000466 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
467 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000468}
Chris Lattner50dd2892008-02-26 00:51:44 +0000469
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000470/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCall60d7b3a2010-08-24 06:29:42 +0000471ExprResult
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000472Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
473 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
474}
475
Chris Lattner50dd2892008-02-26 00:51:44 +0000476/// ActOnCXXThrow - Parse throw expressions.
John McCall60d7b3a2010-08-24 06:29:42 +0000477ExprResult
John McCall9ae2f072010-08-23 23:25:46 +0000478Sema::ActOnCXXThrow(SourceLocation OpLoc, Expr *Ex) {
Anders Carlsson7f11d9c2011-02-19 19:26:44 +0000479 if (!getLangOptions().Exceptions)
Anders Carlssonb1fba312011-02-19 21:53:09 +0000480 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Anders Carlsson7f11d9c2011-02-19 19:26:44 +0000481
Sebastian Redl972041f2009-04-27 20:27:31 +0000482 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
483 return ExprError();
484 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
485}
486
487/// CheckCXXThrowOperand - Validate the operand of a throw.
488bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
489 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000490 // A throw-expression initializes a temporary object, called the exception
491 // object, the type of which is determined by removing any top-level
492 // cv-qualifiers from the static type of the operand of throw and adjusting
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000493 // the type from "array of T" or "function returning T" to "pointer to T"
Douglas Gregor154fe982009-12-23 22:04:40 +0000494 // or "pointer to function returning T", [...]
495 if (E->getType().hasQualifiers())
John McCall2de56d12010-08-25 11:45:40 +0000496 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
Sebastian Redl906082e2010-07-20 04:20:21 +0000497 CastCategory(E));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000498
Sebastian Redl972041f2009-04-27 20:27:31 +0000499 DefaultFunctionArrayConversion(E);
500
501 // If the type of the exception would be an incomplete type or a pointer
502 // to an incomplete type other than (cv) void the program is ill-formed.
503 QualType Ty = E->getType();
John McCallac418162010-04-22 01:10:34 +0000504 bool isPointer = false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000505 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000506 Ty = Ptr->getPointeeType();
John McCallac418162010-04-22 01:10:34 +0000507 isPointer = true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000508 }
509 if (!isPointer || !Ty->isVoidType()) {
510 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000511 PDiag(isPointer ? diag::err_throw_incomplete_ptr
512 : diag::err_throw_incomplete)
513 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000514 return true;
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000515
Douglas Gregorbf422f92010-04-15 18:05:39 +0000516 if (RequireNonAbstractType(ThrowLoc, E->getType(),
517 PDiag(diag::err_throw_abstract_type)
518 << E->getSourceRange()))
519 return true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000520 }
521
John McCallac418162010-04-22 01:10:34 +0000522 // Initialize the exception result. This implicitly weeds out
523 // abstract types or types with inaccessible copy constructors.
Douglas Gregor72dfa272011-01-21 22:46:35 +0000524 const VarDecl *NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
525
Douglas Gregorf5d8f462011-01-21 18:05:27 +0000526 // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p32.
John McCallac418162010-04-22 01:10:34 +0000527 InitializedEntity Entity =
Douglas Gregor72dfa272011-01-21 22:46:35 +0000528 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
529 /*NRVO=*/false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000530 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
Douglas Gregor72dfa272011-01-21 22:46:35 +0000531 QualType(), E);
John McCallac418162010-04-22 01:10:34 +0000532 if (Res.isInvalid())
533 return true;
534 E = Res.takeAs<Expr>();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000535
Eli Friedman5ed9b932010-06-03 20:39:03 +0000536 // If the exception has class type, we need additional handling.
537 const RecordType *RecordTy = Ty->getAs<RecordType>();
538 if (!RecordTy)
539 return false;
540 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
541
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000542 // If we are throwing a polymorphic class type or pointer thereof,
543 // exception handling will make use of the vtable.
Eli Friedman5ed9b932010-06-03 20:39:03 +0000544 MarkVTableUsed(ThrowLoc, RD);
545
Eli Friedman98efb9f2010-10-12 20:32:36 +0000546 // If a pointer is thrown, the referenced object will not be destroyed.
547 if (isPointer)
548 return false;
549
Eli Friedman5ed9b932010-06-03 20:39:03 +0000550 // If the class has a non-trivial destructor, we must be able to call it.
551 if (RD->hasTrivialDestructor())
552 return false;
553
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000554 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +0000555 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman5ed9b932010-06-03 20:39:03 +0000556 if (!Destructor)
557 return false;
558
559 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
560 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregored8abf12010-07-08 06:14:04 +0000561 PDiag(diag::err_access_dtor_exception) << Ty);
Sebastian Redl972041f2009-04-27 20:27:31 +0000562 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000563}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000564
John McCall5808ce42011-02-03 08:15:49 +0000565CXXMethodDecl *Sema::tryCaptureCXXThis() {
566 // Ignore block scopes: we can capture through them.
567 // Ignore nested enum scopes: we'll diagnose non-constant expressions
568 // where they're invalid, and other uses are legitimate.
569 // Don't ignore nested class scopes: you can't use 'this' in a local class.
John McCall469a1eb2011-02-02 13:00:07 +0000570 DeclContext *DC = CurContext;
John McCall5808ce42011-02-03 08:15:49 +0000571 while (true) {
572 if (isa<BlockDecl>(DC)) DC = cast<BlockDecl>(DC)->getDeclContext();
573 else if (isa<EnumDecl>(DC)) DC = cast<EnumDecl>(DC)->getDeclContext();
574 else break;
575 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000576
John McCall5808ce42011-02-03 08:15:49 +0000577 // If we're not in an instance method, error out.
John McCall469a1eb2011-02-02 13:00:07 +0000578 CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC);
579 if (!method || !method->isInstance())
John McCall5808ce42011-02-03 08:15:49 +0000580 return 0;
John McCall469a1eb2011-02-02 13:00:07 +0000581
582 // Mark that we're closing on 'this' in all the block scopes, if applicable.
583 for (unsigned idx = FunctionScopes.size() - 1;
584 isa<BlockScopeInfo>(FunctionScopes[idx]);
585 --idx)
586 cast<BlockScopeInfo>(FunctionScopes[idx])->CapturesCXXThis = true;
587
John McCall5808ce42011-02-03 08:15:49 +0000588 return method;
589}
590
591ExprResult Sema::ActOnCXXThis(SourceLocation loc) {
592 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
593 /// is a non-lvalue expression whose value is the address of the object for
594 /// which the function is called.
595
596 CXXMethodDecl *method = tryCaptureCXXThis();
597 if (!method) return Diag(loc, diag::err_invalid_this_use);
598
599 return Owned(new (Context) CXXThisExpr(loc, method->getThisType(Context),
John McCall469a1eb2011-02-02 13:00:07 +0000600 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000601}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000602
John McCall60d7b3a2010-08-24 06:29:42 +0000603ExprResult
Douglas Gregorab6677e2010-09-08 00:15:04 +0000604Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000605 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000606 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000607 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000608 if (!TypeRep)
609 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000610
John McCall9d125032010-01-15 18:39:57 +0000611 TypeSourceInfo *TInfo;
612 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
613 if (!TInfo)
614 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregorab6677e2010-09-08 00:15:04 +0000615
616 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
617}
618
619/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
620/// Can be interpreted either as function-style casting ("int(x)")
621/// or class type construction ("ClassType(x,y,z)")
622/// or creation of a value-initialized type ("int()").
623ExprResult
624Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
625 SourceLocation LParenLoc,
626 MultiExprArg exprs,
627 SourceLocation RParenLoc) {
628 QualType Ty = TInfo->getType();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000629 unsigned NumExprs = exprs.size();
630 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000631 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000632 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
633
Sebastian Redlf53597f2009-03-15 17:47:39 +0000634 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000635 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000636 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000637
Douglas Gregorab6677e2010-09-08 00:15:04 +0000638 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000639 LParenLoc,
640 Exprs, NumExprs,
641 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000642 }
643
Anders Carlssonbb60a502009-08-27 03:53:50 +0000644 if (Ty->isArrayType())
645 return ExprError(Diag(TyBeginLoc,
646 diag::err_value_init_for_array_type) << FullRange);
647 if (!Ty->isVoidType() &&
648 RequireCompleteType(TyBeginLoc, Ty,
649 PDiag(diag::err_invalid_incomplete_type_use)
650 << FullRange))
651 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000652
Anders Carlssonbb60a502009-08-27 03:53:50 +0000653 if (RequireNonAbstractType(TyBeginLoc, Ty,
654 diag::err_allocation_of_abstract_type))
655 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000656
657
Douglas Gregor506ae412009-01-16 18:33:17 +0000658 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000659 // If the expression list is a single expression, the type conversion
660 // expression is equivalent (in definedness, and if defined in meaning) to the
661 // corresponding cast expression.
662 //
663 if (NumExprs == 1) {
John McCalldaa8e4e2010-11-15 09:13:47 +0000664 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +0000665 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +0000666 CXXCastPath BasePath;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000667 if (CheckCastTypes(TInfo->getTypeLoc().getSourceRange(), Ty, Exprs[0],
John McCallf89e55a2010-11-18 06:31:45 +0000668 Kind, VK, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000669 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000670 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000671
672 exprs.release();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000673
John McCallf871d0c2010-08-07 06:22:56 +0000674 return Owned(CXXFunctionalCastExpr::Create(Context,
Douglas Gregorab6677e2010-09-08 00:15:04 +0000675 Ty.getNonLValueExprType(Context),
John McCallf89e55a2010-11-18 06:31:45 +0000676 VK, TInfo, TyBeginLoc, Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000677 Exprs[0], &BasePath,
678 RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000679 }
680
Douglas Gregor19311e72010-09-08 21:40:08 +0000681 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
682 InitializationKind Kind
683 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
684 LParenLoc, RParenLoc)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000685 : InitializationKind::CreateValue(TyBeginLoc,
Douglas Gregor19311e72010-09-08 21:40:08 +0000686 LParenLoc, RParenLoc);
687 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
688 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redlf53597f2009-03-15 17:47:39 +0000689
Douglas Gregor19311e72010-09-08 21:40:08 +0000690 // FIXME: Improve AST representation?
691 return move(Result);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000692}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000693
John McCall6ec278d2011-01-27 09:37:56 +0000694/// doesUsualArrayDeleteWantSize - Answers whether the usual
695/// operator delete[] for the given type has a size_t parameter.
696static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
697 QualType allocType) {
698 const RecordType *record =
699 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
700 if (!record) return false;
701
702 // Try to find an operator delete[] in class scope.
703
704 DeclarationName deleteName =
705 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
706 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
707 S.LookupQualifiedName(ops, record->getDecl());
708
709 // We're just doing this for information.
710 ops.suppressDiagnostics();
711
712 // Very likely: there's no operator delete[].
713 if (ops.empty()) return false;
714
715 // If it's ambiguous, it should be illegal to call operator delete[]
716 // on this thing, so it doesn't matter if we allocate extra space or not.
717 if (ops.isAmbiguous()) return false;
718
719 LookupResult::Filter filter = ops.makeFilter();
720 while (filter.hasNext()) {
721 NamedDecl *del = filter.next()->getUnderlyingDecl();
722
723 // C++0x [basic.stc.dynamic.deallocation]p2:
724 // A template instance is never a usual deallocation function,
725 // regardless of its signature.
726 if (isa<FunctionTemplateDecl>(del)) {
727 filter.erase();
728 continue;
729 }
730
731 // C++0x [basic.stc.dynamic.deallocation]p2:
732 // If class T does not declare [an operator delete[] with one
733 // parameter] but does declare a member deallocation function
734 // named operator delete[] with exactly two parameters, the
735 // second of which has type std::size_t, then this function
736 // is a usual deallocation function.
737 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
738 filter.erase();
739 continue;
740 }
741 }
742 filter.done();
743
744 if (!ops.isSingleResult()) return false;
745
746 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
747 return (del->getNumParams() == 2);
748}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000749
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000750/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
751/// @code new (memory) int[size][4] @endcode
752/// or
753/// @code ::new Foo(23, "hello") @endcode
754/// For the interpretation of this heap of arguments, consult the base version.
John McCall60d7b3a2010-08-24 06:29:42 +0000755ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000756Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000757 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000758 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000759 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000760 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000761 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000762 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000763 // If the specified type is an array, unwrap it and save the expression.
764 if (D.getNumTypeObjects() > 0 &&
765 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
766 DeclaratorChunk &Chunk = D.getTypeObject(0);
767 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000768 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
769 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000770 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000771 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
772 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000773
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000774 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000775 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000776 }
777
Douglas Gregor043cad22009-09-11 00:18:58 +0000778 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000779 if (ArraySize) {
780 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000781 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
782 break;
783
784 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
785 if (Expr *NumElts = (Expr *)Array.NumElts) {
786 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
787 !NumElts->isIntegerConstantExpr(Context)) {
788 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
789 << NumElts->getSourceRange();
790 return ExprError();
791 }
792 }
793 }
794 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000795
John McCallbf1a0282010-06-04 23:28:52 +0000796 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
797 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
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000801 if (!TInfo)
802 TInfo = Context.getTrivialTypeSourceInfo(AllocType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000803
Mike Stump1eb44332009-09-09 15:08:12 +0000804 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000805 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000806 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000807 PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000808 TypeIdParens,
Mike Stump1eb44332009-09-09 15:08:12 +0000809 AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000810 TInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000811 ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000812 ConstructorLParen,
813 move(ConstructorArgs),
814 ConstructorRParen);
815}
816
John McCall60d7b3a2010-08-24 06:29:42 +0000817ExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000818Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
819 SourceLocation PlacementLParen,
820 MultiExprArg PlacementArgs,
821 SourceLocation PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000822 SourceRange TypeIdParens,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000823 QualType AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000824 TypeSourceInfo *AllocTypeInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000825 Expr *ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000826 SourceLocation ConstructorLParen,
827 MultiExprArg ConstructorArgs,
828 SourceLocation ConstructorRParen) {
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000829 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000830
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000831 // Per C++0x [expr.new]p5, the type being constructed may be a
832 // typedef of an array type.
John McCall9ae2f072010-08-23 23:25:46 +0000833 if (!ArraySize) {
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000834 if (const ConstantArrayType *Array
835 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000836 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
837 Context.getSizeType(),
838 TypeRange.getEnd());
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000839 AllocType = Array->getElementType();
840 }
841 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000842
Douglas Gregora0750762010-10-06 16:00:31 +0000843 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
844 return ExprError();
845
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000846 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000847
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000848 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
849 // or enumeration type with a non-negative value."
Sebastian Redl28507842009-02-26 14:39:58 +0000850 if (ArraySize && !ArraySize->isTypeDependent()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000851
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000852 QualType SizeType = ArraySize->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000853
John McCall60d7b3a2010-08-24 06:29:42 +0000854 ExprResult ConvertedSize
John McCall9ae2f072010-08-23 23:25:46 +0000855 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000856 PDiag(diag::err_array_size_not_integral),
857 PDiag(diag::err_array_size_incomplete_type)
858 << ArraySize->getSourceRange(),
859 PDiag(diag::err_array_size_explicit_conversion),
860 PDiag(diag::note_array_size_conversion),
861 PDiag(diag::err_array_size_ambiguous_conversion),
862 PDiag(diag::note_array_size_conversion),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000863 PDiag(getLangOptions().CPlusPlus0x? 0
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000864 : diag::ext_array_size_conversion));
865 if (ConvertedSize.isInvalid())
866 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000867
John McCall9ae2f072010-08-23 23:25:46 +0000868 ArraySize = ConvertedSize.take();
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000869 SizeType = ArraySize->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000870 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000871 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000872
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000873 // Let's see if this is a constant < 0. If so, we reject it out of hand.
874 // We don't care about special rules, so we tell the machinery it's not
875 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000876 if (!ArraySize->isValueDependent()) {
877 llvm::APSInt Value;
878 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
879 if (Value < llvm::APSInt(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000880 llvm::APInt::getNullValue(Value.getBitWidth()),
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000881 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000882 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +0000883 diag::err_typecheck_negative_array_size)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000884 << ArraySize->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000885
Douglas Gregor2767ce22010-08-18 00:39:00 +0000886 if (!AllocType->isDependentType()) {
887 unsigned ActiveSizeBits
888 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
889 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000890 Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +0000891 diag::err_array_too_large)
892 << Value.toString(10)
893 << ArraySize->getSourceRange();
894 return ExprError();
895 }
896 }
Douglas Gregor4bd40312010-07-13 15:54:32 +0000897 } else if (TypeIdParens.isValid()) {
898 // Can't have dynamic array size when the type-id is in parentheses.
899 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
900 << ArraySize->getSourceRange()
901 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
902 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000903
Douglas Gregor4bd40312010-07-13 15:54:32 +0000904 TypeIdParens = SourceRange();
Sebastian Redl28507842009-02-26 14:39:58 +0000905 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000906 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000907
Eli Friedman73c39ab2009-10-20 08:27:19 +0000908 ImpCastExprToType(ArraySize, Context.getSizeType(),
John McCall2de56d12010-08-25 11:45:40 +0000909 CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000910 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000911
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000912 FunctionDecl *OperatorNew = 0;
913 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000914 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
915 unsigned NumPlaceArgs = PlacementArgs.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000916
Sebastian Redl28507842009-02-26 14:39:58 +0000917 if (!AllocType->isDependentType() &&
918 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
919 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000920 SourceRange(PlacementLParen, PlacementRParen),
921 UseGlobal, AllocType, ArraySize, PlaceArgs,
922 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000923 return ExprError();
John McCall6ec278d2011-01-27 09:37:56 +0000924
925 // If this is an array allocation, compute whether the usual array
926 // deallocation function for the type has a size_t parameter.
927 bool UsualArrayDeleteWantsSize = false;
928 if (ArraySize && !AllocType->isDependentType())
929 UsualArrayDeleteWantsSize
930 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
931
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000932 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000933 if (OperatorNew) {
934 // Add default arguments, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000935 const FunctionProtoType *Proto =
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000936 OperatorNew->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000937 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000938 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000939
Anders Carlsson28e94832010-05-03 02:07:56 +0000940 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000941 Proto, 1, PlaceArgs, NumPlaceArgs,
Anders Carlsson28e94832010-05-03 02:07:56 +0000942 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000943 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000944
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000945 NumPlaceArgs = AllPlaceArgs.size();
946 if (NumPlaceArgs > 0)
947 PlaceArgs = &AllPlaceArgs[0];
948 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000949
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000950 bool Init = ConstructorLParen.isValid();
951 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000952 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000953 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
954 unsigned NumConsArgs = ConstructorArgs.size();
John McCallca0408f2010-08-23 06:44:23 +0000955 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000956
Anders Carlsson48c95012010-05-03 15:45:23 +0000957 // Array 'new' can't have any initializers.
Anders Carlsson55cbd6e2010-05-16 16:24:20 +0000958 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlsson48c95012010-05-03 15:45:23 +0000959 SourceRange InitRange(ConsArgs[0]->getLocStart(),
960 ConsArgs[NumConsArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000961
Anders Carlsson48c95012010-05-03 15:45:23 +0000962 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
963 return ExprError();
964 }
965
Douglas Gregor99a2e602009-12-16 01:38:02 +0000966 if (!AllocType->isDependentType() &&
967 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
968 // C++0x [expr.new]p15:
969 // A new-expression that creates an object of type T initializes that
970 // object as follows:
971 InitializationKind Kind
972 // - If the new-initializer is omitted, the object is default-
973 // initialized (8.5); if no initialization is performed,
974 // the object has indeterminate value
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000975 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000976 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor99a2e602009-12-16 01:38:02 +0000977 // initialization rules of 8.5 for direct-initialization.
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000978 : InitializationKind::CreateDirect(TypeRange.getBegin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000979 ConstructorLParen,
Douglas Gregor99a2e602009-12-16 01:38:02 +0000980 ConstructorRParen);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000981
Douglas Gregor99a2e602009-12-16 01:38:02 +0000982 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +0000983 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000984 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000985 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor99a2e602009-12-16 01:38:02 +0000986 move(ConstructorArgs));
987 if (FullInit.isInvalid())
988 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000989
990 // FullInit is our initializer; walk through it to determine if it's a
Douglas Gregor99a2e602009-12-16 01:38:02 +0000991 // constructor call, which CXXNewExpr handles directly.
992 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
993 if (CXXBindTemporaryExpr *Binder
994 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
995 FullInitExpr = Binder->getSubExpr();
996 if (CXXConstructExpr *Construct
997 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
998 Constructor = Construct->getConstructor();
999 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
1000 AEnd = Construct->arg_end();
1001 A != AEnd; ++A)
John McCall3fa5cae2010-10-26 07:05:15 +00001002 ConvertedConstructorArgs.push_back(*A);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001003 } else {
1004 // Take the converted initializer.
1005 ConvertedConstructorArgs.push_back(FullInit.release());
1006 }
1007 } else {
1008 // No initialization required.
1009 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001010
Douglas Gregor99a2e602009-12-16 01:38:02 +00001011 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +00001012 NumConsArgs = ConvertedConstructorArgs.size();
1013 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001014 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001015
Douglas Gregor6d908702010-02-26 05:06:18 +00001016 // Mark the new and delete operators as referenced.
1017 if (OperatorNew)
1018 MarkDeclarationReferenced(StartLoc, OperatorNew);
1019 if (OperatorDelete)
1020 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1021
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001022 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001023
Sebastian Redlf53597f2009-03-15 17:47:39 +00001024 PlacementArgs.release();
1025 ConstructorArgs.release();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001026
Ted Kremenekad7fe862010-02-11 22:51:03 +00001027 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregor4bd40312010-07-13 15:54:32 +00001028 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001029 ArraySize, Constructor, Init,
1030 ConsArgs, NumConsArgs, OperatorDelete,
John McCall6ec278d2011-01-27 09:37:56 +00001031 UsualArrayDeleteWantsSize,
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001032 ResultType, AllocTypeInfo,
1033 StartLoc,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001034 Init ? ConstructorRParen :
Chandler Carruth428edaf2010-10-25 08:47:36 +00001035 TypeRange.getEnd(),
1036 ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001037}
1038
1039/// CheckAllocatedType - Checks that a type is suitable as the allocated type
1040/// in a new-expression.
1041/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +00001042bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00001043 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001044 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1045 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +00001046 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001047 return Diag(Loc, diag::err_bad_new_type)
1048 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001049 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001050 return Diag(Loc, diag::err_bad_new_type)
1051 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001052 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +00001053 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001054 PDiag(diag::err_new_incomplete_type)
1055 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001056 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +00001057 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +00001058 diag::err_allocation_of_abstract_type))
1059 return true;
Douglas Gregora0750762010-10-06 16:00:31 +00001060 else if (AllocType->isVariablyModifiedType())
1061 return Diag(Loc, diag::err_variably_modified_new_type)
1062 << AllocType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001063
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001064 return false;
1065}
1066
Douglas Gregor6d908702010-02-26 05:06:18 +00001067/// \brief Determine whether the given function is a non-placement
1068/// deallocation function.
1069static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1070 if (FD->isInvalidDecl())
1071 return false;
1072
1073 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1074 return Method->isUsualDeallocationFunction();
1075
1076 return ((FD->getOverloadedOperator() == OO_Delete ||
1077 FD->getOverloadedOperator() == OO_Array_Delete) &&
1078 FD->getNumParams() == 1);
1079}
1080
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001081/// FindAllocationFunctions - Finds the overloads of operator new and delete
1082/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001083bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1084 bool UseGlobal, QualType AllocType,
1085 bool IsArray, Expr **PlaceArgs,
1086 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001087 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +00001088 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001089 // --- Choosing an allocation function ---
1090 // C++ 5.3.4p8 - 14 & 18
1091 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1092 // in the scope of the allocated class.
1093 // 2) If an array size is given, look for operator new[], else look for
1094 // operator new.
1095 // 3) The first argument is always size_t. Append the arguments from the
1096 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001097
1098 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
1099 // We don't care about the actual value of this argument.
1100 // FIXME: Should the Sema create the expression and embed it in the syntax
1101 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00001102 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Anders Carlssond67c4c32009-08-16 20:29:29 +00001103 Context.Target.getPointerWidth(0)),
1104 Context.getSizeType(),
1105 SourceLocation());
1106 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001107 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1108
Douglas Gregor6d908702010-02-26 05:06:18 +00001109 // C++ [expr.new]p8:
1110 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001111 // function's name is operator new and the deallocation function's
Douglas Gregor6d908702010-02-26 05:06:18 +00001112 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001113 // type, the allocation function's name is operator new[] and the
1114 // deallocation function's name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001115 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1116 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +00001117 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1118 IsArray ? OO_Array_Delete : OO_Delete);
1119
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001120 QualType AllocElemType = Context.getBaseElementType(AllocType);
1121
1122 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +00001123 CXXRecordDecl *Record
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001124 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +00001125 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001126 AllocArgs.size(), Record, /*AllowMissing=*/true,
1127 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001128 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001129 }
1130 if (!OperatorNew) {
1131 // Didn't find a member overload. Look for a global one.
1132 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +00001133 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +00001134 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001135 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1136 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001137 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001138 }
1139
John McCall9c82afc2010-04-20 02:18:25 +00001140 // We don't need an operator delete if we're running under
1141 // -fno-exceptions.
1142 if (!getLangOptions().Exceptions) {
1143 OperatorDelete = 0;
1144 return false;
1145 }
1146
Anders Carlssond9583892009-05-31 20:26:12 +00001147 // FindAllocationOverload can change the passed in arguments, so we need to
1148 // copy them back.
1149 if (NumPlaceArgs > 0)
1150 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001151
Douglas Gregor6d908702010-02-26 05:06:18 +00001152 // C++ [expr.new]p19:
1153 //
1154 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001155 // deallocation function's name is looked up in the global
Douglas Gregor6d908702010-02-26 05:06:18 +00001156 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001157 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6d908702010-02-26 05:06:18 +00001158 // the scope of T. If this lookup fails to find the name, or if
1159 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001160 // deallocation function's name is looked up in the global scope.
Douglas Gregor6d908702010-02-26 05:06:18 +00001161 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001162 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001163 CXXRecordDecl *RD
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001164 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6d908702010-02-26 05:06:18 +00001165 LookupQualifiedName(FoundDelete, RD);
1166 }
John McCall90c8c572010-03-18 08:19:33 +00001167 if (FoundDelete.isAmbiguous())
1168 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +00001169
1170 if (FoundDelete.empty()) {
1171 DeclareGlobalNewDelete();
1172 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1173 }
1174
1175 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +00001176
1177 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1178
John McCalledeb6c92010-09-14 21:34:24 +00001179 // Whether we're looking for a placement operator delete is dictated
1180 // by whether we selected a placement operator new, not by whether
1181 // we had explicit placement arguments. This matters for things like
1182 // struct A { void *operator new(size_t, int = 0); ... };
1183 // A *a = new A()
1184 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1185
1186 if (isPlacementNew) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001187 // C++ [expr.new]p20:
1188 // A declaration of a placement deallocation function matches the
1189 // declaration of a placement allocation function if it has the
1190 // same number of parameters and, after parameter transformations
1191 // (8.3.5), all parameter types except the first are
1192 // identical. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001193 //
Douglas Gregor6d908702010-02-26 05:06:18 +00001194 // To perform this comparison, we compute the function type that
1195 // the deallocation function should have, and use that type both
1196 // for template argument deduction and for comparison purposes.
John McCalle23cf432010-12-14 08:05:40 +00001197 //
1198 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6d908702010-02-26 05:06:18 +00001199 QualType ExpectedFunctionType;
1200 {
1201 const FunctionProtoType *Proto
1202 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00001203
Douglas Gregor6d908702010-02-26 05:06:18 +00001204 llvm::SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001205 ArgTypes.push_back(Context.VoidPtrTy);
Douglas Gregor6d908702010-02-26 05:06:18 +00001206 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1207 ArgTypes.push_back(Proto->getArgType(I));
1208
John McCalle23cf432010-12-14 08:05:40 +00001209 FunctionProtoType::ExtProtoInfo EPI;
1210 EPI.Variadic = Proto->isVariadic();
1211
Douglas Gregor6d908702010-02-26 05:06:18 +00001212 ExpectedFunctionType
1213 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
John McCalle23cf432010-12-14 08:05:40 +00001214 ArgTypes.size(), EPI);
Douglas Gregor6d908702010-02-26 05:06:18 +00001215 }
1216
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001217 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001218 DEnd = FoundDelete.end();
1219 D != DEnd; ++D) {
1220 FunctionDecl *Fn = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001221 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6d908702010-02-26 05:06:18 +00001222 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1223 // Perform template argument deduction to try to match the
1224 // expected function type.
1225 TemplateDeductionInfo Info(Context, StartLoc);
1226 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1227 continue;
1228 } else
1229 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1230
1231 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001232 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001233 }
1234 } else {
1235 // C++ [expr.new]p20:
1236 // [...] Any non-placement deallocation function matches a
1237 // non-placement allocation function. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001238 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001239 DEnd = FoundDelete.end();
1240 D != DEnd; ++D) {
1241 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1242 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001243 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001244 }
1245 }
1246
1247 // C++ [expr.new]p20:
1248 // [...] If the lookup finds a single matching deallocation
1249 // function, that function will be called; otherwise, no
1250 // deallocation function will be called.
1251 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001252 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001253
1254 // C++0x [expr.new]p20:
1255 // If the lookup finds the two-parameter form of a usual
1256 // deallocation function (3.7.4.2) and that function, considered
1257 // as a placement deallocation function, would have been
1258 // selected as a match for the allocation function, the program
1259 // is ill-formed.
1260 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1261 isNonPlacementDeallocationFunction(OperatorDelete)) {
1262 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001263 << SourceRange(PlaceArgs[0]->getLocStart(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001264 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1265 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1266 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001267 } else {
1268 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001269 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001270 }
1271 }
1272
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001273 return false;
1274}
1275
Sebastian Redl7f662392008-12-04 22:20:51 +00001276/// FindAllocationOverload - Find an fitting overload for the allocation
1277/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001278bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1279 DeclarationName Name, Expr** Args,
1280 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +00001281 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001282 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1283 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001284 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001285 if (AllowMissing)
1286 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001287 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001288 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001289 }
1290
John McCall90c8c572010-03-18 08:19:33 +00001291 if (R.isAmbiguous())
1292 return true;
1293
1294 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001295
John McCall5769d612010-02-08 23:07:23 +00001296 OverloadCandidateSet Candidates(StartLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001297 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001298 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001299 // Even member operator new/delete are implicitly treated as
1300 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001301 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001302
John McCall9aa472c2010-03-19 07:35:19 +00001303 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1304 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001305 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1306 Candidates,
1307 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001308 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001309 }
1310
John McCall9aa472c2010-03-19 07:35:19 +00001311 FunctionDecl *Fn = cast<FunctionDecl>(D);
1312 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001313 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001314 }
1315
1316 // Do the resolution.
1317 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00001318 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001319 case OR_Success: {
1320 // Got one!
1321 FunctionDecl *FnDecl = Best->Function;
1322 // The first argument is size_t, and the first parameter must be size_t,
1323 // too. This is checked on declaration and can be assumed. (It can't be
1324 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001325 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001326 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1327 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
John McCall60d7b3a2010-08-24 06:29:42 +00001328 ExprResult Result
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001329 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001330 Context,
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001331 FnDecl->getParamDecl(i)),
1332 SourceLocation(),
John McCall3fa5cae2010-10-26 07:05:15 +00001333 Owned(Args[i]));
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001334 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001335 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001336
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001337 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001338 }
1339 Operator = FnDecl;
John McCall9aa472c2010-03-19 07:35:19 +00001340 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001341 return false;
1342 }
1343
1344 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +00001345 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001346 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001347 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001348 return true;
1349
1350 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +00001351 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +00001352 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001353 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001354 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001355
1356 case OR_Deleted:
1357 Diag(StartLoc, diag::err_ovl_deleted_call)
1358 << Best->Function->isDeleted()
1359 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001360 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001361 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001362 }
1363 assert(false && "Unreachable, bad result from BestViableFunction");
1364 return true;
1365}
1366
1367
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001368/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1369/// delete. These are:
1370/// @code
1371/// void* operator new(std::size_t) throw(std::bad_alloc);
1372/// void* operator new[](std::size_t) throw(std::bad_alloc);
1373/// void operator delete(void *) throw();
1374/// void operator delete[](void *) throw();
1375/// @endcode
1376/// Note that the placement and nothrow forms of new are *not* implicitly
1377/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001378void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001379 if (GlobalNewDeleteDeclared)
1380 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001381
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001382 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001383 // [...] The following allocation and deallocation functions (18.4) are
1384 // implicitly declared in global scope in each translation unit of a
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001385 // program
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001386 //
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001387 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001388 // void* operator new[](std::size_t) throw(std::bad_alloc);
1389 // void operator delete(void*) throw();
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001390 // void operator delete[](void*) throw();
1391 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001392 // These implicit declarations introduce only the function names operator
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001393 // new, operator new[], operator delete, operator delete[].
1394 //
1395 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1396 // "std" or "bad_alloc" as necessary to form the exception specification.
1397 // However, we do not make these implicit declarations visible to name
1398 // lookup.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001399 if (!StdBadAlloc) {
1400 // The "std::bad_alloc" class has not yet been declared, so build it
1401 // implicitly.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001402 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1403 getOrCreateStdNamespace(),
1404 SourceLocation(),
1405 &PP.getIdentifierTable().get("bad_alloc"),
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001406 SourceLocation(), 0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001407 getStdBadAlloc()->setImplicit(true);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001408 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001409
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001410 GlobalNewDeleteDeclared = true;
1411
1412 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1413 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001414 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001415
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001416 DeclareGlobalAllocationFunction(
1417 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001418 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001419 DeclareGlobalAllocationFunction(
1420 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001421 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001422 DeclareGlobalAllocationFunction(
1423 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1424 Context.VoidTy, VoidPtr);
1425 DeclareGlobalAllocationFunction(
1426 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1427 Context.VoidTy, VoidPtr);
1428}
1429
1430/// DeclareGlobalAllocationFunction - Declares a single implicit global
1431/// allocation function if it doesn't already exist.
1432void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001433 QualType Return, QualType Argument,
1434 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001435 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1436
1437 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001438 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001439 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001440 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001441 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001442 // Only look at non-template functions, as it is the predefined,
1443 // non-templated allocation function we are trying to declare here.
1444 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1445 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001446 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001447 Func->getParamDecl(0)->getType().getUnqualifiedType());
1448 // FIXME: Do we need to check for default arguments here?
Douglas Gregor7b868622010-08-18 15:06:25 +00001449 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1450 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00001451 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001452 return;
Douglas Gregor7b868622010-08-18 15:06:25 +00001453 }
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001454 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001455 }
1456 }
1457
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001458 QualType BadAllocType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001459 bool HasBadAllocExceptionSpec
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001460 = (Name.getCXXOverloadedOperator() == OO_New ||
1461 Name.getCXXOverloadedOperator() == OO_Array_New);
1462 if (HasBadAllocExceptionSpec) {
1463 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001464 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001465 }
John McCalle23cf432010-12-14 08:05:40 +00001466
1467 FunctionProtoType::ExtProtoInfo EPI;
1468 EPI.HasExceptionSpec = true;
1469 if (HasBadAllocExceptionSpec) {
1470 EPI.NumExceptions = 1;
1471 EPI.Exceptions = &BadAllocType;
1472 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001473
John McCalle23cf432010-12-14 08:05:40 +00001474 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001475 FunctionDecl *Alloc =
1476 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCalld931b082010-08-26 03:08:43 +00001477 FnType, /*TInfo=*/0, SC_None,
1478 SC_None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001479 Alloc->setImplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001480
Nuno Lopesfc284482009-12-16 16:59:22 +00001481 if (AddMallocAttr)
Sean Huntcf807c42010-08-18 23:23:40 +00001482 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001483
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001484 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00001485 0, Argument, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00001486 SC_None,
1487 SC_None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00001488 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001489
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001490 // FIXME: Also add this declaration to the IdentifierResolver, but
1491 // make sure it is at the end of the chain to coincide with the
1492 // global scope.
John McCall5f1e0942010-08-24 08:50:51 +00001493 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001494}
1495
Anders Carlsson78f74552009-11-15 18:45:20 +00001496bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1497 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00001498 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001499 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001500 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001501 LookupQualifiedName(Found, RD);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001502
John McCalla24dc2e2009-11-17 02:14:36 +00001503 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001504 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001505
Chandler Carruth23893242010-06-28 00:30:51 +00001506 Found.suppressDiagnostics();
1507
John McCall046a7462010-08-04 00:31:26 +00001508 llvm::SmallVector<DeclAccessPair,4> Matches;
Anders Carlsson78f74552009-11-15 18:45:20 +00001509 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1510 F != FEnd; ++F) {
Chandler Carruth09556fd2010-08-08 07:04:00 +00001511 NamedDecl *ND = (*F)->getUnderlyingDecl();
1512
1513 // Ignore template operator delete members from the check for a usual
1514 // deallocation function.
1515 if (isa<FunctionTemplateDecl>(ND))
1516 continue;
1517
1518 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall046a7462010-08-04 00:31:26 +00001519 Matches.push_back(F.getPair());
1520 }
1521
1522 // There's exactly one suitable operator; pick it.
1523 if (Matches.size() == 1) {
1524 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
1525 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1526 Matches[0]);
1527 return false;
1528
1529 // We found multiple suitable operators; complain about the ambiguity.
1530 } else if (!Matches.empty()) {
1531 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1532 << Name << RD;
1533
1534 for (llvm::SmallVectorImpl<DeclAccessPair>::iterator
1535 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1536 Diag((*F)->getUnderlyingDecl()->getLocation(),
1537 diag::note_member_declared_here) << Name;
1538 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001539 }
1540
1541 // We did find operator delete/operator delete[] declarations, but
1542 // none of them were suitable.
1543 if (!Found.empty()) {
1544 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1545 << Name << RD;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001546
Anders Carlsson78f74552009-11-15 18:45:20 +00001547 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
John McCall046a7462010-08-04 00:31:26 +00001548 F != FEnd; ++F)
1549 Diag((*F)->getUnderlyingDecl()->getLocation(),
1550 diag::note_member_declared_here) << Name;
Anders Carlsson78f74552009-11-15 18:45:20 +00001551
1552 return true;
1553 }
1554
1555 // Look for a global declaration.
1556 DeclareGlobalNewDelete();
1557 DeclContext *TUDecl = Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001558
Anders Carlsson78f74552009-11-15 18:45:20 +00001559 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1560 Expr* DeallocArgs[1];
1561 DeallocArgs[0] = &Null;
1562 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1563 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1564 Operator))
1565 return true;
1566
1567 assert(Operator && "Did not find a deallocation function!");
1568 return false;
1569}
1570
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001571/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1572/// @code ::delete ptr; @endcode
1573/// or
1574/// @code delete [] ptr; @endcode
John McCall60d7b3a2010-08-24 06:29:42 +00001575ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001576Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John McCall9ae2f072010-08-23 23:25:46 +00001577 bool ArrayForm, Expr *Ex) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001578 // C++ [expr.delete]p1:
1579 // The operand shall have a pointer type, or a class type having a single
1580 // conversion function to a pointer type. The result has type void.
1581 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001582 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1583
Anders Carlssond67c4c32009-08-16 20:29:29 +00001584 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001585 bool ArrayFormAsWritten = ArrayForm;
John McCall6ec278d2011-01-27 09:37:56 +00001586 bool UsualArrayDeleteWantsSize = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001587
Sebastian Redl28507842009-02-26 14:39:58 +00001588 if (!Ex->isTypeDependent()) {
1589 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001590
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001591 if (const RecordType *Record = Type->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001592 if (RequireCompleteType(StartLoc, Type,
Douglas Gregor254a9422010-07-29 14:44:35 +00001593 PDiag(diag::err_delete_incomplete_class_type)))
1594 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001595
John McCall32daa422010-03-31 01:36:47 +00001596 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1597
Fariborz Jahanian53462782009-09-11 21:44:33 +00001598 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001599 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001600 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001601 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001602 NamedDecl *D = I.getDecl();
1603 if (isa<UsingShadowDecl>(D))
1604 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1605
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001606 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001607 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001608 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001609
John McCall32daa422010-03-31 01:36:47 +00001610 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001611
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001612 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1613 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedman13578692010-08-05 02:49:48 +00001614 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001615 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001616 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001617 if (ObjectPtrConversions.size() == 1) {
1618 // We have a single conversion to a pointer-to-object type. Perform
1619 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001620 // TODO: don't redo the conversion calculation.
John McCall32daa422010-03-31 01:36:47 +00001621 if (!PerformImplicitConversion(Ex,
1622 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +00001623 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001624 Type = Ex->getType();
1625 }
1626 }
1627 else if (ObjectPtrConversions.size() > 1) {
1628 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1629 << Type << Ex->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001630 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1631 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001632 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001633 }
Sebastian Redl28507842009-02-26 14:39:58 +00001634 }
1635
Sebastian Redlf53597f2009-03-15 17:47:39 +00001636 if (!Type->isPointerType())
1637 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1638 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001639
Ted Kremenek6217b802009-07-29 21:53:49 +00001640 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor94a61572010-05-24 17:01:56 +00001641 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001642 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregor94a61572010-05-24 17:01:56 +00001643 // effectively bans deletion of "void*". However, most compilers support
1644 // this, so we treat it as a warning unless we're in a SFINAE context.
1645 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1646 << Type << Ex->getSourceRange();
1647 } else if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001648 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1649 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001650 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001651 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +00001652 PDiag(diag::warn_delete_incomplete)
1653 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001654 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +00001655
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001656 // C++ [expr.delete]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001657 // [Note: a pointer to a const type can be the operand of a
1658 // delete-expression; it is not necessary to cast away the constness
1659 // (5.2.11) of the pointer expression before it is used as the operand
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001660 // of the delete-expression. ]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001661 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
John McCall2de56d12010-08-25 11:45:40 +00001662 CK_NoOp);
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001663
1664 if (Pointee->isArrayType() && !ArrayForm) {
1665 Diag(StartLoc, diag::warn_delete_array_type)
1666 << Type << Ex->getSourceRange()
1667 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1668 ArrayForm = true;
1669 }
1670
Anders Carlssond67c4c32009-08-16 20:29:29 +00001671 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1672 ArrayForm ? OO_Array_Delete : OO_Delete);
1673
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001674 QualType PointeeElem = Context.getBaseElementType(Pointee);
1675 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001676 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1677
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001678 if (!UseGlobal &&
Anders Carlsson78f74552009-11-15 18:45:20 +00001679 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001680 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001681
John McCall6ec278d2011-01-27 09:37:56 +00001682 // If we're allocating an array of records, check whether the
1683 // usual operator delete[] has a size_t parameter.
1684 if (ArrayForm) {
1685 // If the user specifically asked to use the global allocator,
1686 // we'll need to do the lookup into the class.
1687 if (UseGlobal)
1688 UsualArrayDeleteWantsSize =
1689 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
1690
1691 // Otherwise, the usual operator delete[] should be the
1692 // function we just found.
1693 else if (isa<CXXMethodDecl>(OperatorDelete))
1694 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
1695 }
1696
Anders Carlsson78f74552009-11-15 18:45:20 +00001697 if (!RD->hasTrivialDestructor())
Douglas Gregor9b623632010-10-12 23:32:35 +00001698 if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001699 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001700 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor9b623632010-10-12 23:32:35 +00001701 DiagnoseUseOfDecl(Dtor, StartLoc);
1702 }
Anders Carlssond67c4c32009-08-16 20:29:29 +00001703 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001704
Anders Carlssond67c4c32009-08-16 20:29:29 +00001705 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001706 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001707 DeclareGlobalNewDelete();
1708 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001709 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +00001710 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001711 OperatorDelete))
1712 return ExprError();
1713 }
Mike Stump1eb44332009-09-09 15:08:12 +00001714
John McCall9c82afc2010-04-20 02:18:25 +00001715 MarkDeclarationReferenced(StartLoc, OperatorDelete);
John McCall6ec278d2011-01-27 09:37:56 +00001716
Douglas Gregord880f522011-02-01 15:50:11 +00001717 // Check access and ambiguity of operator delete and destructor.
1718 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
1719 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1720 if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
1721 CheckDestructorAccess(Ex->getExprLoc(), Dtor,
1722 PDiag(diag::err_access_dtor) << PointeeElem);
1723 }
1724 }
1725
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001726 }
1727
Sebastian Redlf53597f2009-03-15 17:47:39 +00001728 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
John McCall6ec278d2011-01-27 09:37:56 +00001729 ArrayFormAsWritten,
1730 UsualArrayDeleteWantsSize,
1731 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001732}
1733
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001734/// \brief Check the use of the given variable as a C++ condition in an if,
1735/// while, do-while, or switch statement.
John McCall60d7b3a2010-08-24 06:29:42 +00001736ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCallf89e55a2010-11-18 06:31:45 +00001737 SourceLocation StmtLoc,
1738 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001739 QualType T = ConditionVar->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001740
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001741 // C++ [stmt.select]p2:
1742 // The declarator shall not specify a function or an array.
1743 if (T->isFunctionType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001744 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001745 diag::err_invalid_use_of_function_type)
1746 << ConditionVar->getSourceRange());
1747 else if (T->isArrayType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001748 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001749 diag::err_invalid_use_of_array_type)
1750 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001751
Douglas Gregor586596f2010-05-06 17:25:47 +00001752 Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001753 ConditionVar->getLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00001754 ConditionVar->getType().getNonReferenceType(),
John McCall09431682010-11-18 19:01:18 +00001755 VK_LValue);
Douglas Gregorff331c12010-07-25 18:17:45 +00001756 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc))
Douglas Gregor586596f2010-05-06 17:25:47 +00001757 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001758
Douglas Gregor586596f2010-05-06 17:25:47 +00001759 return Owned(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001760}
1761
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001762/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1763bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1764 // C++ 6.4p4:
1765 // The value of a condition that is an initialized declaration in a statement
1766 // other than a switch statement is the value of the declared variable
1767 // implicitly converted to type bool. If that conversion is ill-formed, the
1768 // program is ill-formed.
1769 // The value of a condition that is an expression is the value of the
1770 // expression, implicitly converted to bool.
1771 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001772 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001773}
Douglas Gregor77a52232008-09-12 00:47:35 +00001774
1775/// Helper function to determine whether this is the (deprecated) C++
1776/// conversion from a string literal to a pointer to non-const char or
1777/// non-const wchar_t (for narrow and wide string literals,
1778/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001779bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001780Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1781 // Look inside the implicit cast, if it exists.
1782 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1783 From = Cast->getSubExpr();
1784
1785 // A string literal (2.13.4) that is not a wide string literal can
1786 // be converted to an rvalue of type "pointer to char"; a wide
1787 // string literal can be converted to an rvalue of type "pointer
1788 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00001789 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00001790 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001791 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001792 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001793 // This conversion is considered only when there is an
1794 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001795 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001796 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1797 (!StrLit->isWide() &&
1798 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1799 ToPointeeType->getKind() == BuiltinType::Char_S))))
1800 return true;
1801 }
1802
1803 return false;
1804}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001805
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001806static ExprResult BuildCXXCastArgument(Sema &S,
John McCall2de56d12010-08-25 11:45:40 +00001807 SourceLocation CastLoc,
1808 QualType Ty,
1809 CastKind Kind,
1810 CXXMethodDecl *Method,
Douglas Gregor83eecbe2011-01-20 01:32:05 +00001811 NamedDecl *FoundDecl,
John McCall2de56d12010-08-25 11:45:40 +00001812 Expr *From) {
Douglas Gregorba70ab62010-04-16 22:17:36 +00001813 switch (Kind) {
1814 default: assert(0 && "Unhandled cast kind!");
John McCall2de56d12010-08-25 11:45:40 +00001815 case CK_ConstructorConversion: {
John McCallca0408f2010-08-23 06:44:23 +00001816 ASTOwningVector<Expr*> ConstructorArgs(S);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001817
Douglas Gregorba70ab62010-04-16 22:17:36 +00001818 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
John McCallf312b1e2010-08-26 23:41:50 +00001819 MultiExprArg(&From, 1),
Douglas Gregorba70ab62010-04-16 22:17:36 +00001820 CastLoc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00001821 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001822
1823 ExprResult Result =
1824 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
John McCall7a1fad32010-08-24 07:32:53 +00001825 move_arg(ConstructorArgs),
Chandler Carruth428edaf2010-10-25 08:47:36 +00001826 /*ZeroInit*/ false, CXXConstructExpr::CK_Complete,
1827 SourceRange());
Douglas Gregorba70ab62010-04-16 22:17:36 +00001828 if (Result.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00001829 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001830
Douglas Gregorba70ab62010-04-16 22:17:36 +00001831 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1832 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001833
John McCall2de56d12010-08-25 11:45:40 +00001834 case CK_UserDefinedConversion: {
Douglas Gregorba70ab62010-04-16 22:17:36 +00001835 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001836
Douglas Gregorba70ab62010-04-16 22:17:36 +00001837 // Create an implicit call expr that calls it.
Douglas Gregor83eecbe2011-01-20 01:32:05 +00001838 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00001839 if (Result.isInvalid())
1840 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001841
Douglas Gregorf2ae5262011-01-20 00:18:04 +00001842 return S.MaybeBindToTemporary(Result.get());
Douglas Gregorba70ab62010-04-16 22:17:36 +00001843 }
1844 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001845}
Douglas Gregorba70ab62010-04-16 22:17:36 +00001846
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001847/// PerformImplicitConversion - Perform an implicit conversion of the
1848/// expression From to the type ToType using the pre-computed implicit
1849/// conversion sequence ICS. Returns true if there was an error, false
1850/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001851/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001852/// used in the error message.
1853bool
1854Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1855 const ImplicitConversionSequence &ICS,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001856 AssignmentAction Action, bool CStyle) {
John McCall1d318332010-01-12 00:44:57 +00001857 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001858 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001859 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001860 CStyle))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001861 return true;
1862 break;
1863
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001864 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001865
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001866 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCalldaa8e4e2010-11-15 09:13:47 +00001867 CastKind CastKind;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001868 QualType BeforeToType;
1869 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCall2de56d12010-08-25 11:45:40 +00001870 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001871
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001872 // If the user-defined conversion is specified by a conversion function,
1873 // the initial standard conversion sequence converts the source type to
1874 // the implicit object parameter of the conversion function.
1875 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCall9ec94452010-12-04 09:57:16 +00001876 } else {
1877 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCall2de56d12010-08-25 11:45:40 +00001878 CastKind = CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001879 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001880 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001881 // If the user-defined conversion is specified by a constructor, the
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001882 // initial standard conversion sequence converts the source type to the
1883 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001884 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1885 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001886 }
Douglas Gregora3998bd2010-12-02 21:47:04 +00001887 // Watch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001888 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001889 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001890 ICS.UserDefined.Before, AA_Converting,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001891 CStyle))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001892 return true;
1893 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001894
1895 ExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00001896 = BuildCXXCastArgument(*this,
1897 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00001898 ToType.getNonReferenceType(),
Douglas Gregor83eecbe2011-01-20 01:32:05 +00001899 CastKind, cast<CXXMethodDecl>(FD),
1900 ICS.UserDefined.FoundConversionFunction,
John McCall9ae2f072010-08-23 23:25:46 +00001901 From);
Anders Carlsson0aebc812009-09-09 21:33:21 +00001902
1903 if (CastArg.isInvalid())
1904 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001905
1906 From = CastArg.takeAs<Expr>();
1907
Eli Friedmand8889622009-11-27 04:41:50 +00001908 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001909 AA_Converting, CStyle);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001910 }
John McCall1d318332010-01-12 00:44:57 +00001911
1912 case ImplicitConversionSequence::AmbiguousConversion:
John McCall120d63c2010-08-24 20:38:10 +00001913 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall1d318332010-01-12 00:44:57 +00001914 PDiag(diag::err_typecheck_ambiguous_condition)
1915 << From->getSourceRange());
1916 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001917
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001918 case ImplicitConversionSequence::EllipsisConversion:
1919 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001920 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001921
1922 case ImplicitConversionSequence::BadConversion:
1923 return true;
1924 }
1925
1926 // Everything went well.
1927 return false;
1928}
1929
1930/// PerformImplicitConversion - Perform an implicit conversion of the
1931/// expression From to the type ToType by following the standard
1932/// conversion sequence SCS. Returns true if there was an error, false
1933/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001934/// expression. Flavor is the context in which we're performing this
1935/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001936bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001937Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001938 const StandardConversionSequence& SCS,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001939 AssignmentAction Action, bool CStyle) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001940 // Overall FIXME: we are recomputing too many types here and doing far too
1941 // much extra work. What this means is that we need to keep track of more
1942 // information that is computed when we try the implicit conversion initially,
1943 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001944 QualType FromType = From->getType();
1945
Douglas Gregor225c41e2008-11-03 19:09:14 +00001946 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001947 // FIXME: When can ToType be a reference type?
1948 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001949 if (SCS.Second == ICK_Derived_To_Base) {
John McCallca0408f2010-08-23 06:44:23 +00001950 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001951 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCallca0408f2010-08-23 06:44:23 +00001952 MultiExprArg(*this, &From, 1),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001953 /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001954 ConstructorArgs))
1955 return true;
John McCall60d7b3a2010-08-24 06:29:42 +00001956 ExprResult FromResult =
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001957 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1958 ToType, SCS.CopyConstructor,
John McCall7a1fad32010-08-24 07:32:53 +00001959 move_arg(ConstructorArgs),
1960 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00001961 CXXConstructExpr::CK_Complete,
1962 SourceRange());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001963 if (FromResult.isInvalid())
1964 return true;
1965 From = FromResult.takeAs<Expr>();
1966 return false;
1967 }
John McCall60d7b3a2010-08-24 06:29:42 +00001968 ExprResult FromResult =
Mike Stump1eb44332009-09-09 15:08:12 +00001969 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1970 ToType, SCS.CopyConstructor,
John McCall7a1fad32010-08-24 07:32:53 +00001971 MultiExprArg(*this, &From, 1),
1972 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00001973 CXXConstructExpr::CK_Complete,
1974 SourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +00001975
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001976 if (FromResult.isInvalid())
1977 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001978
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001979 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001980 return false;
1981 }
1982
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001983 // Resolve overloaded function references.
1984 if (Context.hasSameType(FromType, Context.OverloadTy)) {
1985 DeclAccessPair Found;
1986 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1987 true, Found);
1988 if (!Fn)
1989 return true;
1990
1991 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1992 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001993
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001994 From = FixOverloadedFunctionReference(From, Found, Fn);
1995 FromType = From->getType();
1996 }
1997
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001998 // Perform the first implicit conversion.
1999 switch (SCS.First) {
2000 case ICK_Identity:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002001 // Nothing to do.
2002 break;
2003
John McCallf6a16482010-12-04 03:47:34 +00002004 case ICK_Lvalue_To_Rvalue:
2005 // Should this get its own ICK?
2006 if (From->getObjectKind() == OK_ObjCProperty) {
2007 ConvertPropertyForRValue(From);
John McCall241d5582010-12-07 22:54:16 +00002008 if (!From->isGLValue()) break;
John McCallf6a16482010-12-04 03:47:34 +00002009 }
2010
Chandler Carruth35001ca2011-02-17 21:10:52 +00002011 // Check for trivial buffer overflows.
2012 if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(From))
2013 CheckArrayAccess(AE);
2014
John McCallf6a16482010-12-04 03:47:34 +00002015 FromType = FromType.getUnqualifiedType();
2016 From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
2017 From, 0, VK_RValue);
2018 break;
2019
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002020 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002021 FromType = Context.getArrayDecayedType(FromType);
John McCall2de56d12010-08-25 11:45:40 +00002022 ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002023 break;
2024
2025 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002026 FromType = Context.getPointerType(FromType);
John McCall2de56d12010-08-25 11:45:40 +00002027 ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002028 break;
2029
2030 default:
2031 assert(false && "Improper first standard conversion");
2032 break;
2033 }
2034
2035 // Perform the second implicit conversion
2036 switch (SCS.Second) {
2037 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002038 // If both sides are functions (or pointers/references to them), there could
2039 // be incompatible exception declarations.
2040 if (CheckExceptionSpecCompatibility(From, ToType))
2041 return true;
2042 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002043 break;
2044
Douglas Gregor43c79c22009-12-09 00:47:37 +00002045 case ICK_NoReturn_Adjustment:
2046 // If both sides are functions (or pointers/references to them), there could
2047 // be incompatible exception declarations.
2048 if (CheckExceptionSpecCompatibility(From, ToType))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002049 return true;
2050
John McCalle6a365d2010-12-19 02:44:49 +00002051 ImpCastExprToType(From, ToType, CK_NoOp);
Douglas Gregor43c79c22009-12-09 00:47:37 +00002052 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002053
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002054 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002055 case ICK_Integral_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00002056 ImpCastExprToType(From, ToType, CK_IntegralCast);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002057 break;
2058
2059 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002060 case ICK_Floating_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00002061 ImpCastExprToType(From, ToType, CK_FloatingCast);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002062 break;
2063
2064 case ICK_Complex_Promotion:
John McCalldaa8e4e2010-11-15 09:13:47 +00002065 case ICK_Complex_Conversion: {
2066 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2067 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2068 CastKind CK;
2069 if (FromEl->isRealFloatingType()) {
2070 if (ToEl->isRealFloatingType())
2071 CK = CK_FloatingComplexCast;
2072 else
2073 CK = CK_FloatingComplexToIntegralComplex;
2074 } else if (ToEl->isRealFloatingType()) {
2075 CK = CK_IntegralComplexToFloatingComplex;
2076 } else {
2077 CK = CK_IntegralComplexCast;
2078 }
2079 ImpCastExprToType(From, ToType, CK);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002080 break;
John McCalldaa8e4e2010-11-15 09:13:47 +00002081 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00002082
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002083 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00002084 if (ToType->isRealFloatingType())
John McCall2de56d12010-08-25 11:45:40 +00002085 ImpCastExprToType(From, ToType, CK_IntegralToFloating);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002086 else
John McCall2de56d12010-08-25 11:45:40 +00002087 ImpCastExprToType(From, ToType, CK_FloatingToIntegral);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002088 break;
2089
Douglas Gregorf9201e02009-02-11 23:02:49 +00002090 case ICK_Compatible_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00002091 ImpCastExprToType(From, ToType, CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002092 break;
2093
Anders Carlsson61faec12009-09-12 04:46:44 +00002094 case ICK_Pointer_Conversion: {
Douglas Gregora3998bd2010-12-02 21:47:04 +00002095 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor45920e82008-12-19 17:40:08 +00002096 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00002097 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00002098 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00002099 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00002100 << From->getSourceRange();
2101 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002102
John McCalldaa8e4e2010-11-15 09:13:47 +00002103 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002104 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002105 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002106 return true;
John McCall5baba9d2010-08-25 10:28:54 +00002107 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002108 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00002109 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002110
Anders Carlsson61faec12009-09-12 04:46:44 +00002111 case ICK_Pointer_Member: {
John McCalldaa8e4e2010-11-15 09:13:47 +00002112 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002113 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002114 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
Anders Carlsson61faec12009-09-12 04:46:44 +00002115 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002116 if (CheckExceptionSpecCompatibility(From, ToType))
2117 return true;
John McCall5baba9d2010-08-25 10:28:54 +00002118 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
Anders Carlsson61faec12009-09-12 04:46:44 +00002119 break;
2120 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00002121 case ICK_Boolean_Conversion: {
John McCalldaa8e4e2010-11-15 09:13:47 +00002122 CastKind Kind = CK_Invalid;
2123 switch (FromType->getScalarTypeKind()) {
2124 case Type::STK_Pointer: Kind = CK_PointerToBoolean; break;
2125 case Type::STK_MemberPointer: Kind = CK_MemberPointerToBoolean; break;
2126 case Type::STK_Bool: llvm_unreachable("bool -> bool conversion?");
2127 case Type::STK_Integral: Kind = CK_IntegralToBoolean; break;
2128 case Type::STK_Floating: Kind = CK_FloatingToBoolean; break;
2129 case Type::STK_IntegralComplex: Kind = CK_IntegralComplexToBoolean; break;
2130 case Type::STK_FloatingComplex: Kind = CK_FloatingComplexToBoolean; break;
2131 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002132
Anders Carlssonbc0e0782009-11-23 20:04:44 +00002133 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002134 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00002135 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002136
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002137 case ICK_Derived_To_Base: {
John McCallf871d0c2010-08-07 06:22:56 +00002138 CXXCastPath BasePath;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002139 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002140 ToType.getNonReferenceType(),
2141 From->getLocStart(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002142 From->getSourceRange(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002143 &BasePath,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002144 CStyle))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002145 return true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002146
Sebastian Redl906082e2010-07-20 04:20:21 +00002147 ImpCastExprToType(From, ToType.getNonReferenceType(),
John McCall2de56d12010-08-25 11:45:40 +00002148 CK_DerivedToBase, CastCategory(From),
John McCallf871d0c2010-08-07 06:22:56 +00002149 &BasePath);
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002150 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002151 }
2152
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002153 case ICK_Vector_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00002154 ImpCastExprToType(From, ToType, CK_BitCast);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002155 break;
2156
2157 case ICK_Vector_Splat:
John McCall2de56d12010-08-25 11:45:40 +00002158 ImpCastExprToType(From, ToType, CK_VectorSplat);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002159 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002160
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002161 case ICK_Complex_Real:
John McCalldaa8e4e2010-11-15 09:13:47 +00002162 // Case 1. x -> _Complex y
2163 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2164 QualType ElType = ToComplex->getElementType();
2165 bool isFloatingComplex = ElType->isRealFloatingType();
2166
2167 // x -> y
2168 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2169 // do nothing
2170 } else if (From->getType()->isRealFloatingType()) {
2171 ImpCastExprToType(From, ElType,
2172 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral);
2173 } else {
2174 assert(From->getType()->isIntegerType());
2175 ImpCastExprToType(From, ElType,
2176 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast);
2177 }
2178 // y -> _Complex y
2179 ImpCastExprToType(From, ToType,
2180 isFloatingComplex ? CK_FloatingRealToComplex
2181 : CK_IntegralRealToComplex);
2182
2183 // Case 2. _Complex x -> y
2184 } else {
2185 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2186 assert(FromComplex);
2187
2188 QualType ElType = FromComplex->getElementType();
2189 bool isFloatingComplex = ElType->isRealFloatingType();
2190
2191 // _Complex x -> x
2192 ImpCastExprToType(From, ElType,
2193 isFloatingComplex ? CK_FloatingComplexToReal
2194 : CK_IntegralComplexToReal);
2195
2196 // x -> y
2197 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2198 // do nothing
2199 } else if (ToType->isRealFloatingType()) {
2200 ImpCastExprToType(From, ToType,
2201 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating);
2202 } else {
2203 assert(ToType->isIntegerType());
2204 ImpCastExprToType(From, ToType,
2205 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast);
2206 }
2207 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002208 break;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002209
2210 case ICK_Block_Pointer_Conversion: {
2211 ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast, VK_RValue);
2212 break;
2213 }
2214
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002215 case ICK_Lvalue_To_Rvalue:
2216 case ICK_Array_To_Pointer:
2217 case ICK_Function_To_Pointer:
2218 case ICK_Qualification:
2219 case ICK_Num_Conversion_Kinds:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002220 assert(false && "Improper second standard conversion");
2221 break;
2222 }
2223
2224 switch (SCS.Third) {
2225 case ICK_Identity:
2226 // Nothing to do.
2227 break;
2228
Sebastian Redl906082e2010-07-20 04:20:21 +00002229 case ICK_Qualification: {
2230 // The qualification keeps the category of the inner expression, unless the
2231 // target type isn't a reference.
John McCall5baba9d2010-08-25 10:28:54 +00002232 ExprValueKind VK = ToType->isReferenceType() ?
2233 CastCategory(From) : VK_RValue;
Douglas Gregor63982352010-07-13 18:40:04 +00002234 ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
John McCall2de56d12010-08-25 11:45:40 +00002235 CK_NoOp, VK);
Douglas Gregora9bff302010-02-28 18:30:25 +00002236
2237 if (SCS.DeprecatedStringLiteralToCharPtr)
2238 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2239 << ToType.getNonReferenceType();
2240
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002241 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002242 }
2243
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002244 default:
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002245 assert(false && "Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002246 break;
2247 }
2248
2249 return false;
2250}
2251
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002252ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002253 SourceLocation KWLoc,
2254 ParsedType Ty,
2255 SourceLocation RParen) {
2256 TypeSourceInfo *TSInfo;
2257 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002258
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002259 if (!TSInfo)
2260 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002261 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002262}
2263
Sebastian Redlf8aca862010-09-14 23:40:14 +00002264static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT, QualType T,
2265 SourceLocation KeyLoc) {
Douglas Gregora0506182011-01-27 20:35:44 +00002266 // FIXME: For many of these traits, we need a complete type before we can
2267 // check these properties.
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002268 assert(!T->isDependentType() &&
2269 "Cannot evaluate traits for dependent types.");
2270 ASTContext &C = Self.Context;
2271 switch(UTT) {
2272 default: assert(false && "Unknown type trait or not implemented");
2273 case UTT_IsPOD: return T->isPODType();
2274 case UTT_IsLiteral: return T->isLiteralType();
2275 case UTT_IsClass: // Fallthrough
2276 case UTT_IsUnion:
2277 if (const RecordType *Record = T->getAs<RecordType>()) {
2278 bool Union = Record->getDecl()->isUnion();
2279 return UTT == UTT_IsUnion ? Union : !Union;
2280 }
2281 return false;
2282 case UTT_IsEnum: return T->isEnumeralType();
2283 case UTT_IsPolymorphic:
2284 if (const RecordType *Record = T->getAs<RecordType>()) {
2285 // Type traits are only parsed in C++, so we've got CXXRecords.
2286 return cast<CXXRecordDecl>(Record->getDecl())->isPolymorphic();
2287 }
2288 return false;
2289 case UTT_IsAbstract:
2290 if (const RecordType *RT = T->getAs<RecordType>())
2291 return cast<CXXRecordDecl>(RT->getDecl())->isAbstract();
2292 return false;
2293 case UTT_IsEmpty:
2294 if (const RecordType *Record = T->getAs<RecordType>()) {
2295 return !Record->getDecl()->isUnion()
2296 && cast<CXXRecordDecl>(Record->getDecl())->isEmpty();
2297 }
2298 return false;
2299 case UTT_HasTrivialConstructor:
2300 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2301 // If __is_pod (type) is true then the trait is true, else if type is
2302 // a cv class or union type (or array thereof) with a trivial default
2303 // constructor ([class.ctor]) then the trait is true, else it is false.
2304 if (T->isPODType())
2305 return true;
2306 if (const RecordType *RT =
2307 C.getBaseElementType(T)->getAs<RecordType>())
2308 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialConstructor();
2309 return false;
2310 case UTT_HasTrivialCopy:
2311 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2312 // If __is_pod (type) is true or type is a reference type then
2313 // the trait is true, else if type is a cv class or union type
2314 // with a trivial copy constructor ([class.copy]) then the trait
2315 // is true, else it is false.
2316 if (T->isPODType() || T->isReferenceType())
2317 return true;
2318 if (const RecordType *RT = T->getAs<RecordType>())
2319 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2320 return false;
2321 case UTT_HasTrivialAssign:
2322 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2323 // If type is const qualified or is a reference type then the
2324 // trait is false. Otherwise if __is_pod (type) is true then the
2325 // trait is true, else if type is a cv class or union type with
2326 // a trivial copy assignment ([class.copy]) then the trait is
2327 // true, else it is false.
2328 // Note: the const and reference restrictions are interesting,
2329 // given that const and reference members don't prevent a class
2330 // from having a trivial copy assignment operator (but do cause
2331 // errors if the copy assignment operator is actually used, q.v.
2332 // [class.copy]p12).
2333
2334 if (C.getBaseElementType(T).isConstQualified())
2335 return false;
2336 if (T->isPODType())
2337 return true;
2338 if (const RecordType *RT = T->getAs<RecordType>())
2339 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2340 return false;
2341 case UTT_HasTrivialDestructor:
2342 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2343 // If __is_pod (type) is true or type is a reference type
2344 // then the trait is true, else if type is a cv class or union
2345 // type (or array thereof) with a trivial destructor
2346 // ([class.dtor]) then the trait is true, else it is
2347 // false.
2348 if (T->isPODType() || T->isReferenceType())
2349 return true;
2350 if (const RecordType *RT =
2351 C.getBaseElementType(T)->getAs<RecordType>())
2352 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2353 return false;
2354 // TODO: Propagate nothrowness for implicitly declared special members.
2355 case UTT_HasNothrowAssign:
2356 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2357 // If type is const qualified or is a reference type then the
2358 // trait is false. Otherwise if __has_trivial_assign (type)
2359 // is true then the trait is true, else if type is a cv class
2360 // or union type with copy assignment operators that are known
2361 // not to throw an exception then the trait is true, else it is
2362 // false.
2363 if (C.getBaseElementType(T).isConstQualified())
2364 return false;
2365 if (T->isReferenceType())
2366 return false;
2367 if (T->isPODType())
2368 return true;
2369 if (const RecordType *RT = T->getAs<RecordType>()) {
2370 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2371 if (RD->hasTrivialCopyAssignment())
2372 return true;
2373
2374 bool FoundAssign = false;
2375 bool AllNoThrow = true;
2376 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redlf8aca862010-09-14 23:40:14 +00002377 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2378 Sema::LookupOrdinaryName);
2379 if (Self.LookupQualifiedName(Res, RD)) {
2380 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2381 Op != OpEnd; ++Op) {
2382 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2383 if (Operator->isCopyAssignmentOperator()) {
2384 FoundAssign = true;
2385 const FunctionProtoType *CPT
2386 = Operator->getType()->getAs<FunctionProtoType>();
2387 if (!CPT->hasEmptyExceptionSpec()) {
2388 AllNoThrow = false;
2389 break;
2390 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002391 }
2392 }
2393 }
2394
2395 return FoundAssign && AllNoThrow;
2396 }
2397 return false;
2398 case UTT_HasNothrowCopy:
2399 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2400 // If __has_trivial_copy (type) is true then the trait is true, else
2401 // if type is a cv class or union type with copy constructors that are
2402 // known not to throw an exception then the trait is true, else it is
2403 // false.
2404 if (T->isPODType() || T->isReferenceType())
2405 return true;
2406 if (const RecordType *RT = T->getAs<RecordType>()) {
2407 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2408 if (RD->hasTrivialCopyConstructor())
2409 return true;
2410
2411 bool FoundConstructor = false;
2412 bool AllNoThrow = true;
2413 unsigned FoundTQs;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002414 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl5f4e8992010-09-13 21:10:20 +00002415 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002416 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002417 // A template constructor is never a copy constructor.
2418 // FIXME: However, it may actually be selected at the actual overload
2419 // resolution point.
2420 if (isa<FunctionTemplateDecl>(*Con))
2421 continue;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002422 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2423 if (Constructor->isCopyConstructor(FoundTQs)) {
2424 FoundConstructor = true;
2425 const FunctionProtoType *CPT
2426 = Constructor->getType()->getAs<FunctionProtoType>();
Sebastian Redl751025d2010-09-13 22:02:47 +00002427 // TODO: check whether evaluating default arguments can throw.
2428 // For now, we'll be conservative and assume that they can throw.
2429 if (!CPT->hasEmptyExceptionSpec() || CPT->getNumArgs() > 1) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002430 AllNoThrow = false;
2431 break;
2432 }
2433 }
2434 }
2435
2436 return FoundConstructor && AllNoThrow;
2437 }
2438 return false;
2439 case UTT_HasNothrowConstructor:
2440 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2441 // If __has_trivial_constructor (type) is true then the trait is
2442 // true, else if type is a cv class or union type (or array
2443 // thereof) with a default constructor that is known not to
2444 // throw an exception then the trait is true, else it is false.
2445 if (T->isPODType())
2446 return true;
2447 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
2448 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2449 if (RD->hasTrivialConstructor())
2450 return true;
2451
Sebastian Redl751025d2010-09-13 22:02:47 +00002452 DeclContext::lookup_const_iterator Con, ConEnd;
2453 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2454 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002455 // FIXME: In C++0x, a constructor template can be a default constructor.
2456 if (isa<FunctionTemplateDecl>(*Con))
2457 continue;
Sebastian Redl751025d2010-09-13 22:02:47 +00002458 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2459 if (Constructor->isDefaultConstructor()) {
2460 const FunctionProtoType *CPT
2461 = Constructor->getType()->getAs<FunctionProtoType>();
2462 // TODO: check whether evaluating default arguments can throw.
2463 // For now, we'll be conservative and assume that they can throw.
2464 return CPT->hasEmptyExceptionSpec() && CPT->getNumArgs() == 0;
2465 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002466 }
2467 }
2468 return false;
2469 case UTT_HasVirtualDestructor:
2470 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2471 // If type is a class type with a virtual destructor ([class.dtor])
2472 // then the trait is true, else it is false.
2473 if (const RecordType *Record = T->getAs<RecordType>()) {
2474 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redlf8aca862010-09-14 23:40:14 +00002475 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002476 return Destructor->isVirtual();
2477 }
2478 return false;
2479 }
2480}
2481
2482ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002483 SourceLocation KWLoc,
2484 TypeSourceInfo *TSInfo,
2485 SourceLocation RParen) {
2486 QualType T = TSInfo->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002487
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002488 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
2489 // all traits except __is_class, __is_enum and __is_union require a the type
Sebastian Redl607a1782010-09-08 00:48:43 +00002490 // to be complete, an array of unknown bound, or void.
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002491 if (UTT != UTT_IsClass && UTT != UTT_IsEnum && UTT != UTT_IsUnion) {
Sebastian Redl607a1782010-09-08 00:48:43 +00002492 QualType E = T;
2493 if (T->isIncompleteArrayType())
2494 E = Context.getAsArrayType(T)->getElementType();
2495 if (!T->isVoidType() &&
2496 RequireCompleteType(KWLoc, E,
Anders Carlssond497ba72009-08-26 22:59:12 +00002497 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002498 return ExprError();
2499 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00002500
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002501 bool Value = false;
2502 if (!T->isDependentType())
Sebastian Redlf8aca862010-09-14 23:40:14 +00002503 Value = EvaluateUnaryTypeTrait(*this, UTT, T, KWLoc);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002504
2505 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002506 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00002507}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002508
Francois Pichet6ad6f282010-12-07 00:08:36 +00002509ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
2510 SourceLocation KWLoc,
2511 ParsedType LhsTy,
2512 ParsedType RhsTy,
2513 SourceLocation RParen) {
2514 TypeSourceInfo *LhsTSInfo;
2515 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
2516 if (!LhsTSInfo)
2517 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
2518
2519 TypeSourceInfo *RhsTSInfo;
2520 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
2521 if (!RhsTSInfo)
2522 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
2523
2524 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
2525}
2526
2527static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
2528 QualType LhsT, QualType RhsT,
2529 SourceLocation KeyLoc) {
2530 assert((!LhsT->isDependentType() || RhsT->isDependentType()) &&
2531 "Cannot evaluate traits for dependent types.");
2532
2533 switch(BTT) {
John McCalld89d30f2011-01-28 22:02:36 +00002534 case BTT_IsBaseOf: {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002535 // C++0x [meta.rel]p2
John McCalld89d30f2011-01-28 22:02:36 +00002536 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet6ad6f282010-12-07 00:08:36 +00002537 // Base and Derived are not unions and name the same class type without
2538 // regard to cv-qualifiers.
Francois Pichet6ad6f282010-12-07 00:08:36 +00002539
John McCalld89d30f2011-01-28 22:02:36 +00002540 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
2541 if (!lhsRecord) return false;
2542
2543 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
2544 if (!rhsRecord) return false;
2545
2546 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
2547 == (lhsRecord == rhsRecord));
2548
2549 if (lhsRecord == rhsRecord)
2550 return !lhsRecord->getDecl()->isUnion();
2551
2552 // C++0x [meta.rel]p2:
2553 // If Base and Derived are class types and are different types
2554 // (ignoring possible cv-qualifiers) then Derived shall be a
2555 // complete type.
2556 if (Self.RequireCompleteType(KeyLoc, RhsT,
2557 diag::err_incomplete_type_used_in_type_trait_expr))
2558 return false;
2559
2560 return cast<CXXRecordDecl>(rhsRecord->getDecl())
2561 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
2562 }
2563
Francois Pichetf1872372010-12-08 22:35:30 +00002564 case BTT_TypeCompatible:
2565 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
2566 RhsT.getUnqualifiedType());
Douglas Gregor9f361132011-01-27 20:28:01 +00002567
2568 case BTT_IsConvertibleTo: {
2569 // C++0x [meta.rel]p4:
2570 // Given the following function prototype:
2571 //
2572 // template <class T>
2573 // typename add_rvalue_reference<T>::type create();
2574 //
2575 // the predicate condition for a template specialization
2576 // is_convertible<From, To> shall be satisfied if and only if
2577 // the return expression in the following code would be
2578 // well-formed, including any implicit conversions to the return
2579 // type of the function:
2580 //
2581 // To test() {
2582 // return create<From>();
2583 // }
2584 //
2585 // Access checking is performed as if in a context unrelated to To and
2586 // From. Only the validity of the immediate context of the expression
2587 // of the return-statement (including conversions to the return type)
2588 // is considered.
2589 //
2590 // We model the initialization as a copy-initialization of a temporary
2591 // of the appropriate type, which for this expression is identical to the
2592 // return statement (since NRVO doesn't apply).
2593 if (LhsT->isObjectType() || LhsT->isFunctionType())
2594 LhsT = Self.Context.getRValueReferenceType(LhsT);
2595
2596 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorb608b982011-01-28 02:26:04 +00002597 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor9f361132011-01-27 20:28:01 +00002598 Expr::getValueKindForType(LhsT));
2599 Expr *FromPtr = &From;
2600 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
2601 SourceLocation()));
2602
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00002603 // Perform the initialization within a SFINAE trap at translation unit
2604 // scope.
2605 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
2606 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Douglas Gregor9f361132011-01-27 20:28:01 +00002607 InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
2608 if (Init.getKind() == InitializationSequence::FailedSequence)
2609 return false;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00002610
Douglas Gregor9f361132011-01-27 20:28:01 +00002611 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
2612 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
2613 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00002614 }
2615 llvm_unreachable("Unknown type trait or not implemented");
2616}
2617
2618ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
2619 SourceLocation KWLoc,
2620 TypeSourceInfo *LhsTSInfo,
2621 TypeSourceInfo *RhsTSInfo,
2622 SourceLocation RParen) {
2623 QualType LhsT = LhsTSInfo->getType();
2624 QualType RhsT = RhsTSInfo->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002625
John McCalld89d30f2011-01-28 22:02:36 +00002626 if (BTT == BTT_TypeCompatible) {
Francois Pichetf1872372010-12-08 22:35:30 +00002627 if (getLangOptions().CPlusPlus) {
2628 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
2629 << SourceRange(KWLoc, RParen);
2630 return ExprError();
2631 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00002632 }
2633
2634 bool Value = false;
2635 if (!LhsT->isDependentType() && !RhsT->isDependentType())
2636 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
2637
Francois Pichetf1872372010-12-08 22:35:30 +00002638 // Select trait result type.
2639 QualType ResultType;
2640 switch (BTT) {
Francois Pichetf1872372010-12-08 22:35:30 +00002641 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
2642 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
Douglas Gregor9f361132011-01-27 20:28:01 +00002643 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00002644 }
2645
Francois Pichet6ad6f282010-12-07 00:08:36 +00002646 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
2647 RhsTSInfo, Value, RParen,
Francois Pichetf1872372010-12-08 22:35:30 +00002648 ResultType));
Francois Pichet6ad6f282010-12-07 00:08:36 +00002649}
2650
John McCallf89e55a2010-11-18 06:31:45 +00002651QualType Sema::CheckPointerToMemberOperands(Expr *&lex, Expr *&rex,
2652 ExprValueKind &VK,
2653 SourceLocation Loc,
2654 bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002655 const char *OpSpelling = isIndirect ? "->*" : ".*";
2656 // C++ 5.5p2
2657 // The binary operator .* [p3: ->*] binds its second operand, which shall
2658 // be of type "pointer to member of T" (where T is a completely-defined
2659 // class type) [...]
2660 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002661 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00002662 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002663 Diag(Loc, diag::err_bad_memptr_rhs)
2664 << OpSpelling << RType << rex->getSourceRange();
2665 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00002666 }
Douglas Gregore7450f52009-03-24 19:52:54 +00002667
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002668 QualType Class(MemPtr->getClass(), 0);
2669
Douglas Gregor7d520ba2010-10-13 20:41:14 +00002670 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
2671 // member pointer points must be completely-defined. However, there is no
2672 // reason for this semantic distinction, and the rule is not enforced by
2673 // other compilers. Therefore, we do not check this property, as it is
2674 // likely to be considered a defect.
Sebastian Redl59fc2692010-04-10 10:14:54 +00002675
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002676 // C++ 5.5p2
2677 // [...] to its first operand, which shall be of class T or of a class of
2678 // which T is an unambiguous and accessible base class. [p3: a pointer to
2679 // such a class]
2680 QualType LType = lex->getType();
2681 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002682 if (const PointerType *Ptr = LType->getAs<PointerType>())
John McCallf89e55a2010-11-18 06:31:45 +00002683 LType = Ptr->getPointeeType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002684 else {
2685 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00002686 << OpSpelling << 1 << LType
Douglas Gregor849b2432010-03-31 17:46:05 +00002687 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002688 return QualType();
2689 }
2690 }
2691
Douglas Gregora4923eb2009-11-16 21:35:15 +00002692 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00002693 // If we want to check the hierarchy, we need a complete type.
2694 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
2695 << OpSpelling << (int)isIndirect)) {
2696 return QualType();
2697 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002698 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002699 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00002700 // FIXME: Would it be useful to print full ambiguity paths, or is that
2701 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002702 if (!IsDerivedFrom(LType, Class, Paths) ||
2703 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
2704 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00002705 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002706 return QualType();
2707 }
Eli Friedman3005efe2010-01-16 00:00:48 +00002708 // Cast LHS to type of use.
2709 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
John McCall5baba9d2010-08-25 10:28:54 +00002710 ExprValueKind VK =
2711 isIndirect ? VK_RValue : CastCategory(lex);
Sebastian Redl906082e2010-07-20 04:20:21 +00002712
John McCallf871d0c2010-08-07 06:22:56 +00002713 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002714 BuildBasePathArray(Paths, BasePath);
John McCall5baba9d2010-08-25 10:28:54 +00002715 ImpCastExprToType(lex, UseType, CK_DerivedToBase, VK, &BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002716 }
2717
Douglas Gregored8abf12010-07-08 06:14:04 +00002718 if (isa<CXXScalarValueInitExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00002719 // Diagnose use of pointer-to-member type which when used as
2720 // the functional cast in a pointer-to-member expression.
2721 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
2722 return QualType();
2723 }
John McCallf89e55a2010-11-18 06:31:45 +00002724
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002725 // C++ 5.5p2
2726 // The result is an object or a function of the type specified by the
2727 // second operand.
2728 // The cv qualifiers are the union of those in the pointer and the left side,
2729 // in accordance with 5.5p5 and 5.2.5.
2730 // FIXME: This returns a dereferenced member function pointer as a normal
2731 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00002732 // calling them. There's also a GCC extension to get a function pointer to the
2733 // thing, which is another complication, because this type - unlike the type
2734 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002735 // argument.
2736 // We probably need a "MemberFunctionClosureType" or something like that.
2737 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00002738 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
John McCallf89e55a2010-11-18 06:31:45 +00002739
Douglas Gregor6b4df912011-01-26 16:40:18 +00002740 // C++0x [expr.mptr.oper]p6:
2741 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002742 // ill-formed if the second operand is a pointer to member function with
2743 // ref-qualifier &. In a ->* expression or in a .* expression whose object
2744 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor6b4df912011-01-26 16:40:18 +00002745 // is a pointer to member function with ref-qualifier &&.
2746 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
2747 switch (Proto->getRefQualifier()) {
2748 case RQ_None:
2749 // Do nothing
2750 break;
2751
2752 case RQ_LValue:
2753 if (!isIndirect && !lex->Classify(Context).isLValue())
2754 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
2755 << RType << 1 << lex->getSourceRange();
2756 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002757
Douglas Gregor6b4df912011-01-26 16:40:18 +00002758 case RQ_RValue:
2759 if (isIndirect || !lex->Classify(Context).isRValue())
2760 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
2761 << RType << 0 << lex->getSourceRange();
2762 break;
2763 }
2764 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002765
John McCallf89e55a2010-11-18 06:31:45 +00002766 // C++ [expr.mptr.oper]p6:
2767 // The result of a .* expression whose second operand is a pointer
2768 // to a data member is of the same value category as its
2769 // first operand. The result of a .* expression whose second
2770 // operand is a pointer to a member function is a prvalue. The
2771 // result of an ->* expression is an lvalue if its second operand
2772 // is a pointer to data member and a prvalue otherwise.
2773 if (Result->isFunctionType())
2774 VK = VK_RValue;
2775 else if (isIndirect)
2776 VK = VK_LValue;
2777 else
2778 VK = lex->getValueKind();
2779
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002780 return Result;
2781}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002782
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002783/// \brief Try to convert a type to another according to C++0x 5.16p3.
2784///
2785/// This is part of the parameter validation for the ? operator. If either
2786/// value operand is a class type, the two operands are attempted to be
2787/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002788/// It returns true if the program is ill-formed and has already been diagnosed
2789/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002790static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
2791 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00002792 bool &HaveConversion,
2793 QualType &ToType) {
2794 HaveConversion = false;
2795 ToType = To->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002796
2797 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00002798 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002799 // C++0x 5.16p3
2800 // The process for determining whether an operand expression E1 of type T1
2801 // can be converted to match an operand expression E2 of type T2 is defined
2802 // as follows:
2803 // -- If E2 is an lvalue:
John McCall7eb0a9e2010-11-24 05:12:34 +00002804 bool ToIsLvalue = To->isLValue();
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002805 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002806 // E1 can be converted to match E2 if E1 can be implicitly converted to
2807 // type "lvalue reference to T2", subject to the constraint that in the
2808 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002809 QualType T = Self.Context.getLValueReferenceType(ToType);
2810 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002811
Douglas Gregorb70cf442010-03-26 20:14:36 +00002812 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2813 if (InitSeq.isDirectReferenceBinding()) {
2814 ToType = T;
2815 HaveConversion = true;
2816 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002817 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002818
Douglas Gregorb70cf442010-03-26 20:14:36 +00002819 if (InitSeq.isAmbiguous())
2820 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002821 }
John McCallb1bdc622010-02-25 01:37:24 +00002822
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002823 // -- If E2 is an rvalue, or if the conversion above cannot be done:
2824 // -- if E1 and E2 have class type, and the underlying class types are
2825 // the same or one is a base class of the other:
2826 QualType FTy = From->getType();
2827 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002828 const RecordType *FRec = FTy->getAs<RecordType>();
2829 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002830 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00002831 Self.IsDerivedFrom(FTy, TTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002832 if (FRec && TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00002833 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002834 // E1 can be converted to match E2 if the class of T2 is the
2835 // same type as, or a base class of, the class of T1, and
2836 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00002837 if (FRec == TRec || FDerivedFromT) {
2838 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002839 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2840 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2841 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2842 HaveConversion = true;
2843 return false;
2844 }
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);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002848 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002849 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002850
Douglas Gregorb70cf442010-03-26 20:14:36 +00002851 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002852 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002853
Douglas Gregorb70cf442010-03-26 20:14:36 +00002854 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2855 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002856 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002857 // an rvalue).
2858 //
2859 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2860 // to the array-to-pointer or function-to-pointer conversions.
2861 if (!TTy->getAs<TagType>())
2862 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002863
Douglas Gregorb70cf442010-03-26 20:14:36 +00002864 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2865 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002866 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002867 ToType = TTy;
2868 if (InitSeq.isAmbiguous())
2869 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2870
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002871 return false;
2872}
2873
2874/// \brief Try to find a common type for two according to C++0x 5.16p5.
2875///
2876/// This is part of the parameter validation for the ? operator. If either
2877/// value operand is a class type, overload resolution is used to find a
2878/// conversion to a common type.
2879static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
Chandler Carruth82214a82011-02-18 23:54:50 +00002880 SourceLocation QuestionLoc) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002881 Expr *Args[2] = { LHS, RHS };
Chandler Carruth82214a82011-02-18 23:54:50 +00002882 OverloadCandidateSet CandidateSet(QuestionLoc);
2883 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
2884 CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002885
2886 OverloadCandidateSet::iterator Best;
Chandler Carruth82214a82011-02-18 23:54:50 +00002887 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002888 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002889 // We found a match. Perform the conversions on the arguments and move on.
2890 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00002891 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002892 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00002893 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002894 break;
2895 return false;
2896
Douglas Gregor20093b42009-12-09 23:02:17 +00002897 case OR_No_Viable_Function:
Chandler Carruth82214a82011-02-18 23:54:50 +00002898
2899 // Emit a better diagnostic if one of the expressions is a null pointer
2900 // constant and the other is a pointer type. In this case, the user most
2901 // likely forgot to take the address of the other expression.
2902 if (Self.DiagnoseConditionalForNull(LHS, RHS, QuestionLoc))
2903 return true;
2904
2905 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002906 << LHS->getType() << RHS->getType()
2907 << LHS->getSourceRange() << RHS->getSourceRange();
2908 return true;
2909
Douglas Gregor20093b42009-12-09 23:02:17 +00002910 case OR_Ambiguous:
Chandler Carruth82214a82011-02-18 23:54:50 +00002911 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002912 << LHS->getType() << RHS->getType()
2913 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00002914 // FIXME: Print the possible common types by printing the return types of
2915 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002916 break;
2917
Douglas Gregor20093b42009-12-09 23:02:17 +00002918 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002919 assert(false && "Conditional operator has only built-in overloads");
2920 break;
2921 }
2922 return true;
2923}
2924
Sebastian Redl76458502009-04-17 16:30:52 +00002925/// \brief Perform an "extended" implicit conversion as returned by
2926/// TryClassUnification.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002927static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2928 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2929 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2930 SourceLocation());
2931 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
John McCallf312b1e2010-08-26 23:41:50 +00002932 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&E, 1));
Douglas Gregorb70cf442010-03-26 20:14:36 +00002933 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00002934 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002935
Douglas Gregorb70cf442010-03-26 20:14:36 +00002936 E = Result.takeAs<Expr>();
Sebastian Redl76458502009-04-17 16:30:52 +00002937 return false;
2938}
2939
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002940/// \brief Check the operands of ?: under C++ semantics.
2941///
2942/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2943/// extension. In this case, LHS == Cond. (But they're not aliases.)
2944QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
John McCall56ca35d2011-02-17 10:25:35 +00002945 ExprValueKind &VK, ExprObjectKind &OK,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002946 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002947 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2948 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002949
2950 // C++0x 5.16p1
2951 // The first expression is contextually converted to bool.
2952 if (!Cond->isTypeDependent()) {
2953 if (CheckCXXBooleanCondition(Cond))
2954 return QualType();
2955 }
2956
John McCallf89e55a2010-11-18 06:31:45 +00002957 // Assume r-value.
2958 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00002959 OK = OK_Ordinary;
John McCallf89e55a2010-11-18 06:31:45 +00002960
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002961 // Either of the arguments dependent?
2962 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2963 return Context.DependentTy;
2964
2965 // C++0x 5.16p2
2966 // If either the second or the third operand has type (cv) void, ...
2967 QualType LTy = LHS->getType();
2968 QualType RTy = RHS->getType();
2969 bool LVoid = LTy->isVoidType();
2970 bool RVoid = RTy->isVoidType();
2971 if (LVoid || RVoid) {
2972 // ... then the [l2r] conversions are performed on the second and third
2973 // operands ...
Douglas Gregora873dfc2010-02-03 00:27:59 +00002974 DefaultFunctionArrayLvalueConversion(LHS);
2975 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002976 LTy = LHS->getType();
2977 RTy = RHS->getType();
2978
2979 // ... and one of the following shall hold:
2980 // -- The second or the third operand (but not both) is a throw-
2981 // expression; the result is of the type of the other and is an rvalue.
2982 bool LThrow = isa<CXXThrowExpr>(LHS);
2983 bool RThrow = isa<CXXThrowExpr>(RHS);
2984 if (LThrow && !RThrow)
2985 return RTy;
2986 if (RThrow && !LThrow)
2987 return LTy;
2988
2989 // -- Both the second and third operands have type void; the result is of
2990 // type void and is an rvalue.
2991 if (LVoid && RVoid)
2992 return Context.VoidTy;
2993
2994 // Neither holds, error.
2995 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2996 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2997 << LHS->getSourceRange() << RHS->getSourceRange();
2998 return QualType();
2999 }
3000
3001 // Neither is void.
3002
3003 // C++0x 5.16p3
3004 // Otherwise, if the second and third operand have different types, and
3005 // either has (cv) class type, and attempt is made to convert each of those
3006 // operands to the other.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003007 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003008 (LTy->isRecordType() || RTy->isRecordType())) {
3009 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
3010 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003011 QualType L2RType, R2LType;
3012 bool HaveL2R, HaveR2L;
3013 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003014 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00003015 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003016 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003017
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003018 // If both can be converted, [...] the program is ill-formed.
3019 if (HaveL2R && HaveR2L) {
3020 Diag(QuestionLoc, diag::err_conditional_ambiguous)
3021 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
3022 return QualType();
3023 }
3024
3025 // If exactly one conversion is possible, that conversion is applied to
3026 // the chosen operand and the converted operands are used in place of the
3027 // original operands for the remainder of this section.
3028 if (HaveL2R) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003029 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003030 return QualType();
3031 LTy = LHS->getType();
3032 } else if (HaveR2L) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003033 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003034 return QualType();
3035 RTy = RHS->getType();
3036 }
3037 }
3038
3039 // C++0x 5.16p4
John McCallf89e55a2010-11-18 06:31:45 +00003040 // If the second and third operands are glvalues of the same value
3041 // category and have the same type, the result is of that type and
3042 // value category and it is a bit-field if the second or the third
3043 // operand is a bit-field, or if both are bit-fields.
John McCall09431682010-11-18 19:01:18 +00003044 // We only extend this to bitfields, not to the crazy other kinds of
3045 // l-values.
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003046 bool Same = Context.hasSameType(LTy, RTy);
John McCallf89e55a2010-11-18 06:31:45 +00003047 if (Same &&
John McCall56ca35d2011-02-17 10:25:35 +00003048 LHS->isGLValue() &&
John McCallf89e55a2010-11-18 06:31:45 +00003049 LHS->getValueKind() == RHS->getValueKind() &&
John McCall56ca35d2011-02-17 10:25:35 +00003050 LHS->isOrdinaryOrBitFieldObject() &&
3051 RHS->isOrdinaryOrBitFieldObject()) {
John McCallf89e55a2010-11-18 06:31:45 +00003052 VK = LHS->getValueKind();
John McCall09431682010-11-18 19:01:18 +00003053 if (LHS->getObjectKind() == OK_BitField ||
3054 RHS->getObjectKind() == OK_BitField)
3055 OK = OK_BitField;
John McCallf89e55a2010-11-18 06:31:45 +00003056 return LTy;
Fariborz Jahanian3911a1a2010-09-25 01:08:05 +00003057 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003058
3059 // C++0x 5.16p5
3060 // Otherwise, the result is an rvalue. If the second and third operands
3061 // do not have the same type, and either has (cv) class type, ...
3062 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
3063 // ... overload resolution is used to determine the conversions (if any)
3064 // to be applied to the operands. If the overload resolution fails, the
3065 // program is ill-formed.
3066 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
3067 return QualType();
3068 }
3069
3070 // C++0x 5.16p6
3071 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
3072 // conversions are performed on the second and third operands.
Douglas Gregora873dfc2010-02-03 00:27:59 +00003073 DefaultFunctionArrayLvalueConversion(LHS);
3074 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003075 LTy = LHS->getType();
3076 RTy = RHS->getType();
3077
3078 // After those conversions, one of the following shall hold:
3079 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00003080 // is of that type. If the operands have class type, the result
3081 // is a prvalue temporary of the result type, which is
3082 // copy-initialized from either the second operand or the third
3083 // operand depending on the value of the first operand.
3084 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
3085 if (LTy->isRecordType()) {
3086 // The operands have class type. Make a temporary copy.
3087 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003088 ExprResult LHSCopy = PerformCopyInitialization(Entity,
3089 SourceLocation(),
John McCallf6a16482010-12-04 03:47:34 +00003090 Owned(LHS));
Douglas Gregorb65a4582010-05-19 23:40:50 +00003091 if (LHSCopy.isInvalid())
3092 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003093
3094 ExprResult RHSCopy = PerformCopyInitialization(Entity,
3095 SourceLocation(),
John McCallf6a16482010-12-04 03:47:34 +00003096 Owned(RHS));
Douglas Gregorb65a4582010-05-19 23:40:50 +00003097 if (RHSCopy.isInvalid())
3098 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003099
Douglas Gregorb65a4582010-05-19 23:40:50 +00003100 LHS = LHSCopy.takeAs<Expr>();
3101 RHS = RHSCopy.takeAs<Expr>();
3102 }
3103
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003104 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00003105 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003106
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003107 // Extension: conditional operator involving vector types.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003108 if (LTy->isVectorType() || RTy->isVectorType())
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003109 return CheckVectorOperands(QuestionLoc, LHS, RHS);
3110
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003111 // -- The second and third operands have arithmetic or enumeration type;
3112 // the usual arithmetic conversions are performed to bring them to a
3113 // common type, and the result is of that type.
3114 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
3115 UsualArithmeticConversions(LHS, RHS);
3116 return LHS->getType();
3117 }
3118
3119 // -- The second and third operands have pointer type, or one has pointer
3120 // type and the other is a null pointer constant; pointer conversions
3121 // and qualification conversions are performed to bring them to their
3122 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00003123 // -- The second and third operands have pointer to member type, or one has
3124 // pointer to member type and the other is a null pointer constant;
3125 // pointer to member conversions and qualification conversions are
3126 // performed to bring them to a common type, whose cv-qualification
3127 // shall match the cv-qualification of either the second or the third
3128 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003129 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003130 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003131 isSFINAEContext()? 0 : &NonStandardCompositeType);
3132 if (!Composite.isNull()) {
3133 if (NonStandardCompositeType)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003134 Diag(QuestionLoc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003135 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
3136 << LTy << RTy << Composite
3137 << LHS->getSourceRange() << RHS->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003138
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003139 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003140 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003141
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003142 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00003143 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
3144 if (!Composite.isNull())
3145 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003146
Chandler Carruth7ef93242011-02-19 00:13:59 +00003147 // Check if we are using a null with a non-pointer type.
3148 if (DiagnoseConditionalForNull(LHS, RHS, QuestionLoc))
3149 return QualType();
3150
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003151 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3152 << LHS->getType() << RHS->getType()
3153 << LHS->getSourceRange() << RHS->getSourceRange();
3154 return QualType();
3155}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003156
3157/// \brief Find a merged pointer type and convert the two expressions to it.
3158///
Douglas Gregor20b3e992009-08-24 17:42:35 +00003159/// This finds the composite pointer type (or member pointer type) for @p E1
3160/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
3161/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003162/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003163///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003164/// \param Loc The location of the operator requiring these two expressions to
3165/// be converted to the composite pointer type.
3166///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003167/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
3168/// a non-standard (but still sane) composite type to which both expressions
3169/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
3170/// will be set true.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003171QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003172 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003173 bool *NonStandardCompositeType) {
3174 if (NonStandardCompositeType)
3175 *NonStandardCompositeType = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003176
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003177 assert(getLangOptions().CPlusPlus && "This function assumes C++");
3178 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003179
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00003180 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
3181 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00003182 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003183
3184 // C++0x 5.9p2
3185 // Pointer conversions and qualification conversions are performed on
3186 // pointer operands to bring them to their composite pointer type. If
3187 // one operand is a null pointer constant, the composite pointer type is
3188 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00003189 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003190 if (T2->isMemberPointerType())
John McCall2de56d12010-08-25 11:45:40 +00003191 ImpCastExprToType(E1, T2, CK_NullToMemberPointer);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003192 else
John McCall404cd162010-11-13 01:35:44 +00003193 ImpCastExprToType(E1, T2, CK_NullToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003194 return T2;
3195 }
Douglas Gregorce940492009-09-25 04:25:58 +00003196 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003197 if (T1->isMemberPointerType())
John McCall2de56d12010-08-25 11:45:40 +00003198 ImpCastExprToType(E2, T1, CK_NullToMemberPointer);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003199 else
John McCall404cd162010-11-13 01:35:44 +00003200 ImpCastExprToType(E2, T1, CK_NullToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003201 return T1;
3202 }
Mike Stump1eb44332009-09-09 15:08:12 +00003203
Douglas Gregor20b3e992009-08-24 17:42:35 +00003204 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003205 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
3206 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003207 return QualType();
3208
3209 // Otherwise, of one of the operands has type "pointer to cv1 void," then
3210 // the other has type "pointer to cv2 T" and the composite pointer type is
3211 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
3212 // Otherwise, the composite pointer type is a pointer type similar to the
3213 // type of one of the operands, with a cv-qualification signature that is
3214 // the union of the cv-qualification signatures of the operand types.
3215 // In practice, the first part here is redundant; it's subsumed by the second.
3216 // What we do here is, we build the two possible composite types, and try the
3217 // conversions in both directions. If only one works, or if the two composite
3218 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00003219 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00003220 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
3221 QualifierVector QualifierUnion;
3222 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
3223 ContainingClassVector;
3224 ContainingClassVector MemberOfClass;
3225 QualType Composite1 = Context.getCanonicalType(T1),
3226 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003227 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00003228 do {
3229 const PointerType *Ptr1, *Ptr2;
3230 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3231 (Ptr2 = Composite2->getAs<PointerType>())) {
3232 Composite1 = Ptr1->getPointeeType();
3233 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003234
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003235 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003236 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003237 if (NonStandardCompositeType &&
3238 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3239 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003240
Douglas Gregor20b3e992009-08-24 17:42:35 +00003241 QualifierUnion.push_back(
3242 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3243 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3244 continue;
3245 }
Mike Stump1eb44332009-09-09 15:08:12 +00003246
Douglas Gregor20b3e992009-08-24 17:42:35 +00003247 const MemberPointerType *MemPtr1, *MemPtr2;
3248 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3249 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3250 Composite1 = MemPtr1->getPointeeType();
3251 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003252
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003253 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003254 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003255 if (NonStandardCompositeType &&
3256 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3257 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003258
Douglas Gregor20b3e992009-08-24 17:42:35 +00003259 QualifierUnion.push_back(
3260 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3261 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
3262 MemPtr2->getClass()));
3263 continue;
3264 }
Mike Stump1eb44332009-09-09 15:08:12 +00003265
Douglas Gregor20b3e992009-08-24 17:42:35 +00003266 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00003267
Douglas Gregor20b3e992009-08-24 17:42:35 +00003268 // Cannot unwrap any more types.
3269 break;
3270 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00003271
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003272 if (NeedConstBefore && NonStandardCompositeType) {
3273 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003274 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003275 // requirements of C++ [conv.qual]p4 bullet 3.
3276 for (unsigned I = 0; I != NeedConstBefore; ++I) {
3277 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
3278 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
3279 *NonStandardCompositeType = true;
3280 }
3281 }
3282 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003283
Douglas Gregor20b3e992009-08-24 17:42:35 +00003284 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003285 ContainingClassVector::reverse_iterator MOC
3286 = MemberOfClass.rbegin();
3287 for (QualifierVector::reverse_iterator
3288 I = QualifierUnion.rbegin(),
3289 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00003290 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00003291 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00003292 if (MOC->first && MOC->second) {
3293 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00003294 Composite1 = Context.getMemberPointerType(
3295 Context.getQualifiedType(Composite1, Quals),
3296 MOC->first);
3297 Composite2 = Context.getMemberPointerType(
3298 Context.getQualifiedType(Composite2, Quals),
3299 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00003300 } else {
3301 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00003302 Composite1
3303 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
3304 Composite2
3305 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00003306 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003307 }
3308
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003309 // Try to convert to the first composite pointer type.
3310 InitializedEntity Entity1
3311 = InitializedEntity::InitializeTemporary(Composite1);
3312 InitializationKind Kind
3313 = InitializationKind::CreateCopy(Loc, SourceLocation());
3314 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
3315 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00003316
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003317 if (E1ToC1 && E2ToC1) {
3318 // Conversion to Composite1 is viable.
3319 if (!Context.hasSameType(Composite1, Composite2)) {
3320 // Composite2 is a different type from Composite1. Check whether
3321 // Composite2 is also viable.
3322 InitializedEntity Entity2
3323 = InitializedEntity::InitializeTemporary(Composite2);
3324 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3325 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3326 if (E1ToC2 && E2ToC2) {
3327 // Both Composite1 and Composite2 are viable and are different;
3328 // this is an ambiguity.
3329 return QualType();
3330 }
3331 }
3332
3333 // Convert E1 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00003334 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00003335 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003336 if (E1Result.isInvalid())
3337 return QualType();
3338 E1 = E1Result.takeAs<Expr>();
3339
3340 // Convert E2 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00003341 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00003342 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003343 if (E2Result.isInvalid())
3344 return QualType();
3345 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003346
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003347 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003348 }
3349
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003350 // Check whether Composite2 is 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 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003357
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003358 // Convert E1 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00003359 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00003360 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003361 if (E1Result.isInvalid())
3362 return QualType();
3363 E1 = E1Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003364
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003365 // Convert E2 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00003366 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00003367 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003368 if (E2Result.isInvalid())
3369 return QualType();
3370 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003371
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003372 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003373}
Anders Carlsson165a0a02009-05-17 18:41:29 +00003374
John McCall60d7b3a2010-08-24 06:29:42 +00003375ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor19cc1c72010-11-01 21:10:29 +00003376 if (!E)
3377 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003378
Anders Carlsson089c2602009-08-15 23:41:35 +00003379 if (!Context.getLangOptions().CPlusPlus)
3380 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003381
Douglas Gregor51326552009-12-24 18:51:59 +00003382 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
3383
Ted Kremenek6217b802009-07-29 21:53:49 +00003384 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00003385 if (!RT)
3386 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003387
Douglas Gregor5e6fcd42011-02-08 02:14:35 +00003388 // If the result is a glvalue, we shouldn't bind it.
3389 if (E->Classify(Context).isGLValue())
3390 return Owned(E);
John McCall86ff3082010-02-04 22:26:26 +00003391
3392 // That should be enough to guarantee that this type is complete.
3393 // If it has a trivial destructor, we can avoid the extra copy.
Jeffrey Yasskinb7ee2e52011-01-27 19:17:54 +00003394 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall507384f2010-08-12 02:40:37 +00003395 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall86ff3082010-02-04 22:26:26 +00003396 return Owned(E);
3397
Douglas Gregordb89f282010-07-01 22:47:18 +00003398 CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD));
Anders Carlsson860306e2009-05-30 21:21:49 +00003399 ExprTemporaries.push_back(Temp);
Douglas Gregordb89f282010-07-01 22:47:18 +00003400 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003401 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00003402 CheckDestructorAccess(E->getExprLoc(), Destructor,
3403 PDiag(diag::err_access_dtor_temp)
3404 << E->getType());
3405 }
Anders Carlssondef11992009-05-30 20:36:53 +00003406 // FIXME: Add the temporary to the temporaries vector.
3407 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
3408}
3409
John McCall4765fa02010-12-06 08:20:24 +00003410Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003411 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00003412
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00003413 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3414 assert(ExprTemporaries.size() >= FirstTemporary);
3415 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003416 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003417
John McCall4765fa02010-12-06 08:20:24 +00003418 Expr *E = ExprWithCleanups::Create(Context, SubExpr,
3419 &ExprTemporaries[FirstTemporary],
3420 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00003421 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
3422 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00003423
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003424 return E;
3425}
3426
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003427ExprResult
John McCall4765fa02010-12-06 08:20:24 +00003428Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregor90f93822009-12-22 22:17:25 +00003429 if (SubExpr.isInvalid())
3430 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003431
John McCall4765fa02010-12-06 08:20:24 +00003432 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregor90f93822009-12-22 22:17:25 +00003433}
3434
John McCall4765fa02010-12-06 08:20:24 +00003435Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003436 assert(SubStmt && "sub statement can't be null!");
3437
3438 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3439 assert(ExprTemporaries.size() >= FirstTemporary);
3440 if (ExprTemporaries.size() == FirstTemporary)
3441 return SubStmt;
3442
3443 // FIXME: In order to attach the temporaries, wrap the statement into
3444 // a StmtExpr; currently this is only used for asm statements.
3445 // This is hacky, either create a new CXXStmtWithTemporaries statement or
3446 // a new AsmStmtWithTemporaries.
3447 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
3448 SourceLocation(),
3449 SourceLocation());
3450 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
3451 SourceLocation());
John McCall4765fa02010-12-06 08:20:24 +00003452 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003453}
3454
John McCall60d7b3a2010-08-24 06:29:42 +00003455ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003456Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallb3d87482010-08-24 05:47:05 +00003457 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00003458 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003459 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003460 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003461 if (Result.isInvalid()) return ExprError();
3462 Base = Result.get();
Mike Stump1eb44332009-09-09 15:08:12 +00003463
John McCall9ae2f072010-08-23 23:25:46 +00003464 QualType BaseType = Base->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00003465 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003466 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00003467 // If we have a pointer to a dependent type and are using the -> operator,
3468 // the object type is the type that the pointer points to. We might still
3469 // have enough information about that type to do something useful.
3470 if (OpKind == tok::arrow)
3471 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3472 BaseType = Ptr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003473
John McCallb3d87482010-08-24 05:47:05 +00003474 ObjectType = ParsedType::make(BaseType);
Douglas Gregord4dca082010-02-24 18:44:31 +00003475 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00003476 return Owned(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003477 }
Mike Stump1eb44332009-09-09 15:08:12 +00003478
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003479 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00003480 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003481 // returned, with the original second operand.
3482 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00003483 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00003484 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00003485 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00003486 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003487
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003488 while (BaseType->isRecordType()) {
John McCall9ae2f072010-08-23 23:25:46 +00003489 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
3490 if (Result.isInvalid())
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003491 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00003492 Base = Result.get();
3493 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonde699e52009-10-13 22:55:59 +00003494 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCall9ae2f072010-08-23 23:25:46 +00003495 BaseType = Base->getType();
John McCallc4e83212009-09-30 01:01:30 +00003496 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00003497 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00003498 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00003499 for (unsigned i = 0; i < Locations.size(); i++)
3500 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00003501 return ExprError();
3502 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003503 }
Mike Stump1eb44332009-09-09 15:08:12 +00003504
Douglas Gregor31658df2009-11-20 19:58:21 +00003505 if (BaseType->isPointerType())
3506 BaseType = BaseType->getPointeeType();
3507 }
Mike Stump1eb44332009-09-09 15:08:12 +00003508
3509 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003510 // vector types or Objective-C interfaces. Just return early and let
3511 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00003512 if (!BaseType->isRecordType()) {
3513 // C++ [basic.lookup.classref]p2:
3514 // [...] If the type of the object expression is of pointer to scalar
3515 // type, the unqualified-id is looked up in the context of the complete
3516 // postfix-expression.
Douglas Gregord4dca082010-02-24 18:44:31 +00003517 //
3518 // This also indicates that we should be parsing a
3519 // pseudo-destructor-name.
John McCallb3d87482010-08-24 05:47:05 +00003520 ObjectType = ParsedType();
Douglas Gregord4dca082010-02-24 18:44:31 +00003521 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00003522 return Owned(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00003523 }
Mike Stump1eb44332009-09-09 15:08:12 +00003524
Douglas Gregor03c57052009-11-17 05:17:33 +00003525 // The object type must be complete (or dependent).
3526 if (!BaseType->isDependentType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003527 RequireCompleteType(OpLoc, BaseType,
Douglas Gregor03c57052009-11-17 05:17:33 +00003528 PDiag(diag::err_incomplete_member_access)))
3529 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003530
Douglas Gregorc68afe22009-09-03 21:38:09 +00003531 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00003532 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00003533 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00003534 // type C (or of pointer to a class type C), the unqualified-id is looked
3535 // up in the scope of class C. [...]
John McCallb3d87482010-08-24 05:47:05 +00003536 ObjectType = ParsedType::make(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00003537 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003538}
3539
John McCall60d7b3a2010-08-24 06:29:42 +00003540ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003541 Expr *MemExpr) {
Douglas Gregor77549082010-02-24 21:29:12 +00003542 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCall9ae2f072010-08-23 23:25:46 +00003543 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
3544 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregor849b2432010-03-31 17:46:05 +00003545 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003546
Douglas Gregor77549082010-02-24 21:29:12 +00003547 return ActOnCallExpr(/*Scope*/ 0,
John McCall9ae2f072010-08-23 23:25:46 +00003548 MemExpr,
Douglas Gregor77549082010-02-24 21:29:12 +00003549 /*LPLoc*/ ExpectedLParenLoc,
John McCallf312b1e2010-08-26 23:41:50 +00003550 MultiExprArg(),
Douglas Gregor77549082010-02-24 21:29:12 +00003551 /*RPLoc*/ ExpectedLParenLoc);
3552}
Douglas Gregord4dca082010-02-24 18:44:31 +00003553
John McCall60d7b3a2010-08-24 06:29:42 +00003554ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003555 SourceLocation OpLoc,
3556 tok::TokenKind OpKind,
3557 const CXXScopeSpec &SS,
Douglas Gregor26d4ac92010-02-24 23:40:28 +00003558 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003559 SourceLocation CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00003560 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003561 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003562 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003563 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003564
Douglas Gregorb57fb492010-02-24 22:38:50 +00003565 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003566 // The left-hand side of the dot operator shall be of scalar type. The
Douglas Gregorb57fb492010-02-24 22:38:50 +00003567 // left-hand side of the arrow operator shall be of pointer to scalar type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003568 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00003569 QualType ObjectType = Base->getType();
Douglas Gregorb57fb492010-02-24 22:38:50 +00003570 if (OpKind == tok::arrow) {
3571 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3572 ObjectType = Ptr->getPointeeType();
John McCall9ae2f072010-08-23 23:25:46 +00003573 } else if (!Base->isTypeDependent()) {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003574 // The user wrote "p->" when she probably meant "p."; fix it.
3575 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3576 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00003577 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb57fb492010-02-24 22:38:50 +00003578 if (isSFINAEContext())
3579 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003580
Douglas Gregorb57fb492010-02-24 22:38:50 +00003581 OpKind = tok::period;
3582 }
3583 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003584
Douglas Gregorb57fb492010-02-24 22:38:50 +00003585 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
3586 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
John McCall9ae2f072010-08-23 23:25:46 +00003587 << ObjectType << Base->getSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00003588 return ExprError();
3589 }
3590
3591 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003592 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb57fb492010-02-24 22:38:50 +00003593 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003594 if (DestructedTypeInfo) {
3595 QualType DestructedType = DestructedTypeInfo->getType();
3596 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003597 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003598 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
3599 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
3600 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00003601 << ObjectType << DestructedType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003602 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003603
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003604 // Recover by setting the destructed type to the object type.
3605 DestructedType = ObjectType;
3606 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
3607 DestructedTypeStart);
3608 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3609 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00003610 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003611
Douglas Gregorb57fb492010-02-24 22:38:50 +00003612 // C++ [expr.pseudo]p2:
3613 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
3614 // form
3615 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003616 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb57fb492010-02-24 22:38:50 +00003617 //
3618 // shall designate the same scalar type.
3619 if (ScopeTypeInfo) {
3620 QualType ScopeType = ScopeTypeInfo->getType();
3621 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00003622 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003623
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003624 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00003625 diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00003626 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003627 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003628
Douglas Gregorb57fb492010-02-24 22:38:50 +00003629 ScopeType = QualType();
3630 ScopeTypeInfo = 0;
3631 }
3632 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003633
John McCall9ae2f072010-08-23 23:25:46 +00003634 Expr *Result
3635 = new (Context) CXXPseudoDestructorExpr(Context, Base,
3636 OpKind == tok::arrow, OpLoc,
3637 SS.getScopeRep(), SS.getRange(),
3638 ScopeTypeInfo,
3639 CCLoc,
3640 TildeLoc,
3641 Destructed);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003642
Douglas Gregorb57fb492010-02-24 22:38:50 +00003643 if (HasTrailingLParen)
John McCall9ae2f072010-08-23 23:25:46 +00003644 return Owned(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003645
John McCall9ae2f072010-08-23 23:25:46 +00003646 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor77549082010-02-24 21:29:12 +00003647}
3648
John McCall60d7b3a2010-08-24 06:29:42 +00003649ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
Douglas Gregor77549082010-02-24 21:29:12 +00003650 SourceLocation OpLoc,
3651 tok::TokenKind OpKind,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003652 CXXScopeSpec &SS,
Douglas Gregor77549082010-02-24 21:29:12 +00003653 UnqualifiedId &FirstTypeName,
3654 SourceLocation CCLoc,
3655 SourceLocation TildeLoc,
3656 UnqualifiedId &SecondTypeName,
3657 bool HasTrailingLParen) {
3658 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3659 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3660 "Invalid first type name in pseudo-destructor");
3661 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3662 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3663 "Invalid second type name in pseudo-destructor");
3664
Douglas Gregor77549082010-02-24 21:29:12 +00003665 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003666 // The left-hand side of the dot operator shall be of scalar type. The
Douglas Gregor77549082010-02-24 21:29:12 +00003667 // left-hand side of the arrow operator shall be of pointer to scalar type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003668 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00003669 QualType ObjectType = Base->getType();
Douglas Gregor77549082010-02-24 21:29:12 +00003670 if (OpKind == tok::arrow) {
3671 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3672 ObjectType = Ptr->getPointeeType();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003673 } else if (!ObjectType->isDependentType()) {
Douglas Gregor77549082010-02-24 21:29:12 +00003674 // The user wrote "p->" when she probably meant "p."; fix it.
3675 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003676 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00003677 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor77549082010-02-24 21:29:12 +00003678 if (isSFINAEContext())
3679 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003680
Douglas Gregor77549082010-02-24 21:29:12 +00003681 OpKind = tok::period;
3682 }
3683 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003684
3685 // Compute the object type that we should use for name lookup purposes. Only
3686 // record types and dependent types matter.
John McCallb3d87482010-08-24 05:47:05 +00003687 ParsedType ObjectTypePtrForLookup;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003688 if (!SS.isSet()) {
John McCallb3d87482010-08-24 05:47:05 +00003689 if (const Type *T = ObjectType->getAs<RecordType>())
3690 ObjectTypePtrForLookup = ParsedType::make(QualType(T, 0));
3691 else if (ObjectType->isDependentType())
3692 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003693 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003694
3695 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb57fb492010-02-24 22:38:50 +00003696 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00003697 QualType DestructedType;
3698 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003699 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00003700 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003701 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00003702 SecondTypeName.StartLocation,
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +00003703 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003704 if (!T &&
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003705 ((SS.isSet() && !computeDeclContext(SS, false)) ||
3706 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003707 // The name of the type being destroyed is a dependent name, and we
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003708 // couldn't find anything useful in scope. Just store the identifier and
3709 // it's location, and we'll perform (qualified) name lookup again at
3710 // template instantiation time.
3711 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
3712 SecondTypeName.StartLocation);
3713 } else if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003714 Diag(SecondTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00003715 diag::err_pseudo_dtor_destructor_non_type)
3716 << SecondTypeName.Identifier << ObjectType;
3717 if (isSFINAEContext())
3718 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003719
Douglas Gregor77549082010-02-24 21:29:12 +00003720 // Recover by assuming we had the right type all along.
3721 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003722 } else
Douglas Gregor77549082010-02-24 21:29:12 +00003723 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003724 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003725 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00003726 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003727 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3728 TemplateId->getTemplateArgs(),
3729 TemplateId->NumArgs);
John McCall2b5289b2010-08-23 07:28:44 +00003730 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003731 TemplateId->TemplateNameLoc,
3732 TemplateId->LAngleLoc,
3733 TemplateArgsPtr,
3734 TemplateId->RAngleLoc);
3735 if (T.isInvalid() || !T.get()) {
3736 // Recover by assuming we had the right type all along.
3737 DestructedType = ObjectType;
3738 } else
3739 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003740 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003741
3742 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb57fb492010-02-24 22:38:50 +00003743 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003744 if (!DestructedType.isNull()) {
3745 if (!DestructedTypeInfo)
3746 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003747 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003748 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3749 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003750
Douglas Gregorb57fb492010-02-24 22:38:50 +00003751 // Convert the name of the scope type (the type prior to '::') into a type.
3752 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00003753 QualType ScopeType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003754 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor77549082010-02-24 21:29:12 +00003755 FirstTypeName.Identifier) {
3756 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003757 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00003758 FirstTypeName.StartLocation,
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +00003759 S, &SS, false, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00003760 if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003761 Diag(FirstTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00003762 diag::err_pseudo_dtor_destructor_non_type)
3763 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003764
Douglas Gregorb57fb492010-02-24 22:38:50 +00003765 if (isSFINAEContext())
3766 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003767
Douglas Gregorb57fb492010-02-24 22:38:50 +00003768 // Just drop this type. It's unnecessary anyway.
3769 ScopeType = QualType();
3770 } else
3771 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003772 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003773 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00003774 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003775 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3776 TemplateId->getTemplateArgs(),
3777 TemplateId->NumArgs);
John McCall2b5289b2010-08-23 07:28:44 +00003778 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003779 TemplateId->TemplateNameLoc,
3780 TemplateId->LAngleLoc,
3781 TemplateArgsPtr,
3782 TemplateId->RAngleLoc);
3783 if (T.isInvalid() || !T.get()) {
3784 // Recover by dropping this type.
3785 ScopeType = QualType();
3786 } else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003787 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003788 }
3789 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003790
Douglas Gregorb4a418f2010-02-24 23:02:30 +00003791 if (!ScopeType.isNull() && !ScopeTypeInfo)
3792 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
3793 FirstTypeName.StartLocation);
3794
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003795
John McCall9ae2f072010-08-23 23:25:46 +00003796 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00003797 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003798 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00003799}
3800
Douglas Gregorf2ae5262011-01-20 00:18:04 +00003801ExprResult Sema::BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
3802 CXXMethodDecl *Method) {
John McCall6bb80172010-03-30 21:47:33 +00003803 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
3804 FoundDecl, Method))
Douglas Gregorf2ae5262011-01-20 00:18:04 +00003805 return true;
Eli Friedman772fffa2009-12-09 04:53:56 +00003806
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003807 MemberExpr *ME =
Abramo Bagnara25777432010-08-11 22:01:17 +00003808 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
John McCallf89e55a2010-11-18 06:31:45 +00003809 SourceLocation(), Method->getType(),
3810 VK_RValue, OK_Ordinary);
3811 QualType ResultType = Method->getResultType();
3812 ExprValueKind VK = Expr::getValueKindForType(ResultType);
3813 ResultType = ResultType.getNonLValueExprType(Context);
3814
Douglas Gregor7edfb692009-11-23 12:27:39 +00003815 MarkDeclarationReferenced(Exp->getLocStart(), Method);
3816 CXXMemberCallExpr *CE =
John McCallf89e55a2010-11-18 06:31:45 +00003817 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
Douglas Gregor7edfb692009-11-23 12:27:39 +00003818 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003819 return CE;
3820}
3821
Sebastian Redl2e156222010-09-10 20:55:43 +00003822ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
3823 SourceLocation RParen) {
Sebastian Redl2e156222010-09-10 20:55:43 +00003824 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
3825 Operand->CanThrow(Context),
3826 KeyLoc, RParen));
3827}
3828
3829ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
3830 Expr *Operand, SourceLocation RParen) {
3831 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl02bc21a2010-09-10 20:55:37 +00003832}
3833
John McCallf6a16482010-12-04 03:47:34 +00003834/// Perform the conversions required for an expression used in a
3835/// context that ignores the result.
3836void Sema::IgnoredValueConversions(Expr *&E) {
John McCalla878cda2010-12-02 02:07:15 +00003837 // C99 6.3.2.1:
3838 // [Except in specific positions,] an lvalue that does not have
3839 // array type is converted to the value stored in the
3840 // designated object (and is no longer an lvalue).
John McCallf6a16482010-12-04 03:47:34 +00003841 if (E->isRValue()) return;
John McCalla878cda2010-12-02 02:07:15 +00003842
John McCallf6a16482010-12-04 03:47:34 +00003843 // We always want to do this on ObjC property references.
3844 if (E->getObjectKind() == OK_ObjCProperty) {
3845 ConvertPropertyForRValue(E);
3846 if (E->isRValue()) return;
3847 }
3848
3849 // Otherwise, this rule does not apply in C++, at least not for the moment.
3850 if (getLangOptions().CPlusPlus) return;
3851
3852 // GCC seems to also exclude expressions of incomplete enum type.
3853 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
3854 if (!T->getDecl()->isComplete()) {
3855 // FIXME: stupid workaround for a codegen bug!
3856 ImpCastExprToType(E, Context.VoidTy, CK_ToVoid);
3857 return;
3858 }
3859 }
3860
3861 DefaultFunctionArrayLvalueConversion(E);
John McCall85515d62010-12-04 12:29:11 +00003862 if (!E->getType()->isVoidType())
3863 RequireCompleteType(E->getExprLoc(), E->getType(),
3864 diag::err_incomplete_type);
John McCallf6a16482010-12-04 03:47:34 +00003865}
3866
3867ExprResult Sema::ActOnFinishFullExpr(Expr *FullExpr) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003868 if (!FullExpr)
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003869 return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00003870
Douglas Gregord0937222010-12-13 22:49:22 +00003871 if (DiagnoseUnexpandedParameterPack(FullExpr))
3872 return ExprError();
3873
John McCallf6a16482010-12-04 03:47:34 +00003874 IgnoredValueConversions(FullExpr);
John McCallb4eb64d2010-10-08 02:01:28 +00003875 CheckImplicitConversions(FullExpr);
John McCall4765fa02010-12-06 08:20:24 +00003876 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson165a0a02009-05-17 18:41:29 +00003877}
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003878
3879StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
3880 if (!FullStmt) return StmtError();
3881
John McCall4765fa02010-12-06 08:20:24 +00003882 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003883}