blob: f886e17d5469fadc86e65100cb1a40b1defe4124 [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) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000479 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
480 return ExprError();
481 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
482}
483
484/// CheckCXXThrowOperand - Validate the operand of a throw.
485bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
486 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000487 // A throw-expression initializes a temporary object, called the exception
488 // object, the type of which is determined by removing any top-level
489 // cv-qualifiers from the static type of the operand of throw and adjusting
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000490 // the type from "array of T" or "function returning T" to "pointer to T"
Douglas Gregor154fe982009-12-23 22:04:40 +0000491 // or "pointer to function returning T", [...]
492 if (E->getType().hasQualifiers())
John McCall2de56d12010-08-25 11:45:40 +0000493 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
Sebastian Redl906082e2010-07-20 04:20:21 +0000494 CastCategory(E));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000495
Sebastian Redl972041f2009-04-27 20:27:31 +0000496 DefaultFunctionArrayConversion(E);
497
498 // If the type of the exception would be an incomplete type or a pointer
499 // to an incomplete type other than (cv) void the program is ill-formed.
500 QualType Ty = E->getType();
John McCallac418162010-04-22 01:10:34 +0000501 bool isPointer = false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000502 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000503 Ty = Ptr->getPointeeType();
John McCallac418162010-04-22 01:10:34 +0000504 isPointer = true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000505 }
506 if (!isPointer || !Ty->isVoidType()) {
507 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000508 PDiag(isPointer ? diag::err_throw_incomplete_ptr
509 : diag::err_throw_incomplete)
510 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000511 return true;
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000512
Douglas Gregorbf422f92010-04-15 18:05:39 +0000513 if (RequireNonAbstractType(ThrowLoc, E->getType(),
514 PDiag(diag::err_throw_abstract_type)
515 << E->getSourceRange()))
516 return true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000517 }
518
John McCallac418162010-04-22 01:10:34 +0000519 // Initialize the exception result. This implicitly weeds out
520 // abstract types or types with inaccessible copy constructors.
Douglas Gregor72dfa272011-01-21 22:46:35 +0000521 const VarDecl *NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
522
Douglas Gregorf5d8f462011-01-21 18:05:27 +0000523 // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p32.
John McCallac418162010-04-22 01:10:34 +0000524 InitializedEntity Entity =
Douglas Gregor72dfa272011-01-21 22:46:35 +0000525 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
526 /*NRVO=*/false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000527 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
Douglas Gregor72dfa272011-01-21 22:46:35 +0000528 QualType(), E);
John McCallac418162010-04-22 01:10:34 +0000529 if (Res.isInvalid())
530 return true;
531 E = Res.takeAs<Expr>();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000532
Eli Friedman5ed9b932010-06-03 20:39:03 +0000533 // If the exception has class type, we need additional handling.
534 const RecordType *RecordTy = Ty->getAs<RecordType>();
535 if (!RecordTy)
536 return false;
537 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
538
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000539 // If we are throwing a polymorphic class type or pointer thereof,
540 // exception handling will make use of the vtable.
Eli Friedman5ed9b932010-06-03 20:39:03 +0000541 MarkVTableUsed(ThrowLoc, RD);
542
Eli Friedman98efb9f2010-10-12 20:32:36 +0000543 // If a pointer is thrown, the referenced object will not be destroyed.
544 if (isPointer)
545 return false;
546
Eli Friedman5ed9b932010-06-03 20:39:03 +0000547 // If the class has a non-trivial destructor, we must be able to call it.
548 if (RD->hasTrivialDestructor())
549 return false;
550
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000551 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +0000552 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman5ed9b932010-06-03 20:39:03 +0000553 if (!Destructor)
554 return false;
555
556 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
557 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregored8abf12010-07-08 06:14:04 +0000558 PDiag(diag::err_access_dtor_exception) << Ty);
Sebastian Redl972041f2009-04-27 20:27:31 +0000559 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000560}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000561
John McCall5808ce42011-02-03 08:15:49 +0000562CXXMethodDecl *Sema::tryCaptureCXXThis() {
563 // Ignore block scopes: we can capture through them.
564 // Ignore nested enum scopes: we'll diagnose non-constant expressions
565 // where they're invalid, and other uses are legitimate.
566 // Don't ignore nested class scopes: you can't use 'this' in a local class.
John McCall469a1eb2011-02-02 13:00:07 +0000567 DeclContext *DC = CurContext;
John McCall5808ce42011-02-03 08:15:49 +0000568 while (true) {
569 if (isa<BlockDecl>(DC)) DC = cast<BlockDecl>(DC)->getDeclContext();
570 else if (isa<EnumDecl>(DC)) DC = cast<EnumDecl>(DC)->getDeclContext();
571 else break;
572 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000573
John McCall5808ce42011-02-03 08:15:49 +0000574 // If we're not in an instance method, error out.
John McCall469a1eb2011-02-02 13:00:07 +0000575 CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC);
576 if (!method || !method->isInstance())
John McCall5808ce42011-02-03 08:15:49 +0000577 return 0;
John McCall469a1eb2011-02-02 13:00:07 +0000578
579 // Mark that we're closing on 'this' in all the block scopes, if applicable.
580 for (unsigned idx = FunctionScopes.size() - 1;
581 isa<BlockScopeInfo>(FunctionScopes[idx]);
582 --idx)
583 cast<BlockScopeInfo>(FunctionScopes[idx])->CapturesCXXThis = true;
584
John McCall5808ce42011-02-03 08:15:49 +0000585 return method;
586}
587
588ExprResult Sema::ActOnCXXThis(SourceLocation loc) {
589 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
590 /// is a non-lvalue expression whose value is the address of the object for
591 /// which the function is called.
592
593 CXXMethodDecl *method = tryCaptureCXXThis();
594 if (!method) return Diag(loc, diag::err_invalid_this_use);
595
596 return Owned(new (Context) CXXThisExpr(loc, method->getThisType(Context),
John McCall469a1eb2011-02-02 13:00:07 +0000597 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000598}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000599
John McCall60d7b3a2010-08-24 06:29:42 +0000600ExprResult
Douglas Gregorab6677e2010-09-08 00:15:04 +0000601Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000602 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000603 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000604 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000605 if (!TypeRep)
606 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000607
John McCall9d125032010-01-15 18:39:57 +0000608 TypeSourceInfo *TInfo;
609 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
610 if (!TInfo)
611 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregorab6677e2010-09-08 00:15:04 +0000612
613 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
614}
615
616/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
617/// Can be interpreted either as function-style casting ("int(x)")
618/// or class type construction ("ClassType(x,y,z)")
619/// or creation of a value-initialized type ("int()").
620ExprResult
621Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
622 SourceLocation LParenLoc,
623 MultiExprArg exprs,
624 SourceLocation RParenLoc) {
625 QualType Ty = TInfo->getType();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000626 unsigned NumExprs = exprs.size();
627 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000628 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000629 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
630
Sebastian Redlf53597f2009-03-15 17:47:39 +0000631 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000632 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000633 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000634
Douglas Gregorab6677e2010-09-08 00:15:04 +0000635 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000636 LParenLoc,
637 Exprs, NumExprs,
638 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000639 }
640
Anders Carlssonbb60a502009-08-27 03:53:50 +0000641 if (Ty->isArrayType())
642 return ExprError(Diag(TyBeginLoc,
643 diag::err_value_init_for_array_type) << FullRange);
644 if (!Ty->isVoidType() &&
645 RequireCompleteType(TyBeginLoc, Ty,
646 PDiag(diag::err_invalid_incomplete_type_use)
647 << FullRange))
648 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000649
Anders Carlssonbb60a502009-08-27 03:53:50 +0000650 if (RequireNonAbstractType(TyBeginLoc, Ty,
651 diag::err_allocation_of_abstract_type))
652 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000653
654
Douglas Gregor506ae412009-01-16 18:33:17 +0000655 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000656 // If the expression list is a single expression, the type conversion
657 // expression is equivalent (in definedness, and if defined in meaning) to the
658 // corresponding cast expression.
659 //
660 if (NumExprs == 1) {
John McCalldaa8e4e2010-11-15 09:13:47 +0000661 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +0000662 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +0000663 CXXCastPath BasePath;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000664 if (CheckCastTypes(TInfo->getTypeLoc().getSourceRange(), Ty, Exprs[0],
John McCallf89e55a2010-11-18 06:31:45 +0000665 Kind, VK, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000666 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000667 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000668
669 exprs.release();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000670
John McCallf871d0c2010-08-07 06:22:56 +0000671 return Owned(CXXFunctionalCastExpr::Create(Context,
Douglas Gregorab6677e2010-09-08 00:15:04 +0000672 Ty.getNonLValueExprType(Context),
John McCallf89e55a2010-11-18 06:31:45 +0000673 VK, TInfo, TyBeginLoc, Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000674 Exprs[0], &BasePath,
675 RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000676 }
677
Douglas Gregor19311e72010-09-08 21:40:08 +0000678 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
679 InitializationKind Kind
680 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
681 LParenLoc, RParenLoc)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000682 : InitializationKind::CreateValue(TyBeginLoc,
Douglas Gregor19311e72010-09-08 21:40:08 +0000683 LParenLoc, RParenLoc);
684 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
685 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redlf53597f2009-03-15 17:47:39 +0000686
Douglas Gregor19311e72010-09-08 21:40:08 +0000687 // FIXME: Improve AST representation?
688 return move(Result);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000689}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000690
John McCall6ec278d2011-01-27 09:37:56 +0000691/// doesUsualArrayDeleteWantSize - Answers whether the usual
692/// operator delete[] for the given type has a size_t parameter.
693static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
694 QualType allocType) {
695 const RecordType *record =
696 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
697 if (!record) return false;
698
699 // Try to find an operator delete[] in class scope.
700
701 DeclarationName deleteName =
702 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
703 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
704 S.LookupQualifiedName(ops, record->getDecl());
705
706 // We're just doing this for information.
707 ops.suppressDiagnostics();
708
709 // Very likely: there's no operator delete[].
710 if (ops.empty()) return false;
711
712 // If it's ambiguous, it should be illegal to call operator delete[]
713 // on this thing, so it doesn't matter if we allocate extra space or not.
714 if (ops.isAmbiguous()) return false;
715
716 LookupResult::Filter filter = ops.makeFilter();
717 while (filter.hasNext()) {
718 NamedDecl *del = filter.next()->getUnderlyingDecl();
719
720 // C++0x [basic.stc.dynamic.deallocation]p2:
721 // A template instance is never a usual deallocation function,
722 // regardless of its signature.
723 if (isa<FunctionTemplateDecl>(del)) {
724 filter.erase();
725 continue;
726 }
727
728 // C++0x [basic.stc.dynamic.deallocation]p2:
729 // If class T does not declare [an operator delete[] with one
730 // parameter] but does declare a member deallocation function
731 // named operator delete[] with exactly two parameters, the
732 // second of which has type std::size_t, then this function
733 // is a usual deallocation function.
734 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
735 filter.erase();
736 continue;
737 }
738 }
739 filter.done();
740
741 if (!ops.isSingleResult()) return false;
742
743 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
744 return (del->getNumParams() == 2);
745}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000746
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000747/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
748/// @code new (memory) int[size][4] @endcode
749/// or
750/// @code ::new Foo(23, "hello") @endcode
751/// For the interpretation of this heap of arguments, consult the base version.
John McCall60d7b3a2010-08-24 06:29:42 +0000752ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000753Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000754 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000755 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000756 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000757 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000758 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000759 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000760 // If the specified type is an array, unwrap it and save the expression.
761 if (D.getNumTypeObjects() > 0 &&
762 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
763 DeclaratorChunk &Chunk = D.getTypeObject(0);
764 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000765 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
766 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000767 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000768 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
769 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000770
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000771 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000772 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000773 }
774
Douglas Gregor043cad22009-09-11 00:18:58 +0000775 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000776 if (ArraySize) {
777 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000778 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
779 break;
780
781 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
782 if (Expr *NumElts = (Expr *)Array.NumElts) {
783 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
784 !NumElts->isIntegerConstantExpr(Context)) {
785 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
786 << NumElts->getSourceRange();
787 return ExprError();
788 }
789 }
790 }
791 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000792
John McCallbf1a0282010-06-04 23:28:52 +0000793 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
794 QualType AllocType = TInfo->getType();
Chris Lattnereaaebc72009-04-25 08:06:05 +0000795 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000796 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000797
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000798 if (!TInfo)
799 TInfo = Context.getTrivialTypeSourceInfo(AllocType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000800
Mike Stump1eb44332009-09-09 15:08:12 +0000801 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000802 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000803 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000804 PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000805 TypeIdParens,
Mike Stump1eb44332009-09-09 15:08:12 +0000806 AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000807 TInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000808 ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000809 ConstructorLParen,
810 move(ConstructorArgs),
811 ConstructorRParen);
812}
813
John McCall60d7b3a2010-08-24 06:29:42 +0000814ExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000815Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
816 SourceLocation PlacementLParen,
817 MultiExprArg PlacementArgs,
818 SourceLocation PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000819 SourceRange TypeIdParens,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000820 QualType AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000821 TypeSourceInfo *AllocTypeInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000822 Expr *ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000823 SourceLocation ConstructorLParen,
824 MultiExprArg ConstructorArgs,
825 SourceLocation ConstructorRParen) {
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000826 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000827
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000828 // Per C++0x [expr.new]p5, the type being constructed may be a
829 // typedef of an array type.
John McCall9ae2f072010-08-23 23:25:46 +0000830 if (!ArraySize) {
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000831 if (const ConstantArrayType *Array
832 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000833 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
834 Context.getSizeType(),
835 TypeRange.getEnd());
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000836 AllocType = Array->getElementType();
837 }
838 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000839
Douglas Gregora0750762010-10-06 16:00:31 +0000840 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
841 return ExprError();
842
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000843 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000844
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000845 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
846 // or enumeration type with a non-negative value."
Sebastian Redl28507842009-02-26 14:39:58 +0000847 if (ArraySize && !ArraySize->isTypeDependent()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000848
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000849 QualType SizeType = ArraySize->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000850
John McCall60d7b3a2010-08-24 06:29:42 +0000851 ExprResult ConvertedSize
John McCall9ae2f072010-08-23 23:25:46 +0000852 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000853 PDiag(diag::err_array_size_not_integral),
854 PDiag(diag::err_array_size_incomplete_type)
855 << ArraySize->getSourceRange(),
856 PDiag(diag::err_array_size_explicit_conversion),
857 PDiag(diag::note_array_size_conversion),
858 PDiag(diag::err_array_size_ambiguous_conversion),
859 PDiag(diag::note_array_size_conversion),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000860 PDiag(getLangOptions().CPlusPlus0x? 0
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000861 : diag::ext_array_size_conversion));
862 if (ConvertedSize.isInvalid())
863 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000864
John McCall9ae2f072010-08-23 23:25:46 +0000865 ArraySize = ConvertedSize.take();
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000866 SizeType = ArraySize->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000867 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000868 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000869
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000870 // Let's see if this is a constant < 0. If so, we reject it out of hand.
871 // We don't care about special rules, so we tell the machinery it's not
872 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000873 if (!ArraySize->isValueDependent()) {
874 llvm::APSInt Value;
875 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
876 if (Value < llvm::APSInt(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000877 llvm::APInt::getNullValue(Value.getBitWidth()),
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000878 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000879 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +0000880 diag::err_typecheck_negative_array_size)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000881 << ArraySize->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000882
Douglas Gregor2767ce22010-08-18 00:39:00 +0000883 if (!AllocType->isDependentType()) {
884 unsigned ActiveSizeBits
885 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
886 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000887 Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +0000888 diag::err_array_too_large)
889 << Value.toString(10)
890 << ArraySize->getSourceRange();
891 return ExprError();
892 }
893 }
Douglas Gregor4bd40312010-07-13 15:54:32 +0000894 } else if (TypeIdParens.isValid()) {
895 // Can't have dynamic array size when the type-id is in parentheses.
896 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
897 << ArraySize->getSourceRange()
898 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
899 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000900
Douglas Gregor4bd40312010-07-13 15:54:32 +0000901 TypeIdParens = SourceRange();
Sebastian Redl28507842009-02-26 14:39:58 +0000902 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000903 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000904
Eli Friedman73c39ab2009-10-20 08:27:19 +0000905 ImpCastExprToType(ArraySize, Context.getSizeType(),
John McCall2de56d12010-08-25 11:45:40 +0000906 CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000907 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000908
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000909 FunctionDecl *OperatorNew = 0;
910 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000911 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
912 unsigned NumPlaceArgs = PlacementArgs.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000913
Sebastian Redl28507842009-02-26 14:39:58 +0000914 if (!AllocType->isDependentType() &&
915 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
916 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000917 SourceRange(PlacementLParen, PlacementRParen),
918 UseGlobal, AllocType, ArraySize, PlaceArgs,
919 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000920 return ExprError();
John McCall6ec278d2011-01-27 09:37:56 +0000921
922 // If this is an array allocation, compute whether the usual array
923 // deallocation function for the type has a size_t parameter.
924 bool UsualArrayDeleteWantsSize = false;
925 if (ArraySize && !AllocType->isDependentType())
926 UsualArrayDeleteWantsSize
927 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
928
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000929 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000930 if (OperatorNew) {
931 // Add default arguments, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000932 const FunctionProtoType *Proto =
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000933 OperatorNew->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000934 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000935 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000936
Anders Carlsson28e94832010-05-03 02:07:56 +0000937 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000938 Proto, 1, PlaceArgs, NumPlaceArgs,
Anders Carlsson28e94832010-05-03 02:07:56 +0000939 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000940 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000941
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000942 NumPlaceArgs = AllPlaceArgs.size();
943 if (NumPlaceArgs > 0)
944 PlaceArgs = &AllPlaceArgs[0];
945 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000946
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000947 bool Init = ConstructorLParen.isValid();
948 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000949 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000950 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
951 unsigned NumConsArgs = ConstructorArgs.size();
John McCallca0408f2010-08-23 06:44:23 +0000952 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000953
Anders Carlsson48c95012010-05-03 15:45:23 +0000954 // Array 'new' can't have any initializers.
Anders Carlsson55cbd6e2010-05-16 16:24:20 +0000955 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlsson48c95012010-05-03 15:45:23 +0000956 SourceRange InitRange(ConsArgs[0]->getLocStart(),
957 ConsArgs[NumConsArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000958
Anders Carlsson48c95012010-05-03 15:45:23 +0000959 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
960 return ExprError();
961 }
962
Douglas Gregor99a2e602009-12-16 01:38:02 +0000963 if (!AllocType->isDependentType() &&
964 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
965 // C++0x [expr.new]p15:
966 // A new-expression that creates an object of type T initializes that
967 // object as follows:
968 InitializationKind Kind
969 // - If the new-initializer is omitted, the object is default-
970 // initialized (8.5); if no initialization is performed,
971 // the object has indeterminate value
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000972 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000973 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor99a2e602009-12-16 01:38:02 +0000974 // initialization rules of 8.5 for direct-initialization.
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000975 : InitializationKind::CreateDirect(TypeRange.getBegin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000976 ConstructorLParen,
Douglas Gregor99a2e602009-12-16 01:38:02 +0000977 ConstructorRParen);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000978
Douglas Gregor99a2e602009-12-16 01:38:02 +0000979 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +0000980 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000981 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000982 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor99a2e602009-12-16 01:38:02 +0000983 move(ConstructorArgs));
984 if (FullInit.isInvalid())
985 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000986
987 // FullInit is our initializer; walk through it to determine if it's a
Douglas Gregor99a2e602009-12-16 01:38:02 +0000988 // constructor call, which CXXNewExpr handles directly.
989 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
990 if (CXXBindTemporaryExpr *Binder
991 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
992 FullInitExpr = Binder->getSubExpr();
993 if (CXXConstructExpr *Construct
994 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
995 Constructor = Construct->getConstructor();
996 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
997 AEnd = Construct->arg_end();
998 A != AEnd; ++A)
John McCall3fa5cae2010-10-26 07:05:15 +0000999 ConvertedConstructorArgs.push_back(*A);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001000 } else {
1001 // Take the converted initializer.
1002 ConvertedConstructorArgs.push_back(FullInit.release());
1003 }
1004 } else {
1005 // No initialization required.
1006 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001007
Douglas Gregor99a2e602009-12-16 01:38:02 +00001008 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +00001009 NumConsArgs = ConvertedConstructorArgs.size();
1010 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001011 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001012
Douglas Gregor6d908702010-02-26 05:06:18 +00001013 // Mark the new and delete operators as referenced.
1014 if (OperatorNew)
1015 MarkDeclarationReferenced(StartLoc, OperatorNew);
1016 if (OperatorDelete)
1017 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1018
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001019 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001020
Sebastian Redlf53597f2009-03-15 17:47:39 +00001021 PlacementArgs.release();
1022 ConstructorArgs.release();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001023
Ted Kremenekad7fe862010-02-11 22:51:03 +00001024 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregor4bd40312010-07-13 15:54:32 +00001025 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001026 ArraySize, Constructor, Init,
1027 ConsArgs, NumConsArgs, OperatorDelete,
John McCall6ec278d2011-01-27 09:37:56 +00001028 UsualArrayDeleteWantsSize,
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001029 ResultType, AllocTypeInfo,
1030 StartLoc,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001031 Init ? ConstructorRParen :
Chandler Carruth428edaf2010-10-25 08:47:36 +00001032 TypeRange.getEnd(),
1033 ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001034}
1035
1036/// CheckAllocatedType - Checks that a type is suitable as the allocated type
1037/// in a new-expression.
1038/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +00001039bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00001040 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001041 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1042 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +00001043 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001044 return Diag(Loc, diag::err_bad_new_type)
1045 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001046 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001047 return Diag(Loc, diag::err_bad_new_type)
1048 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001049 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +00001050 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001051 PDiag(diag::err_new_incomplete_type)
1052 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001053 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +00001054 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +00001055 diag::err_allocation_of_abstract_type))
1056 return true;
Douglas Gregora0750762010-10-06 16:00:31 +00001057 else if (AllocType->isVariablyModifiedType())
1058 return Diag(Loc, diag::err_variably_modified_new_type)
1059 << AllocType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001060
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001061 return false;
1062}
1063
Douglas Gregor6d908702010-02-26 05:06:18 +00001064/// \brief Determine whether the given function is a non-placement
1065/// deallocation function.
1066static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1067 if (FD->isInvalidDecl())
1068 return false;
1069
1070 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1071 return Method->isUsualDeallocationFunction();
1072
1073 return ((FD->getOverloadedOperator() == OO_Delete ||
1074 FD->getOverloadedOperator() == OO_Array_Delete) &&
1075 FD->getNumParams() == 1);
1076}
1077
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001078/// FindAllocationFunctions - Finds the overloads of operator new and delete
1079/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001080bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1081 bool UseGlobal, QualType AllocType,
1082 bool IsArray, Expr **PlaceArgs,
1083 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001084 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +00001085 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001086 // --- Choosing an allocation function ---
1087 // C++ 5.3.4p8 - 14 & 18
1088 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1089 // in the scope of the allocated class.
1090 // 2) If an array size is given, look for operator new[], else look for
1091 // operator new.
1092 // 3) The first argument is always size_t. Append the arguments from the
1093 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001094
1095 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
1096 // We don't care about the actual value of this argument.
1097 // FIXME: Should the Sema create the expression and embed it in the syntax
1098 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00001099 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Anders Carlssond67c4c32009-08-16 20:29:29 +00001100 Context.Target.getPointerWidth(0)),
1101 Context.getSizeType(),
1102 SourceLocation());
1103 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001104 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1105
Douglas Gregor6d908702010-02-26 05:06:18 +00001106 // C++ [expr.new]p8:
1107 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001108 // function's name is operator new and the deallocation function's
Douglas Gregor6d908702010-02-26 05:06:18 +00001109 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001110 // type, the allocation function's name is operator new[] and the
1111 // deallocation function's name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001112 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1113 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +00001114 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1115 IsArray ? OO_Array_Delete : OO_Delete);
1116
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001117 QualType AllocElemType = Context.getBaseElementType(AllocType);
1118
1119 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +00001120 CXXRecordDecl *Record
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001121 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +00001122 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001123 AllocArgs.size(), Record, /*AllowMissing=*/true,
1124 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001125 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001126 }
1127 if (!OperatorNew) {
1128 // Didn't find a member overload. Look for a global one.
1129 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +00001130 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +00001131 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001132 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1133 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001134 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001135 }
1136
John McCall9c82afc2010-04-20 02:18:25 +00001137 // We don't need an operator delete if we're running under
1138 // -fno-exceptions.
1139 if (!getLangOptions().Exceptions) {
1140 OperatorDelete = 0;
1141 return false;
1142 }
1143
Anders Carlssond9583892009-05-31 20:26:12 +00001144 // FindAllocationOverload can change the passed in arguments, so we need to
1145 // copy them back.
1146 if (NumPlaceArgs > 0)
1147 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001148
Douglas Gregor6d908702010-02-26 05:06:18 +00001149 // C++ [expr.new]p19:
1150 //
1151 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001152 // deallocation function's name is looked up in the global
Douglas Gregor6d908702010-02-26 05:06:18 +00001153 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001154 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6d908702010-02-26 05:06:18 +00001155 // the scope of T. If this lookup fails to find the name, or if
1156 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001157 // deallocation function's name is looked up in the global scope.
Douglas Gregor6d908702010-02-26 05:06:18 +00001158 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001159 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001160 CXXRecordDecl *RD
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001161 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6d908702010-02-26 05:06:18 +00001162 LookupQualifiedName(FoundDelete, RD);
1163 }
John McCall90c8c572010-03-18 08:19:33 +00001164 if (FoundDelete.isAmbiguous())
1165 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +00001166
1167 if (FoundDelete.empty()) {
1168 DeclareGlobalNewDelete();
1169 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1170 }
1171
1172 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +00001173
1174 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1175
John McCalledeb6c92010-09-14 21:34:24 +00001176 // Whether we're looking for a placement operator delete is dictated
1177 // by whether we selected a placement operator new, not by whether
1178 // we had explicit placement arguments. This matters for things like
1179 // struct A { void *operator new(size_t, int = 0); ... };
1180 // A *a = new A()
1181 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1182
1183 if (isPlacementNew) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001184 // C++ [expr.new]p20:
1185 // A declaration of a placement deallocation function matches the
1186 // declaration of a placement allocation function if it has the
1187 // same number of parameters and, after parameter transformations
1188 // (8.3.5), all parameter types except the first are
1189 // identical. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001190 //
Douglas Gregor6d908702010-02-26 05:06:18 +00001191 // To perform this comparison, we compute the function type that
1192 // the deallocation function should have, and use that type both
1193 // for template argument deduction and for comparison purposes.
John McCalle23cf432010-12-14 08:05:40 +00001194 //
1195 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6d908702010-02-26 05:06:18 +00001196 QualType ExpectedFunctionType;
1197 {
1198 const FunctionProtoType *Proto
1199 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00001200
Douglas Gregor6d908702010-02-26 05:06:18 +00001201 llvm::SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001202 ArgTypes.push_back(Context.VoidPtrTy);
Douglas Gregor6d908702010-02-26 05:06:18 +00001203 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1204 ArgTypes.push_back(Proto->getArgType(I));
1205
John McCalle23cf432010-12-14 08:05:40 +00001206 FunctionProtoType::ExtProtoInfo EPI;
1207 EPI.Variadic = Proto->isVariadic();
1208
Douglas Gregor6d908702010-02-26 05:06:18 +00001209 ExpectedFunctionType
1210 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
John McCalle23cf432010-12-14 08:05:40 +00001211 ArgTypes.size(), EPI);
Douglas Gregor6d908702010-02-26 05:06:18 +00001212 }
1213
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001214 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001215 DEnd = FoundDelete.end();
1216 D != DEnd; ++D) {
1217 FunctionDecl *Fn = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001218 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6d908702010-02-26 05:06:18 +00001219 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1220 // Perform template argument deduction to try to match the
1221 // expected function type.
1222 TemplateDeductionInfo Info(Context, StartLoc);
1223 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1224 continue;
1225 } else
1226 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1227
1228 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001229 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001230 }
1231 } else {
1232 // C++ [expr.new]p20:
1233 // [...] Any non-placement deallocation function matches a
1234 // non-placement allocation function. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001235 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001236 DEnd = FoundDelete.end();
1237 D != DEnd; ++D) {
1238 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1239 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001240 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001241 }
1242 }
1243
1244 // C++ [expr.new]p20:
1245 // [...] If the lookup finds a single matching deallocation
1246 // function, that function will be called; otherwise, no
1247 // deallocation function will be called.
1248 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001249 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001250
1251 // C++0x [expr.new]p20:
1252 // If the lookup finds the two-parameter form of a usual
1253 // deallocation function (3.7.4.2) and that function, considered
1254 // as a placement deallocation function, would have been
1255 // selected as a match for the allocation function, the program
1256 // is ill-formed.
1257 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1258 isNonPlacementDeallocationFunction(OperatorDelete)) {
1259 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001260 << SourceRange(PlaceArgs[0]->getLocStart(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001261 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1262 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1263 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001264 } else {
1265 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001266 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001267 }
1268 }
1269
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001270 return false;
1271}
1272
Sebastian Redl7f662392008-12-04 22:20:51 +00001273/// FindAllocationOverload - Find an fitting overload for the allocation
1274/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001275bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1276 DeclarationName Name, Expr** Args,
1277 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +00001278 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001279 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1280 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001281 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001282 if (AllowMissing)
1283 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001284 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001285 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001286 }
1287
John McCall90c8c572010-03-18 08:19:33 +00001288 if (R.isAmbiguous())
1289 return true;
1290
1291 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001292
John McCall5769d612010-02-08 23:07:23 +00001293 OverloadCandidateSet Candidates(StartLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001294 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001295 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001296 // Even member operator new/delete are implicitly treated as
1297 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001298 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001299
John McCall9aa472c2010-03-19 07:35:19 +00001300 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1301 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001302 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1303 Candidates,
1304 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001305 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001306 }
1307
John McCall9aa472c2010-03-19 07:35:19 +00001308 FunctionDecl *Fn = cast<FunctionDecl>(D);
1309 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001310 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001311 }
1312
1313 // Do the resolution.
1314 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00001315 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001316 case OR_Success: {
1317 // Got one!
1318 FunctionDecl *FnDecl = Best->Function;
1319 // The first argument is size_t, and the first parameter must be size_t,
1320 // too. This is checked on declaration and can be assumed. (It can't be
1321 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001322 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001323 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1324 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
John McCall60d7b3a2010-08-24 06:29:42 +00001325 ExprResult Result
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001326 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001327 Context,
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001328 FnDecl->getParamDecl(i)),
1329 SourceLocation(),
John McCall3fa5cae2010-10-26 07:05:15 +00001330 Owned(Args[i]));
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001331 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001332 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001333
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001334 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001335 }
1336 Operator = FnDecl;
John McCall9aa472c2010-03-19 07:35:19 +00001337 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001338 return false;
1339 }
1340
1341 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +00001342 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001343 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001344 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001345 return true;
1346
1347 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +00001348 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +00001349 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001350 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001351 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001352
1353 case OR_Deleted:
1354 Diag(StartLoc, diag::err_ovl_deleted_call)
1355 << Best->Function->isDeleted()
1356 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001357 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001358 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001359 }
1360 assert(false && "Unreachable, bad result from BestViableFunction");
1361 return true;
1362}
1363
1364
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001365/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1366/// delete. These are:
1367/// @code
1368/// void* operator new(std::size_t) throw(std::bad_alloc);
1369/// void* operator new[](std::size_t) throw(std::bad_alloc);
1370/// void operator delete(void *) throw();
1371/// void operator delete[](void *) throw();
1372/// @endcode
1373/// Note that the placement and nothrow forms of new are *not* implicitly
1374/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001375void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001376 if (GlobalNewDeleteDeclared)
1377 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001378
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001379 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001380 // [...] The following allocation and deallocation functions (18.4) are
1381 // implicitly declared in global scope in each translation unit of a
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001382 // program
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001383 //
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001384 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001385 // void* operator new[](std::size_t) throw(std::bad_alloc);
1386 // void operator delete(void*) throw();
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001387 // void operator delete[](void*) throw();
1388 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001389 // These implicit declarations introduce only the function names operator
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001390 // new, operator new[], operator delete, operator delete[].
1391 //
1392 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1393 // "std" or "bad_alloc" as necessary to form the exception specification.
1394 // However, we do not make these implicit declarations visible to name
1395 // lookup.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001396 if (!StdBadAlloc) {
1397 // The "std::bad_alloc" class has not yet been declared, so build it
1398 // implicitly.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001399 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1400 getOrCreateStdNamespace(),
1401 SourceLocation(),
1402 &PP.getIdentifierTable().get("bad_alloc"),
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001403 SourceLocation(), 0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001404 getStdBadAlloc()->setImplicit(true);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001405 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001406
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001407 GlobalNewDeleteDeclared = true;
1408
1409 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1410 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001411 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001412
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001413 DeclareGlobalAllocationFunction(
1414 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001415 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001416 DeclareGlobalAllocationFunction(
1417 Context.DeclarationNames.getCXXOperatorName(OO_Array_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_Delete),
1421 Context.VoidTy, VoidPtr);
1422 DeclareGlobalAllocationFunction(
1423 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1424 Context.VoidTy, VoidPtr);
1425}
1426
1427/// DeclareGlobalAllocationFunction - Declares a single implicit global
1428/// allocation function if it doesn't already exist.
1429void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001430 QualType Return, QualType Argument,
1431 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001432 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1433
1434 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001435 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001436 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001437 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001438 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001439 // Only look at non-template functions, as it is the predefined,
1440 // non-templated allocation function we are trying to declare here.
1441 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1442 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001443 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001444 Func->getParamDecl(0)->getType().getUnqualifiedType());
1445 // FIXME: Do we need to check for default arguments here?
Douglas Gregor7b868622010-08-18 15:06:25 +00001446 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1447 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00001448 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001449 return;
Douglas Gregor7b868622010-08-18 15:06:25 +00001450 }
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001451 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001452 }
1453 }
1454
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001455 QualType BadAllocType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001456 bool HasBadAllocExceptionSpec
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001457 = (Name.getCXXOverloadedOperator() == OO_New ||
1458 Name.getCXXOverloadedOperator() == OO_Array_New);
1459 if (HasBadAllocExceptionSpec) {
1460 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001461 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001462 }
John McCalle23cf432010-12-14 08:05:40 +00001463
1464 FunctionProtoType::ExtProtoInfo EPI;
1465 EPI.HasExceptionSpec = true;
1466 if (HasBadAllocExceptionSpec) {
1467 EPI.NumExceptions = 1;
1468 EPI.Exceptions = &BadAllocType;
1469 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001470
John McCalle23cf432010-12-14 08:05:40 +00001471 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001472 FunctionDecl *Alloc =
1473 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCalld931b082010-08-26 03:08:43 +00001474 FnType, /*TInfo=*/0, SC_None,
1475 SC_None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001476 Alloc->setImplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001477
Nuno Lopesfc284482009-12-16 16:59:22 +00001478 if (AddMallocAttr)
Sean Huntcf807c42010-08-18 23:23:40 +00001479 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001480
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001481 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00001482 0, Argument, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00001483 SC_None,
1484 SC_None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00001485 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001486
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001487 // FIXME: Also add this declaration to the IdentifierResolver, but
1488 // make sure it is at the end of the chain to coincide with the
1489 // global scope.
John McCall5f1e0942010-08-24 08:50:51 +00001490 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001491}
1492
Anders Carlsson78f74552009-11-15 18:45:20 +00001493bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1494 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00001495 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001496 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001497 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001498 LookupQualifiedName(Found, RD);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001499
John McCalla24dc2e2009-11-17 02:14:36 +00001500 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001501 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001502
Chandler Carruth23893242010-06-28 00:30:51 +00001503 Found.suppressDiagnostics();
1504
John McCall046a7462010-08-04 00:31:26 +00001505 llvm::SmallVector<DeclAccessPair,4> Matches;
Anders Carlsson78f74552009-11-15 18:45:20 +00001506 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1507 F != FEnd; ++F) {
Chandler Carruth09556fd2010-08-08 07:04:00 +00001508 NamedDecl *ND = (*F)->getUnderlyingDecl();
1509
1510 // Ignore template operator delete members from the check for a usual
1511 // deallocation function.
1512 if (isa<FunctionTemplateDecl>(ND))
1513 continue;
1514
1515 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall046a7462010-08-04 00:31:26 +00001516 Matches.push_back(F.getPair());
1517 }
1518
1519 // There's exactly one suitable operator; pick it.
1520 if (Matches.size() == 1) {
1521 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
1522 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1523 Matches[0]);
1524 return false;
1525
1526 // We found multiple suitable operators; complain about the ambiguity.
1527 } else if (!Matches.empty()) {
1528 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1529 << Name << RD;
1530
1531 for (llvm::SmallVectorImpl<DeclAccessPair>::iterator
1532 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1533 Diag((*F)->getUnderlyingDecl()->getLocation(),
1534 diag::note_member_declared_here) << Name;
1535 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001536 }
1537
1538 // We did find operator delete/operator delete[] declarations, but
1539 // none of them were suitable.
1540 if (!Found.empty()) {
1541 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1542 << Name << RD;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001543
Anders Carlsson78f74552009-11-15 18:45:20 +00001544 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
John McCall046a7462010-08-04 00:31:26 +00001545 F != FEnd; ++F)
1546 Diag((*F)->getUnderlyingDecl()->getLocation(),
1547 diag::note_member_declared_here) << Name;
Anders Carlsson78f74552009-11-15 18:45:20 +00001548
1549 return true;
1550 }
1551
1552 // Look for a global declaration.
1553 DeclareGlobalNewDelete();
1554 DeclContext *TUDecl = Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001555
Anders Carlsson78f74552009-11-15 18:45:20 +00001556 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1557 Expr* DeallocArgs[1];
1558 DeallocArgs[0] = &Null;
1559 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1560 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1561 Operator))
1562 return true;
1563
1564 assert(Operator && "Did not find a deallocation function!");
1565 return false;
1566}
1567
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001568/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1569/// @code ::delete ptr; @endcode
1570/// or
1571/// @code delete [] ptr; @endcode
John McCall60d7b3a2010-08-24 06:29:42 +00001572ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001573Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John McCall9ae2f072010-08-23 23:25:46 +00001574 bool ArrayForm, Expr *Ex) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001575 // C++ [expr.delete]p1:
1576 // The operand shall have a pointer type, or a class type having a single
1577 // conversion function to a pointer type. The result has type void.
1578 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001579 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1580
Anders Carlssond67c4c32009-08-16 20:29:29 +00001581 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001582 bool ArrayFormAsWritten = ArrayForm;
John McCall6ec278d2011-01-27 09:37:56 +00001583 bool UsualArrayDeleteWantsSize = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001584
Sebastian Redl28507842009-02-26 14:39:58 +00001585 if (!Ex->isTypeDependent()) {
1586 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001587
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001588 if (const RecordType *Record = Type->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001589 if (RequireCompleteType(StartLoc, Type,
Douglas Gregor254a9422010-07-29 14:44:35 +00001590 PDiag(diag::err_delete_incomplete_class_type)))
1591 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001592
John McCall32daa422010-03-31 01:36:47 +00001593 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1594
Fariborz Jahanian53462782009-09-11 21:44:33 +00001595 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001596 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001597 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001598 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001599 NamedDecl *D = I.getDecl();
1600 if (isa<UsingShadowDecl>(D))
1601 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1602
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001603 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001604 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001605 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001606
John McCall32daa422010-03-31 01:36:47 +00001607 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001608
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001609 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1610 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedman13578692010-08-05 02:49:48 +00001611 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001612 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001613 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001614 if (ObjectPtrConversions.size() == 1) {
1615 // We have a single conversion to a pointer-to-object type. Perform
1616 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001617 // TODO: don't redo the conversion calculation.
John McCall32daa422010-03-31 01:36:47 +00001618 if (!PerformImplicitConversion(Ex,
1619 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +00001620 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001621 Type = Ex->getType();
1622 }
1623 }
1624 else if (ObjectPtrConversions.size() > 1) {
1625 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1626 << Type << Ex->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001627 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1628 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001629 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001630 }
Sebastian Redl28507842009-02-26 14:39:58 +00001631 }
1632
Sebastian Redlf53597f2009-03-15 17:47:39 +00001633 if (!Type->isPointerType())
1634 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1635 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001636
Ted Kremenek6217b802009-07-29 21:53:49 +00001637 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor94a61572010-05-24 17:01:56 +00001638 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001639 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregor94a61572010-05-24 17:01:56 +00001640 // effectively bans deletion of "void*". However, most compilers support
1641 // this, so we treat it as a warning unless we're in a SFINAE context.
1642 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1643 << Type << Ex->getSourceRange();
1644 } else if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001645 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1646 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001647 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001648 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +00001649 PDiag(diag::warn_delete_incomplete)
1650 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001651 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +00001652
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001653 // C++ [expr.delete]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001654 // [Note: a pointer to a const type can be the operand of a
1655 // delete-expression; it is not necessary to cast away the constness
1656 // (5.2.11) of the pointer expression before it is used as the operand
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001657 // of the delete-expression. ]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001658 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
John McCall2de56d12010-08-25 11:45:40 +00001659 CK_NoOp);
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001660
1661 if (Pointee->isArrayType() && !ArrayForm) {
1662 Diag(StartLoc, diag::warn_delete_array_type)
1663 << Type << Ex->getSourceRange()
1664 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1665 ArrayForm = true;
1666 }
1667
Anders Carlssond67c4c32009-08-16 20:29:29 +00001668 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1669 ArrayForm ? OO_Array_Delete : OO_Delete);
1670
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001671 QualType PointeeElem = Context.getBaseElementType(Pointee);
1672 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001673 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1674
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001675 if (!UseGlobal &&
Anders Carlsson78f74552009-11-15 18:45:20 +00001676 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001677 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001678
John McCall6ec278d2011-01-27 09:37:56 +00001679 // If we're allocating an array of records, check whether the
1680 // usual operator delete[] has a size_t parameter.
1681 if (ArrayForm) {
1682 // If the user specifically asked to use the global allocator,
1683 // we'll need to do the lookup into the class.
1684 if (UseGlobal)
1685 UsualArrayDeleteWantsSize =
1686 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
1687
1688 // Otherwise, the usual operator delete[] should be the
1689 // function we just found.
1690 else if (isa<CXXMethodDecl>(OperatorDelete))
1691 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
1692 }
1693
Anders Carlsson78f74552009-11-15 18:45:20 +00001694 if (!RD->hasTrivialDestructor())
Douglas Gregor9b623632010-10-12 23:32:35 +00001695 if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001696 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001697 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor9b623632010-10-12 23:32:35 +00001698 DiagnoseUseOfDecl(Dtor, StartLoc);
1699 }
Anders Carlssond67c4c32009-08-16 20:29:29 +00001700 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001701
Anders Carlssond67c4c32009-08-16 20:29:29 +00001702 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001703 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001704 DeclareGlobalNewDelete();
1705 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001706 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +00001707 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001708 OperatorDelete))
1709 return ExprError();
1710 }
Mike Stump1eb44332009-09-09 15:08:12 +00001711
John McCall9c82afc2010-04-20 02:18:25 +00001712 MarkDeclarationReferenced(StartLoc, OperatorDelete);
John McCall6ec278d2011-01-27 09:37:56 +00001713
Douglas Gregord880f522011-02-01 15:50:11 +00001714 // Check access and ambiguity of operator delete and destructor.
1715 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
1716 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1717 if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
1718 CheckDestructorAccess(Ex->getExprLoc(), Dtor,
1719 PDiag(diag::err_access_dtor) << PointeeElem);
1720 }
1721 }
1722
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001723 }
1724
Sebastian Redlf53597f2009-03-15 17:47:39 +00001725 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
John McCall6ec278d2011-01-27 09:37:56 +00001726 ArrayFormAsWritten,
1727 UsualArrayDeleteWantsSize,
1728 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001729}
1730
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001731/// \brief Check the use of the given variable as a C++ condition in an if,
1732/// while, do-while, or switch statement.
John McCall60d7b3a2010-08-24 06:29:42 +00001733ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCallf89e55a2010-11-18 06:31:45 +00001734 SourceLocation StmtLoc,
1735 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001736 QualType T = ConditionVar->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001737
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001738 // C++ [stmt.select]p2:
1739 // The declarator shall not specify a function or an array.
1740 if (T->isFunctionType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001741 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001742 diag::err_invalid_use_of_function_type)
1743 << ConditionVar->getSourceRange());
1744 else if (T->isArrayType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001745 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001746 diag::err_invalid_use_of_array_type)
1747 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001748
Douglas Gregor586596f2010-05-06 17:25:47 +00001749 Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001750 ConditionVar->getLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00001751 ConditionVar->getType().getNonReferenceType(),
John McCall09431682010-11-18 19:01:18 +00001752 VK_LValue);
Douglas Gregorff331c12010-07-25 18:17:45 +00001753 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc))
Douglas Gregor586596f2010-05-06 17:25:47 +00001754 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001755
Douglas Gregor586596f2010-05-06 17:25:47 +00001756 return Owned(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001757}
1758
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001759/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1760bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1761 // C++ 6.4p4:
1762 // The value of a condition that is an initialized declaration in a statement
1763 // other than a switch statement is the value of the declared variable
1764 // implicitly converted to type bool. If that conversion is ill-formed, the
1765 // program is ill-formed.
1766 // The value of a condition that is an expression is the value of the
1767 // expression, implicitly converted to bool.
1768 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001769 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001770}
Douglas Gregor77a52232008-09-12 00:47:35 +00001771
1772/// Helper function to determine whether this is the (deprecated) C++
1773/// conversion from a string literal to a pointer to non-const char or
1774/// non-const wchar_t (for narrow and wide string literals,
1775/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001776bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001777Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1778 // Look inside the implicit cast, if it exists.
1779 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1780 From = Cast->getSubExpr();
1781
1782 // A string literal (2.13.4) that is not a wide string literal can
1783 // be converted to an rvalue of type "pointer to char"; a wide
1784 // string literal can be converted to an rvalue of type "pointer
1785 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00001786 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00001787 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001788 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001789 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001790 // This conversion is considered only when there is an
1791 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001792 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001793 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1794 (!StrLit->isWide() &&
1795 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1796 ToPointeeType->getKind() == BuiltinType::Char_S))))
1797 return true;
1798 }
1799
1800 return false;
1801}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001802
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001803static ExprResult BuildCXXCastArgument(Sema &S,
John McCall2de56d12010-08-25 11:45:40 +00001804 SourceLocation CastLoc,
1805 QualType Ty,
1806 CastKind Kind,
1807 CXXMethodDecl *Method,
Douglas Gregor83eecbe2011-01-20 01:32:05 +00001808 NamedDecl *FoundDecl,
John McCall2de56d12010-08-25 11:45:40 +00001809 Expr *From) {
Douglas Gregorba70ab62010-04-16 22:17:36 +00001810 switch (Kind) {
1811 default: assert(0 && "Unhandled cast kind!");
John McCall2de56d12010-08-25 11:45:40 +00001812 case CK_ConstructorConversion: {
John McCallca0408f2010-08-23 06:44:23 +00001813 ASTOwningVector<Expr*> ConstructorArgs(S);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001814
Douglas Gregorba70ab62010-04-16 22:17:36 +00001815 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
John McCallf312b1e2010-08-26 23:41:50 +00001816 MultiExprArg(&From, 1),
Douglas Gregorba70ab62010-04-16 22:17:36 +00001817 CastLoc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00001818 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001819
1820 ExprResult Result =
1821 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
John McCall7a1fad32010-08-24 07:32:53 +00001822 move_arg(ConstructorArgs),
Chandler Carruth428edaf2010-10-25 08:47:36 +00001823 /*ZeroInit*/ false, CXXConstructExpr::CK_Complete,
1824 SourceRange());
Douglas Gregorba70ab62010-04-16 22:17:36 +00001825 if (Result.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00001826 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001827
Douglas Gregorba70ab62010-04-16 22:17:36 +00001828 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1829 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001830
John McCall2de56d12010-08-25 11:45:40 +00001831 case CK_UserDefinedConversion: {
Douglas Gregorba70ab62010-04-16 22:17:36 +00001832 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001833
Douglas Gregorba70ab62010-04-16 22:17:36 +00001834 // Create an implicit call expr that calls it.
Douglas Gregor83eecbe2011-01-20 01:32:05 +00001835 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00001836 if (Result.isInvalid())
1837 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001838
Douglas Gregorf2ae5262011-01-20 00:18:04 +00001839 return S.MaybeBindToTemporary(Result.get());
Douglas Gregorba70ab62010-04-16 22:17:36 +00001840 }
1841 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001842}
Douglas Gregorba70ab62010-04-16 22:17:36 +00001843
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001844/// PerformImplicitConversion - Perform an implicit conversion of the
1845/// expression From to the type ToType using the pre-computed implicit
1846/// conversion sequence ICS. Returns true if there was an error, false
1847/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001848/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001849/// used in the error message.
1850bool
1851Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1852 const ImplicitConversionSequence &ICS,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001853 AssignmentAction Action, bool CStyle) {
John McCall1d318332010-01-12 00:44:57 +00001854 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001855 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001856 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001857 CStyle))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001858 return true;
1859 break;
1860
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001861 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001862
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001863 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCalldaa8e4e2010-11-15 09:13:47 +00001864 CastKind CastKind;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001865 QualType BeforeToType;
1866 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCall2de56d12010-08-25 11:45:40 +00001867 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001868
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001869 // If the user-defined conversion is specified by a conversion function,
1870 // the initial standard conversion sequence converts the source type to
1871 // the implicit object parameter of the conversion function.
1872 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCall9ec94452010-12-04 09:57:16 +00001873 } else {
1874 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCall2de56d12010-08-25 11:45:40 +00001875 CastKind = CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001876 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001877 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001878 // If the user-defined conversion is specified by a constructor, the
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001879 // initial standard conversion sequence converts the source type to the
1880 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001881 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1882 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001883 }
Douglas Gregora3998bd2010-12-02 21:47:04 +00001884 // Watch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001885 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001886 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001887 ICS.UserDefined.Before, AA_Converting,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001888 CStyle))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001889 return true;
1890 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001891
1892 ExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00001893 = BuildCXXCastArgument(*this,
1894 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00001895 ToType.getNonReferenceType(),
Douglas Gregor83eecbe2011-01-20 01:32:05 +00001896 CastKind, cast<CXXMethodDecl>(FD),
1897 ICS.UserDefined.FoundConversionFunction,
John McCall9ae2f072010-08-23 23:25:46 +00001898 From);
Anders Carlsson0aebc812009-09-09 21:33:21 +00001899
1900 if (CastArg.isInvalid())
1901 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001902
1903 From = CastArg.takeAs<Expr>();
1904
Eli Friedmand8889622009-11-27 04:41:50 +00001905 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001906 AA_Converting, CStyle);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001907 }
John McCall1d318332010-01-12 00:44:57 +00001908
1909 case ImplicitConversionSequence::AmbiguousConversion:
John McCall120d63c2010-08-24 20:38:10 +00001910 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall1d318332010-01-12 00:44:57 +00001911 PDiag(diag::err_typecheck_ambiguous_condition)
1912 << From->getSourceRange());
1913 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001914
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001915 case ImplicitConversionSequence::EllipsisConversion:
1916 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001917 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001918
1919 case ImplicitConversionSequence::BadConversion:
1920 return true;
1921 }
1922
1923 // Everything went well.
1924 return false;
1925}
1926
1927/// PerformImplicitConversion - Perform an implicit conversion of the
1928/// expression From to the type ToType by following the standard
1929/// conversion sequence SCS. Returns true if there was an error, false
1930/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001931/// expression. Flavor is the context in which we're performing this
1932/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001933bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001934Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001935 const StandardConversionSequence& SCS,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001936 AssignmentAction Action, bool CStyle) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001937 // Overall FIXME: we are recomputing too many types here and doing far too
1938 // much extra work. What this means is that we need to keep track of more
1939 // information that is computed when we try the implicit conversion initially,
1940 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001941 QualType FromType = From->getType();
1942
Douglas Gregor225c41e2008-11-03 19:09:14 +00001943 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001944 // FIXME: When can ToType be a reference type?
1945 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001946 if (SCS.Second == ICK_Derived_To_Base) {
John McCallca0408f2010-08-23 06:44:23 +00001947 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001948 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCallca0408f2010-08-23 06:44:23 +00001949 MultiExprArg(*this, &From, 1),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001950 /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001951 ConstructorArgs))
1952 return true;
John McCall60d7b3a2010-08-24 06:29:42 +00001953 ExprResult FromResult =
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001954 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1955 ToType, SCS.CopyConstructor,
John McCall7a1fad32010-08-24 07:32:53 +00001956 move_arg(ConstructorArgs),
1957 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00001958 CXXConstructExpr::CK_Complete,
1959 SourceRange());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001960 if (FromResult.isInvalid())
1961 return true;
1962 From = FromResult.takeAs<Expr>();
1963 return false;
1964 }
John McCall60d7b3a2010-08-24 06:29:42 +00001965 ExprResult FromResult =
Mike Stump1eb44332009-09-09 15:08:12 +00001966 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1967 ToType, SCS.CopyConstructor,
John McCall7a1fad32010-08-24 07:32:53 +00001968 MultiExprArg(*this, &From, 1),
1969 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00001970 CXXConstructExpr::CK_Complete,
1971 SourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +00001972
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001973 if (FromResult.isInvalid())
1974 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001975
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001976 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001977 return false;
1978 }
1979
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001980 // Resolve overloaded function references.
1981 if (Context.hasSameType(FromType, Context.OverloadTy)) {
1982 DeclAccessPair Found;
1983 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1984 true, Found);
1985 if (!Fn)
1986 return true;
1987
1988 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1989 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001990
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001991 From = FixOverloadedFunctionReference(From, Found, Fn);
1992 FromType = From->getType();
1993 }
1994
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001995 // Perform the first implicit conversion.
1996 switch (SCS.First) {
1997 case ICK_Identity:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001998 // Nothing to do.
1999 break;
2000
John McCallf6a16482010-12-04 03:47:34 +00002001 case ICK_Lvalue_To_Rvalue:
2002 // Should this get its own ICK?
2003 if (From->getObjectKind() == OK_ObjCProperty) {
2004 ConvertPropertyForRValue(From);
John McCall241d5582010-12-07 22:54:16 +00002005 if (!From->isGLValue()) break;
John McCallf6a16482010-12-04 03:47:34 +00002006 }
2007
2008 FromType = FromType.getUnqualifiedType();
2009 From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
2010 From, 0, VK_RValue);
2011 break;
2012
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002013 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002014 FromType = Context.getArrayDecayedType(FromType);
John McCall2de56d12010-08-25 11:45:40 +00002015 ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002016 break;
2017
2018 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002019 FromType = Context.getPointerType(FromType);
John McCall2de56d12010-08-25 11:45:40 +00002020 ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002021 break;
2022
2023 default:
2024 assert(false && "Improper first standard conversion");
2025 break;
2026 }
2027
2028 // Perform the second implicit conversion
2029 switch (SCS.Second) {
2030 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002031 // If both sides are functions (or pointers/references to them), there could
2032 // be incompatible exception declarations.
2033 if (CheckExceptionSpecCompatibility(From, ToType))
2034 return true;
2035 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002036 break;
2037
Douglas Gregor43c79c22009-12-09 00:47:37 +00002038 case ICK_NoReturn_Adjustment:
2039 // If both sides are functions (or pointers/references to them), there could
2040 // be incompatible exception declarations.
2041 if (CheckExceptionSpecCompatibility(From, ToType))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002042 return true;
2043
John McCalle6a365d2010-12-19 02:44:49 +00002044 ImpCastExprToType(From, ToType, CK_NoOp);
Douglas Gregor43c79c22009-12-09 00:47:37 +00002045 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002046
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002047 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002048 case ICK_Integral_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00002049 ImpCastExprToType(From, ToType, CK_IntegralCast);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002050 break;
2051
2052 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002053 case ICK_Floating_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00002054 ImpCastExprToType(From, ToType, CK_FloatingCast);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002055 break;
2056
2057 case ICK_Complex_Promotion:
John McCalldaa8e4e2010-11-15 09:13:47 +00002058 case ICK_Complex_Conversion: {
2059 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2060 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2061 CastKind CK;
2062 if (FromEl->isRealFloatingType()) {
2063 if (ToEl->isRealFloatingType())
2064 CK = CK_FloatingComplexCast;
2065 else
2066 CK = CK_FloatingComplexToIntegralComplex;
2067 } else if (ToEl->isRealFloatingType()) {
2068 CK = CK_IntegralComplexToFloatingComplex;
2069 } else {
2070 CK = CK_IntegralComplexCast;
2071 }
2072 ImpCastExprToType(From, ToType, CK);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002073 break;
John McCalldaa8e4e2010-11-15 09:13:47 +00002074 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00002075
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002076 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00002077 if (ToType->isRealFloatingType())
John McCall2de56d12010-08-25 11:45:40 +00002078 ImpCastExprToType(From, ToType, CK_IntegralToFloating);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002079 else
John McCall2de56d12010-08-25 11:45:40 +00002080 ImpCastExprToType(From, ToType, CK_FloatingToIntegral);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002081 break;
2082
Douglas Gregorf9201e02009-02-11 23:02:49 +00002083 case ICK_Compatible_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00002084 ImpCastExprToType(From, ToType, CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002085 break;
2086
Anders Carlsson61faec12009-09-12 04:46:44 +00002087 case ICK_Pointer_Conversion: {
Douglas Gregora3998bd2010-12-02 21:47:04 +00002088 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor45920e82008-12-19 17:40:08 +00002089 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00002090 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00002091 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00002092 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00002093 << From->getSourceRange();
2094 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002095
John McCalldaa8e4e2010-11-15 09:13:47 +00002096 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002097 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002098 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002099 return true;
John McCall5baba9d2010-08-25 10:28:54 +00002100 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002101 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00002102 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002103
Anders Carlsson61faec12009-09-12 04:46:44 +00002104 case ICK_Pointer_Member: {
John McCalldaa8e4e2010-11-15 09:13:47 +00002105 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002106 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002107 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
Anders Carlsson61faec12009-09-12 04:46:44 +00002108 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002109 if (CheckExceptionSpecCompatibility(From, ToType))
2110 return true;
John McCall5baba9d2010-08-25 10:28:54 +00002111 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
Anders Carlsson61faec12009-09-12 04:46:44 +00002112 break;
2113 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00002114 case ICK_Boolean_Conversion: {
John McCalldaa8e4e2010-11-15 09:13:47 +00002115 CastKind Kind = CK_Invalid;
2116 switch (FromType->getScalarTypeKind()) {
2117 case Type::STK_Pointer: Kind = CK_PointerToBoolean; break;
2118 case Type::STK_MemberPointer: Kind = CK_MemberPointerToBoolean; break;
2119 case Type::STK_Bool: llvm_unreachable("bool -> bool conversion?");
2120 case Type::STK_Integral: Kind = CK_IntegralToBoolean; break;
2121 case Type::STK_Floating: Kind = CK_FloatingToBoolean; break;
2122 case Type::STK_IntegralComplex: Kind = CK_IntegralComplexToBoolean; break;
2123 case Type::STK_FloatingComplex: Kind = CK_FloatingComplexToBoolean; break;
2124 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002125
Anders Carlssonbc0e0782009-11-23 20:04:44 +00002126 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002127 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00002128 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002129
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002130 case ICK_Derived_To_Base: {
John McCallf871d0c2010-08-07 06:22:56 +00002131 CXXCastPath BasePath;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002132 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002133 ToType.getNonReferenceType(),
2134 From->getLocStart(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002135 From->getSourceRange(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002136 &BasePath,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002137 CStyle))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002138 return true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002139
Sebastian Redl906082e2010-07-20 04:20:21 +00002140 ImpCastExprToType(From, ToType.getNonReferenceType(),
John McCall2de56d12010-08-25 11:45:40 +00002141 CK_DerivedToBase, CastCategory(From),
John McCallf871d0c2010-08-07 06:22:56 +00002142 &BasePath);
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002143 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002144 }
2145
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002146 case ICK_Vector_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00002147 ImpCastExprToType(From, ToType, CK_BitCast);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002148 break;
2149
2150 case ICK_Vector_Splat:
John McCall2de56d12010-08-25 11:45:40 +00002151 ImpCastExprToType(From, ToType, CK_VectorSplat);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002152 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002153
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002154 case ICK_Complex_Real:
John McCalldaa8e4e2010-11-15 09:13:47 +00002155 // Case 1. x -> _Complex y
2156 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2157 QualType ElType = ToComplex->getElementType();
2158 bool isFloatingComplex = ElType->isRealFloatingType();
2159
2160 // x -> y
2161 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2162 // do nothing
2163 } else if (From->getType()->isRealFloatingType()) {
2164 ImpCastExprToType(From, ElType,
2165 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral);
2166 } else {
2167 assert(From->getType()->isIntegerType());
2168 ImpCastExprToType(From, ElType,
2169 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast);
2170 }
2171 // y -> _Complex y
2172 ImpCastExprToType(From, ToType,
2173 isFloatingComplex ? CK_FloatingRealToComplex
2174 : CK_IntegralRealToComplex);
2175
2176 // Case 2. _Complex x -> y
2177 } else {
2178 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2179 assert(FromComplex);
2180
2181 QualType ElType = FromComplex->getElementType();
2182 bool isFloatingComplex = ElType->isRealFloatingType();
2183
2184 // _Complex x -> x
2185 ImpCastExprToType(From, ElType,
2186 isFloatingComplex ? CK_FloatingComplexToReal
2187 : CK_IntegralComplexToReal);
2188
2189 // x -> y
2190 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2191 // do nothing
2192 } else if (ToType->isRealFloatingType()) {
2193 ImpCastExprToType(From, ToType,
2194 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating);
2195 } else {
2196 assert(ToType->isIntegerType());
2197 ImpCastExprToType(From, ToType,
2198 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast);
2199 }
2200 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002201 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002202
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002203 case ICK_Lvalue_To_Rvalue:
2204 case ICK_Array_To_Pointer:
2205 case ICK_Function_To_Pointer:
2206 case ICK_Qualification:
2207 case ICK_Num_Conversion_Kinds:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002208 assert(false && "Improper second standard conversion");
2209 break;
2210 }
2211
2212 switch (SCS.Third) {
2213 case ICK_Identity:
2214 // Nothing to do.
2215 break;
2216
Sebastian Redl906082e2010-07-20 04:20:21 +00002217 case ICK_Qualification: {
2218 // The qualification keeps the category of the inner expression, unless the
2219 // target type isn't a reference.
John McCall5baba9d2010-08-25 10:28:54 +00002220 ExprValueKind VK = ToType->isReferenceType() ?
2221 CastCategory(From) : VK_RValue;
Douglas Gregor63982352010-07-13 18:40:04 +00002222 ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
John McCall2de56d12010-08-25 11:45:40 +00002223 CK_NoOp, VK);
Douglas Gregora9bff302010-02-28 18:30:25 +00002224
2225 if (SCS.DeprecatedStringLiteralToCharPtr)
2226 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2227 << ToType.getNonReferenceType();
2228
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002229 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002230 }
2231
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002232 default:
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002233 assert(false && "Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002234 break;
2235 }
2236
2237 return false;
2238}
2239
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002240ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002241 SourceLocation KWLoc,
2242 ParsedType Ty,
2243 SourceLocation RParen) {
2244 TypeSourceInfo *TSInfo;
2245 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002246
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002247 if (!TSInfo)
2248 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002249 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002250}
2251
Sebastian Redlf8aca862010-09-14 23:40:14 +00002252static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT, QualType T,
2253 SourceLocation KeyLoc) {
Douglas Gregora0506182011-01-27 20:35:44 +00002254 // FIXME: For many of these traits, we need a complete type before we can
2255 // check these properties.
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002256 assert(!T->isDependentType() &&
2257 "Cannot evaluate traits for dependent types.");
2258 ASTContext &C = Self.Context;
2259 switch(UTT) {
2260 default: assert(false && "Unknown type trait or not implemented");
2261 case UTT_IsPOD: return T->isPODType();
2262 case UTT_IsLiteral: return T->isLiteralType();
2263 case UTT_IsClass: // Fallthrough
2264 case UTT_IsUnion:
2265 if (const RecordType *Record = T->getAs<RecordType>()) {
2266 bool Union = Record->getDecl()->isUnion();
2267 return UTT == UTT_IsUnion ? Union : !Union;
2268 }
2269 return false;
2270 case UTT_IsEnum: return T->isEnumeralType();
2271 case UTT_IsPolymorphic:
2272 if (const RecordType *Record = T->getAs<RecordType>()) {
2273 // Type traits are only parsed in C++, so we've got CXXRecords.
2274 return cast<CXXRecordDecl>(Record->getDecl())->isPolymorphic();
2275 }
2276 return false;
2277 case UTT_IsAbstract:
2278 if (const RecordType *RT = T->getAs<RecordType>())
2279 return cast<CXXRecordDecl>(RT->getDecl())->isAbstract();
2280 return false;
2281 case UTT_IsEmpty:
2282 if (const RecordType *Record = T->getAs<RecordType>()) {
2283 return !Record->getDecl()->isUnion()
2284 && cast<CXXRecordDecl>(Record->getDecl())->isEmpty();
2285 }
2286 return false;
2287 case UTT_HasTrivialConstructor:
2288 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2289 // If __is_pod (type) is true then the trait is true, else if type is
2290 // a cv class or union type (or array thereof) with a trivial default
2291 // constructor ([class.ctor]) then the trait is true, else it is false.
2292 if (T->isPODType())
2293 return true;
2294 if (const RecordType *RT =
2295 C.getBaseElementType(T)->getAs<RecordType>())
2296 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialConstructor();
2297 return false;
2298 case UTT_HasTrivialCopy:
2299 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2300 // If __is_pod (type) is true or type is a reference type then
2301 // the trait is true, else if type is a cv class or union type
2302 // with a trivial copy constructor ([class.copy]) then the trait
2303 // is true, else it is false.
2304 if (T->isPODType() || T->isReferenceType())
2305 return true;
2306 if (const RecordType *RT = T->getAs<RecordType>())
2307 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2308 return false;
2309 case UTT_HasTrivialAssign:
2310 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2311 // If type is const qualified or is a reference type then the
2312 // trait is false. Otherwise if __is_pod (type) is true then the
2313 // trait is true, else if type is a cv class or union type with
2314 // a trivial copy assignment ([class.copy]) then the trait is
2315 // true, else it is false.
2316 // Note: the const and reference restrictions are interesting,
2317 // given that const and reference members don't prevent a class
2318 // from having a trivial copy assignment operator (but do cause
2319 // errors if the copy assignment operator is actually used, q.v.
2320 // [class.copy]p12).
2321
2322 if (C.getBaseElementType(T).isConstQualified())
2323 return false;
2324 if (T->isPODType())
2325 return true;
2326 if (const RecordType *RT = T->getAs<RecordType>())
2327 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2328 return false;
2329 case UTT_HasTrivialDestructor:
2330 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2331 // If __is_pod (type) is true or type is a reference type
2332 // then the trait is true, else if type is a cv class or union
2333 // type (or array thereof) with a trivial destructor
2334 // ([class.dtor]) then the trait is true, else it is
2335 // false.
2336 if (T->isPODType() || T->isReferenceType())
2337 return true;
2338 if (const RecordType *RT =
2339 C.getBaseElementType(T)->getAs<RecordType>())
2340 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2341 return false;
2342 // TODO: Propagate nothrowness for implicitly declared special members.
2343 case UTT_HasNothrowAssign:
2344 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2345 // If type is const qualified or is a reference type then the
2346 // trait is false. Otherwise if __has_trivial_assign (type)
2347 // is true then the trait is true, else if type is a cv class
2348 // or union type with copy assignment operators that are known
2349 // not to throw an exception then the trait is true, else it is
2350 // false.
2351 if (C.getBaseElementType(T).isConstQualified())
2352 return false;
2353 if (T->isReferenceType())
2354 return false;
2355 if (T->isPODType())
2356 return true;
2357 if (const RecordType *RT = T->getAs<RecordType>()) {
2358 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2359 if (RD->hasTrivialCopyAssignment())
2360 return true;
2361
2362 bool FoundAssign = false;
2363 bool AllNoThrow = true;
2364 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redlf8aca862010-09-14 23:40:14 +00002365 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2366 Sema::LookupOrdinaryName);
2367 if (Self.LookupQualifiedName(Res, RD)) {
2368 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2369 Op != OpEnd; ++Op) {
2370 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2371 if (Operator->isCopyAssignmentOperator()) {
2372 FoundAssign = true;
2373 const FunctionProtoType *CPT
2374 = Operator->getType()->getAs<FunctionProtoType>();
2375 if (!CPT->hasEmptyExceptionSpec()) {
2376 AllNoThrow = false;
2377 break;
2378 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002379 }
2380 }
2381 }
2382
2383 return FoundAssign && AllNoThrow;
2384 }
2385 return false;
2386 case UTT_HasNothrowCopy:
2387 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2388 // If __has_trivial_copy (type) is true then the trait is true, else
2389 // if type is a cv class or union type with copy constructors that are
2390 // known not to throw an exception then the trait is true, else it is
2391 // false.
2392 if (T->isPODType() || T->isReferenceType())
2393 return true;
2394 if (const RecordType *RT = T->getAs<RecordType>()) {
2395 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2396 if (RD->hasTrivialCopyConstructor())
2397 return true;
2398
2399 bool FoundConstructor = false;
2400 bool AllNoThrow = true;
2401 unsigned FoundTQs;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002402 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl5f4e8992010-09-13 21:10:20 +00002403 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002404 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002405 // A template constructor is never a copy constructor.
2406 // FIXME: However, it may actually be selected at the actual overload
2407 // resolution point.
2408 if (isa<FunctionTemplateDecl>(*Con))
2409 continue;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002410 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2411 if (Constructor->isCopyConstructor(FoundTQs)) {
2412 FoundConstructor = true;
2413 const FunctionProtoType *CPT
2414 = Constructor->getType()->getAs<FunctionProtoType>();
Sebastian Redl751025d2010-09-13 22:02:47 +00002415 // TODO: check whether evaluating default arguments can throw.
2416 // For now, we'll be conservative and assume that they can throw.
2417 if (!CPT->hasEmptyExceptionSpec() || CPT->getNumArgs() > 1) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002418 AllNoThrow = false;
2419 break;
2420 }
2421 }
2422 }
2423
2424 return FoundConstructor && AllNoThrow;
2425 }
2426 return false;
2427 case UTT_HasNothrowConstructor:
2428 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2429 // If __has_trivial_constructor (type) is true then the trait is
2430 // true, else if type is a cv class or union type (or array
2431 // thereof) with a default constructor that is known not to
2432 // throw an exception then the trait is true, else it is false.
2433 if (T->isPODType())
2434 return true;
2435 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
2436 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2437 if (RD->hasTrivialConstructor())
2438 return true;
2439
Sebastian Redl751025d2010-09-13 22:02:47 +00002440 DeclContext::lookup_const_iterator Con, ConEnd;
2441 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2442 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002443 // FIXME: In C++0x, a constructor template can be a default constructor.
2444 if (isa<FunctionTemplateDecl>(*Con))
2445 continue;
Sebastian Redl751025d2010-09-13 22:02:47 +00002446 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2447 if (Constructor->isDefaultConstructor()) {
2448 const FunctionProtoType *CPT
2449 = Constructor->getType()->getAs<FunctionProtoType>();
2450 // TODO: check whether evaluating default arguments can throw.
2451 // For now, we'll be conservative and assume that they can throw.
2452 return CPT->hasEmptyExceptionSpec() && CPT->getNumArgs() == 0;
2453 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002454 }
2455 }
2456 return false;
2457 case UTT_HasVirtualDestructor:
2458 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2459 // If type is a class type with a virtual destructor ([class.dtor])
2460 // then the trait is true, else it is false.
2461 if (const RecordType *Record = T->getAs<RecordType>()) {
2462 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redlf8aca862010-09-14 23:40:14 +00002463 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002464 return Destructor->isVirtual();
2465 }
2466 return false;
2467 }
2468}
2469
2470ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002471 SourceLocation KWLoc,
2472 TypeSourceInfo *TSInfo,
2473 SourceLocation RParen) {
2474 QualType T = TSInfo->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002475
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002476 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
2477 // all traits except __is_class, __is_enum and __is_union require a the type
Sebastian Redl607a1782010-09-08 00:48:43 +00002478 // to be complete, an array of unknown bound, or void.
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002479 if (UTT != UTT_IsClass && UTT != UTT_IsEnum && UTT != UTT_IsUnion) {
Sebastian Redl607a1782010-09-08 00:48:43 +00002480 QualType E = T;
2481 if (T->isIncompleteArrayType())
2482 E = Context.getAsArrayType(T)->getElementType();
2483 if (!T->isVoidType() &&
2484 RequireCompleteType(KWLoc, E,
Anders Carlssond497ba72009-08-26 22:59:12 +00002485 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002486 return ExprError();
2487 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00002488
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002489 bool Value = false;
2490 if (!T->isDependentType())
Sebastian Redlf8aca862010-09-14 23:40:14 +00002491 Value = EvaluateUnaryTypeTrait(*this, UTT, T, KWLoc);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002492
2493 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002494 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00002495}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002496
Francois Pichet6ad6f282010-12-07 00:08:36 +00002497ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
2498 SourceLocation KWLoc,
2499 ParsedType LhsTy,
2500 ParsedType RhsTy,
2501 SourceLocation RParen) {
2502 TypeSourceInfo *LhsTSInfo;
2503 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
2504 if (!LhsTSInfo)
2505 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
2506
2507 TypeSourceInfo *RhsTSInfo;
2508 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
2509 if (!RhsTSInfo)
2510 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
2511
2512 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
2513}
2514
2515static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
2516 QualType LhsT, QualType RhsT,
2517 SourceLocation KeyLoc) {
2518 assert((!LhsT->isDependentType() || RhsT->isDependentType()) &&
2519 "Cannot evaluate traits for dependent types.");
2520
2521 switch(BTT) {
John McCalld89d30f2011-01-28 22:02:36 +00002522 case BTT_IsBaseOf: {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002523 // C++0x [meta.rel]p2
John McCalld89d30f2011-01-28 22:02:36 +00002524 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet6ad6f282010-12-07 00:08:36 +00002525 // Base and Derived are not unions and name the same class type without
2526 // regard to cv-qualifiers.
Francois Pichet6ad6f282010-12-07 00:08:36 +00002527
John McCalld89d30f2011-01-28 22:02:36 +00002528 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
2529 if (!lhsRecord) return false;
2530
2531 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
2532 if (!rhsRecord) return false;
2533
2534 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
2535 == (lhsRecord == rhsRecord));
2536
2537 if (lhsRecord == rhsRecord)
2538 return !lhsRecord->getDecl()->isUnion();
2539
2540 // C++0x [meta.rel]p2:
2541 // If Base and Derived are class types and are different types
2542 // (ignoring possible cv-qualifiers) then Derived shall be a
2543 // complete type.
2544 if (Self.RequireCompleteType(KeyLoc, RhsT,
2545 diag::err_incomplete_type_used_in_type_trait_expr))
2546 return false;
2547
2548 return cast<CXXRecordDecl>(rhsRecord->getDecl())
2549 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
2550 }
2551
Francois Pichetf1872372010-12-08 22:35:30 +00002552 case BTT_TypeCompatible:
2553 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
2554 RhsT.getUnqualifiedType());
Douglas Gregor9f361132011-01-27 20:28:01 +00002555
2556 case BTT_IsConvertibleTo: {
2557 // C++0x [meta.rel]p4:
2558 // Given the following function prototype:
2559 //
2560 // template <class T>
2561 // typename add_rvalue_reference<T>::type create();
2562 //
2563 // the predicate condition for a template specialization
2564 // is_convertible<From, To> shall be satisfied if and only if
2565 // the return expression in the following code would be
2566 // well-formed, including any implicit conversions to the return
2567 // type of the function:
2568 //
2569 // To test() {
2570 // return create<From>();
2571 // }
2572 //
2573 // Access checking is performed as if in a context unrelated to To and
2574 // From. Only the validity of the immediate context of the expression
2575 // of the return-statement (including conversions to the return type)
2576 // is considered.
2577 //
2578 // We model the initialization as a copy-initialization of a temporary
2579 // of the appropriate type, which for this expression is identical to the
2580 // return statement (since NRVO doesn't apply).
2581 if (LhsT->isObjectType() || LhsT->isFunctionType())
2582 LhsT = Self.Context.getRValueReferenceType(LhsT);
2583
2584 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorb608b982011-01-28 02:26:04 +00002585 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor9f361132011-01-27 20:28:01 +00002586 Expr::getValueKindForType(LhsT));
2587 Expr *FromPtr = &From;
2588 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
2589 SourceLocation()));
2590
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00002591 // Perform the initialization within a SFINAE trap at translation unit
2592 // scope.
2593 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
2594 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Douglas Gregor9f361132011-01-27 20:28:01 +00002595 InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
2596 if (Init.getKind() == InitializationSequence::FailedSequence)
2597 return false;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00002598
Douglas Gregor9f361132011-01-27 20:28:01 +00002599 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
2600 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
2601 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00002602 }
2603 llvm_unreachable("Unknown type trait or not implemented");
2604}
2605
2606ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
2607 SourceLocation KWLoc,
2608 TypeSourceInfo *LhsTSInfo,
2609 TypeSourceInfo *RhsTSInfo,
2610 SourceLocation RParen) {
2611 QualType LhsT = LhsTSInfo->getType();
2612 QualType RhsT = RhsTSInfo->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002613
John McCalld89d30f2011-01-28 22:02:36 +00002614 if (BTT == BTT_TypeCompatible) {
Francois Pichetf1872372010-12-08 22:35:30 +00002615 if (getLangOptions().CPlusPlus) {
2616 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
2617 << SourceRange(KWLoc, RParen);
2618 return ExprError();
2619 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00002620 }
2621
2622 bool Value = false;
2623 if (!LhsT->isDependentType() && !RhsT->isDependentType())
2624 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
2625
Francois Pichetf1872372010-12-08 22:35:30 +00002626 // Select trait result type.
2627 QualType ResultType;
2628 switch (BTT) {
Francois Pichetf1872372010-12-08 22:35:30 +00002629 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
2630 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
Douglas Gregor9f361132011-01-27 20:28:01 +00002631 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00002632 }
2633
Francois Pichet6ad6f282010-12-07 00:08:36 +00002634 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
2635 RhsTSInfo, Value, RParen,
Francois Pichetf1872372010-12-08 22:35:30 +00002636 ResultType));
Francois Pichet6ad6f282010-12-07 00:08:36 +00002637}
2638
John McCallf89e55a2010-11-18 06:31:45 +00002639QualType Sema::CheckPointerToMemberOperands(Expr *&lex, Expr *&rex,
2640 ExprValueKind &VK,
2641 SourceLocation Loc,
2642 bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002643 const char *OpSpelling = isIndirect ? "->*" : ".*";
2644 // C++ 5.5p2
2645 // The binary operator .* [p3: ->*] binds its second operand, which shall
2646 // be of type "pointer to member of T" (where T is a completely-defined
2647 // class type) [...]
2648 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002649 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00002650 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002651 Diag(Loc, diag::err_bad_memptr_rhs)
2652 << OpSpelling << RType << rex->getSourceRange();
2653 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00002654 }
Douglas Gregore7450f52009-03-24 19:52:54 +00002655
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002656 QualType Class(MemPtr->getClass(), 0);
2657
Douglas Gregor7d520ba2010-10-13 20:41:14 +00002658 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
2659 // member pointer points must be completely-defined. However, there is no
2660 // reason for this semantic distinction, and the rule is not enforced by
2661 // other compilers. Therefore, we do not check this property, as it is
2662 // likely to be considered a defect.
Sebastian Redl59fc2692010-04-10 10:14:54 +00002663
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002664 // C++ 5.5p2
2665 // [...] to its first operand, which shall be of class T or of a class of
2666 // which T is an unambiguous and accessible base class. [p3: a pointer to
2667 // such a class]
2668 QualType LType = lex->getType();
2669 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002670 if (const PointerType *Ptr = LType->getAs<PointerType>())
John McCallf89e55a2010-11-18 06:31:45 +00002671 LType = Ptr->getPointeeType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002672 else {
2673 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00002674 << OpSpelling << 1 << LType
Douglas Gregor849b2432010-03-31 17:46:05 +00002675 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002676 return QualType();
2677 }
2678 }
2679
Douglas Gregora4923eb2009-11-16 21:35:15 +00002680 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00002681 // If we want to check the hierarchy, we need a complete type.
2682 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
2683 << OpSpelling << (int)isIndirect)) {
2684 return QualType();
2685 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002686 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002687 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00002688 // FIXME: Would it be useful to print full ambiguity paths, or is that
2689 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002690 if (!IsDerivedFrom(LType, Class, Paths) ||
2691 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
2692 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00002693 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002694 return QualType();
2695 }
Eli Friedman3005efe2010-01-16 00:00:48 +00002696 // Cast LHS to type of use.
2697 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
John McCall5baba9d2010-08-25 10:28:54 +00002698 ExprValueKind VK =
2699 isIndirect ? VK_RValue : CastCategory(lex);
Sebastian Redl906082e2010-07-20 04:20:21 +00002700
John McCallf871d0c2010-08-07 06:22:56 +00002701 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002702 BuildBasePathArray(Paths, BasePath);
John McCall5baba9d2010-08-25 10:28:54 +00002703 ImpCastExprToType(lex, UseType, CK_DerivedToBase, VK, &BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002704 }
2705
Douglas Gregored8abf12010-07-08 06:14:04 +00002706 if (isa<CXXScalarValueInitExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00002707 // Diagnose use of pointer-to-member type which when used as
2708 // the functional cast in a pointer-to-member expression.
2709 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
2710 return QualType();
2711 }
John McCallf89e55a2010-11-18 06:31:45 +00002712
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002713 // C++ 5.5p2
2714 // The result is an object or a function of the type specified by the
2715 // second operand.
2716 // The cv qualifiers are the union of those in the pointer and the left side,
2717 // in accordance with 5.5p5 and 5.2.5.
2718 // FIXME: This returns a dereferenced member function pointer as a normal
2719 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00002720 // calling them. There's also a GCC extension to get a function pointer to the
2721 // thing, which is another complication, because this type - unlike the type
2722 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002723 // argument.
2724 // We probably need a "MemberFunctionClosureType" or something like that.
2725 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00002726 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
John McCallf89e55a2010-11-18 06:31:45 +00002727
Douglas Gregor6b4df912011-01-26 16:40:18 +00002728 // C++0x [expr.mptr.oper]p6:
2729 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002730 // ill-formed if the second operand is a pointer to member function with
2731 // ref-qualifier &. In a ->* expression or in a .* expression whose object
2732 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor6b4df912011-01-26 16:40:18 +00002733 // is a pointer to member function with ref-qualifier &&.
2734 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
2735 switch (Proto->getRefQualifier()) {
2736 case RQ_None:
2737 // Do nothing
2738 break;
2739
2740 case RQ_LValue:
2741 if (!isIndirect && !lex->Classify(Context).isLValue())
2742 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
2743 << RType << 1 << lex->getSourceRange();
2744 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002745
Douglas Gregor6b4df912011-01-26 16:40:18 +00002746 case RQ_RValue:
2747 if (isIndirect || !lex->Classify(Context).isRValue())
2748 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
2749 << RType << 0 << lex->getSourceRange();
2750 break;
2751 }
2752 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002753
John McCallf89e55a2010-11-18 06:31:45 +00002754 // C++ [expr.mptr.oper]p6:
2755 // The result of a .* expression whose second operand is a pointer
2756 // to a data member is of the same value category as its
2757 // first operand. The result of a .* expression whose second
2758 // operand is a pointer to a member function is a prvalue. The
2759 // result of an ->* expression is an lvalue if its second operand
2760 // is a pointer to data member and a prvalue otherwise.
2761 if (Result->isFunctionType())
2762 VK = VK_RValue;
2763 else if (isIndirect)
2764 VK = VK_LValue;
2765 else
2766 VK = lex->getValueKind();
2767
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002768 return Result;
2769}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002770
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002771/// \brief Try to convert a type to another according to C++0x 5.16p3.
2772///
2773/// This is part of the parameter validation for the ? operator. If either
2774/// value operand is a class type, the two operands are attempted to be
2775/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002776/// It returns true if the program is ill-formed and has already been diagnosed
2777/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002778static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
2779 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00002780 bool &HaveConversion,
2781 QualType &ToType) {
2782 HaveConversion = false;
2783 ToType = To->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002784
2785 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00002786 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002787 // C++0x 5.16p3
2788 // The process for determining whether an operand expression E1 of type T1
2789 // can be converted to match an operand expression E2 of type T2 is defined
2790 // as follows:
2791 // -- If E2 is an lvalue:
John McCall7eb0a9e2010-11-24 05:12:34 +00002792 bool ToIsLvalue = To->isLValue();
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002793 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002794 // E1 can be converted to match E2 if E1 can be implicitly converted to
2795 // type "lvalue reference to T2", subject to the constraint that in the
2796 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002797 QualType T = Self.Context.getLValueReferenceType(ToType);
2798 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002799
Douglas Gregorb70cf442010-03-26 20:14:36 +00002800 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2801 if (InitSeq.isDirectReferenceBinding()) {
2802 ToType = T;
2803 HaveConversion = true;
2804 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002805 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002806
Douglas Gregorb70cf442010-03-26 20:14:36 +00002807 if (InitSeq.isAmbiguous())
2808 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002809 }
John McCallb1bdc622010-02-25 01:37:24 +00002810
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002811 // -- If E2 is an rvalue, or if the conversion above cannot be done:
2812 // -- if E1 and E2 have class type, and the underlying class types are
2813 // the same or one is a base class of the other:
2814 QualType FTy = From->getType();
2815 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002816 const RecordType *FRec = FTy->getAs<RecordType>();
2817 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002818 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00002819 Self.IsDerivedFrom(FTy, TTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002820 if (FRec && TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00002821 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002822 // E1 can be converted to match E2 if the class of T2 is the
2823 // same type as, or a base class of, the class of T1, and
2824 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00002825 if (FRec == TRec || FDerivedFromT) {
2826 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002827 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2828 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2829 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2830 HaveConversion = true;
2831 return false;
2832 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002833
Douglas Gregorb70cf442010-03-26 20:14:36 +00002834 if (InitSeq.isAmbiguous())
2835 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002836 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002837 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002838
Douglas Gregorb70cf442010-03-26 20:14:36 +00002839 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002840 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002841
Douglas Gregorb70cf442010-03-26 20:14:36 +00002842 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2843 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002844 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002845 // an rvalue).
2846 //
2847 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2848 // to the array-to-pointer or function-to-pointer conversions.
2849 if (!TTy->getAs<TagType>())
2850 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002851
Douglas Gregorb70cf442010-03-26 20:14:36 +00002852 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2853 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002854 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002855 ToType = TTy;
2856 if (InitSeq.isAmbiguous())
2857 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2858
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002859 return false;
2860}
2861
2862/// \brief Try to find a common type for two according to C++0x 5.16p5.
2863///
2864/// This is part of the parameter validation for the ? operator. If either
2865/// value operand is a class type, overload resolution is used to find a
2866/// conversion to a common type.
2867static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2868 SourceLocation Loc) {
2869 Expr *Args[2] = { LHS, RHS };
John McCall5769d612010-02-08 23:07:23 +00002870 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor573d9c32009-10-21 23:19:44 +00002871 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002872
2873 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00002874 switch (CandidateSet.BestViableFunction(Self, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002875 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002876 // We found a match. Perform the conversions on the arguments and move on.
2877 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00002878 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002879 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00002880 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002881 break;
2882 return false;
2883
Douglas Gregor20093b42009-12-09 23:02:17 +00002884 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002885 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2886 << LHS->getType() << RHS->getType()
2887 << LHS->getSourceRange() << RHS->getSourceRange();
2888 return true;
2889
Douglas Gregor20093b42009-12-09 23:02:17 +00002890 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002891 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2892 << LHS->getType() << RHS->getType()
2893 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00002894 // FIXME: Print the possible common types by printing the return types of
2895 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002896 break;
2897
Douglas Gregor20093b42009-12-09 23:02:17 +00002898 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002899 assert(false && "Conditional operator has only built-in overloads");
2900 break;
2901 }
2902 return true;
2903}
2904
Sebastian Redl76458502009-04-17 16:30:52 +00002905/// \brief Perform an "extended" implicit conversion as returned by
2906/// TryClassUnification.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002907static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2908 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2909 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2910 SourceLocation());
2911 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
John McCallf312b1e2010-08-26 23:41:50 +00002912 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&E, 1));
Douglas Gregorb70cf442010-03-26 20:14:36 +00002913 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00002914 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002915
Douglas Gregorb70cf442010-03-26 20:14:36 +00002916 E = Result.takeAs<Expr>();
Sebastian Redl76458502009-04-17 16:30:52 +00002917 return false;
2918}
2919
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002920/// \brief Check the operands of ?: under C++ semantics.
2921///
2922/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2923/// extension. In this case, LHS == Cond. (But they're not aliases.)
2924QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
John McCallf89e55a2010-11-18 06:31:45 +00002925 Expr *&SAVE, ExprValueKind &VK,
John McCall09431682010-11-18 19:01:18 +00002926 ExprObjectKind &OK,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002927 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002928 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2929 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002930
2931 // C++0x 5.16p1
2932 // The first expression is contextually converted to bool.
2933 if (!Cond->isTypeDependent()) {
Fariborz Jahanian1fb019b2010-09-18 19:38:38 +00002934 if (SAVE && Cond->getType()->isArrayType()) {
2935 QualType CondTy = Cond->getType();
2936 CondTy = Context.getArrayDecayedType(CondTy);
2937 ImpCastExprToType(Cond, CondTy, CK_ArrayToPointerDecay);
2938 SAVE = LHS = Cond;
2939 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002940 if (CheckCXXBooleanCondition(Cond))
2941 return QualType();
2942 }
2943
John McCallf89e55a2010-11-18 06:31:45 +00002944 // Assume r-value.
2945 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00002946 OK = OK_Ordinary;
John McCallf89e55a2010-11-18 06:31:45 +00002947
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002948 // Either of the arguments dependent?
2949 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2950 return Context.DependentTy;
2951
2952 // C++0x 5.16p2
2953 // If either the second or the third operand has type (cv) void, ...
2954 QualType LTy = LHS->getType();
2955 QualType RTy = RHS->getType();
2956 bool LVoid = LTy->isVoidType();
2957 bool RVoid = RTy->isVoidType();
2958 if (LVoid || RVoid) {
2959 // ... then the [l2r] conversions are performed on the second and third
2960 // operands ...
Douglas Gregora873dfc2010-02-03 00:27:59 +00002961 DefaultFunctionArrayLvalueConversion(LHS);
2962 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002963 LTy = LHS->getType();
2964 RTy = RHS->getType();
2965
2966 // ... and one of the following shall hold:
2967 // -- The second or the third operand (but not both) is a throw-
2968 // expression; the result is of the type of the other and is an rvalue.
2969 bool LThrow = isa<CXXThrowExpr>(LHS);
2970 bool RThrow = isa<CXXThrowExpr>(RHS);
2971 if (LThrow && !RThrow)
2972 return RTy;
2973 if (RThrow && !LThrow)
2974 return LTy;
2975
2976 // -- Both the second and third operands have type void; the result is of
2977 // type void and is an rvalue.
2978 if (LVoid && RVoid)
2979 return Context.VoidTy;
2980
2981 // Neither holds, error.
2982 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2983 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2984 << LHS->getSourceRange() << RHS->getSourceRange();
2985 return QualType();
2986 }
2987
2988 // Neither is void.
2989
2990 // C++0x 5.16p3
2991 // Otherwise, if the second and third operand have different types, and
2992 // either has (cv) class type, and attempt is made to convert each of those
2993 // operands to the other.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002994 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002995 (LTy->isRecordType() || RTy->isRecordType())) {
2996 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2997 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002998 QualType L2RType, R2LType;
2999 bool HaveL2R, HaveR2L;
3000 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003001 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00003002 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003003 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003004
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003005 // If both can be converted, [...] the program is ill-formed.
3006 if (HaveL2R && HaveR2L) {
3007 Diag(QuestionLoc, diag::err_conditional_ambiguous)
3008 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
3009 return QualType();
3010 }
3011
3012 // If exactly one conversion is possible, that conversion is applied to
3013 // the chosen operand and the converted operands are used in place of the
3014 // original operands for the remainder of this section.
3015 if (HaveL2R) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003016 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003017 return QualType();
3018 LTy = LHS->getType();
3019 } else if (HaveR2L) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003020 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003021 return QualType();
3022 RTy = RHS->getType();
3023 }
3024 }
3025
3026 // C++0x 5.16p4
John McCallf89e55a2010-11-18 06:31:45 +00003027 // If the second and third operands are glvalues of the same value
3028 // category and have the same type, the result is of that type and
3029 // value category and it is a bit-field if the second or the third
3030 // operand is a bit-field, or if both are bit-fields.
John McCall09431682010-11-18 19:01:18 +00003031 // We only extend this to bitfields, not to the crazy other kinds of
3032 // l-values.
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003033 bool Same = Context.hasSameType(LTy, RTy);
John McCallf89e55a2010-11-18 06:31:45 +00003034 if (Same &&
3035 LHS->getValueKind() != VK_RValue &&
3036 LHS->getValueKind() == RHS->getValueKind() &&
John McCall09431682010-11-18 19:01:18 +00003037 (LHS->getObjectKind() == OK_Ordinary ||
3038 LHS->getObjectKind() == OK_BitField) &&
3039 (RHS->getObjectKind() == OK_Ordinary ||
3040 RHS->getObjectKind() == OK_BitField)) {
John McCallf89e55a2010-11-18 06:31:45 +00003041 VK = LHS->getValueKind();
John McCall09431682010-11-18 19:01:18 +00003042 if (LHS->getObjectKind() == OK_BitField ||
3043 RHS->getObjectKind() == OK_BitField)
3044 OK = OK_BitField;
John McCallf89e55a2010-11-18 06:31:45 +00003045 return LTy;
Fariborz Jahanian3911a1a2010-09-25 01:08:05 +00003046 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003047
3048 // C++0x 5.16p5
3049 // Otherwise, the result is an rvalue. If the second and third operands
3050 // do not have the same type, and either has (cv) class type, ...
3051 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
3052 // ... overload resolution is used to determine the conversions (if any)
3053 // to be applied to the operands. If the overload resolution fails, the
3054 // program is ill-formed.
3055 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
3056 return QualType();
3057 }
3058
3059 // C++0x 5.16p6
3060 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
3061 // conversions are performed on the second and third operands.
Douglas Gregora873dfc2010-02-03 00:27:59 +00003062 DefaultFunctionArrayLvalueConversion(LHS);
3063 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003064 LTy = LHS->getType();
3065 RTy = RHS->getType();
3066
3067 // After those conversions, one of the following shall hold:
3068 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00003069 // is of that type. If the operands have class type, the result
3070 // is a prvalue temporary of the result type, which is
3071 // copy-initialized from either the second operand or the third
3072 // operand depending on the value of the first operand.
3073 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
3074 if (LTy->isRecordType()) {
3075 // The operands have class type. Make a temporary copy.
3076 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003077 ExprResult LHSCopy = PerformCopyInitialization(Entity,
3078 SourceLocation(),
John McCallf6a16482010-12-04 03:47:34 +00003079 Owned(LHS));
Douglas Gregorb65a4582010-05-19 23:40:50 +00003080 if (LHSCopy.isInvalid())
3081 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003082
3083 ExprResult RHSCopy = PerformCopyInitialization(Entity,
3084 SourceLocation(),
John McCallf6a16482010-12-04 03:47:34 +00003085 Owned(RHS));
Douglas Gregorb65a4582010-05-19 23:40:50 +00003086 if (RHSCopy.isInvalid())
3087 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003088
Douglas Gregorb65a4582010-05-19 23:40:50 +00003089 LHS = LHSCopy.takeAs<Expr>();
3090 RHS = RHSCopy.takeAs<Expr>();
3091 }
3092
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003093 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00003094 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003095
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003096 // Extension: conditional operator involving vector types.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003097 if (LTy->isVectorType() || RTy->isVectorType())
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003098 return CheckVectorOperands(QuestionLoc, LHS, RHS);
3099
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003100 // -- The second and third operands have arithmetic or enumeration type;
3101 // the usual arithmetic conversions are performed to bring them to a
3102 // common type, and the result is of that type.
3103 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
3104 UsualArithmeticConversions(LHS, RHS);
3105 return LHS->getType();
3106 }
3107
3108 // -- The second and third operands have pointer type, or one has pointer
3109 // type and the other is a null pointer constant; pointer conversions
3110 // and qualification conversions are performed to bring them to their
3111 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00003112 // -- The second and third operands have pointer to member type, or one has
3113 // pointer to member type and the other is a null pointer constant;
3114 // pointer to member conversions and qualification conversions are
3115 // performed to bring them to a common type, whose cv-qualification
3116 // shall match the cv-qualification of either the second or the third
3117 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003118 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003119 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003120 isSFINAEContext()? 0 : &NonStandardCompositeType);
3121 if (!Composite.isNull()) {
3122 if (NonStandardCompositeType)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003123 Diag(QuestionLoc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003124 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
3125 << LTy << RTy << Composite
3126 << LHS->getSourceRange() << RHS->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003127
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003128 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003129 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003130
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003131 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00003132 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
3133 if (!Composite.isNull())
3134 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003135
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003136 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3137 << LHS->getType() << RHS->getType()
3138 << LHS->getSourceRange() << RHS->getSourceRange();
3139 return QualType();
3140}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003141
3142/// \brief Find a merged pointer type and convert the two expressions to it.
3143///
Douglas Gregor20b3e992009-08-24 17:42:35 +00003144/// This finds the composite pointer type (or member pointer type) for @p E1
3145/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
3146/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003147/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003148///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003149/// \param Loc The location of the operator requiring these two expressions to
3150/// be converted to the composite pointer type.
3151///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003152/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
3153/// a non-standard (but still sane) composite type to which both expressions
3154/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
3155/// will be set true.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003156QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003157 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003158 bool *NonStandardCompositeType) {
3159 if (NonStandardCompositeType)
3160 *NonStandardCompositeType = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003161
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003162 assert(getLangOptions().CPlusPlus && "This function assumes C++");
3163 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003164
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00003165 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
3166 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00003167 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003168
3169 // C++0x 5.9p2
3170 // Pointer conversions and qualification conversions are performed on
3171 // pointer operands to bring them to their composite pointer type. If
3172 // one operand is a null pointer constant, the composite pointer type is
3173 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00003174 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003175 if (T2->isMemberPointerType())
John McCall2de56d12010-08-25 11:45:40 +00003176 ImpCastExprToType(E1, T2, CK_NullToMemberPointer);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003177 else
John McCall404cd162010-11-13 01:35:44 +00003178 ImpCastExprToType(E1, T2, CK_NullToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003179 return T2;
3180 }
Douglas Gregorce940492009-09-25 04:25:58 +00003181 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003182 if (T1->isMemberPointerType())
John McCall2de56d12010-08-25 11:45:40 +00003183 ImpCastExprToType(E2, T1, CK_NullToMemberPointer);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003184 else
John McCall404cd162010-11-13 01:35:44 +00003185 ImpCastExprToType(E2, T1, CK_NullToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003186 return T1;
3187 }
Mike Stump1eb44332009-09-09 15:08:12 +00003188
Douglas Gregor20b3e992009-08-24 17:42:35 +00003189 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003190 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
3191 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003192 return QualType();
3193
3194 // Otherwise, of one of the operands has type "pointer to cv1 void," then
3195 // the other has type "pointer to cv2 T" and the composite pointer type is
3196 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
3197 // Otherwise, the composite pointer type is a pointer type similar to the
3198 // type of one of the operands, with a cv-qualification signature that is
3199 // the union of the cv-qualification signatures of the operand types.
3200 // In practice, the first part here is redundant; it's subsumed by the second.
3201 // What we do here is, we build the two possible composite types, and try the
3202 // conversions in both directions. If only one works, or if the two composite
3203 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00003204 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00003205 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
3206 QualifierVector QualifierUnion;
3207 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
3208 ContainingClassVector;
3209 ContainingClassVector MemberOfClass;
3210 QualType Composite1 = Context.getCanonicalType(T1),
3211 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003212 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00003213 do {
3214 const PointerType *Ptr1, *Ptr2;
3215 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3216 (Ptr2 = Composite2->getAs<PointerType>())) {
3217 Composite1 = Ptr1->getPointeeType();
3218 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003219
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003220 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003221 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003222 if (NonStandardCompositeType &&
3223 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3224 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003225
Douglas Gregor20b3e992009-08-24 17:42:35 +00003226 QualifierUnion.push_back(
3227 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3228 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3229 continue;
3230 }
Mike Stump1eb44332009-09-09 15:08:12 +00003231
Douglas Gregor20b3e992009-08-24 17:42:35 +00003232 const MemberPointerType *MemPtr1, *MemPtr2;
3233 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3234 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3235 Composite1 = MemPtr1->getPointeeType();
3236 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003237
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003238 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003239 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003240 if (NonStandardCompositeType &&
3241 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3242 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003243
Douglas Gregor20b3e992009-08-24 17:42:35 +00003244 QualifierUnion.push_back(
3245 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3246 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
3247 MemPtr2->getClass()));
3248 continue;
3249 }
Mike Stump1eb44332009-09-09 15:08:12 +00003250
Douglas Gregor20b3e992009-08-24 17:42:35 +00003251 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00003252
Douglas Gregor20b3e992009-08-24 17:42:35 +00003253 // Cannot unwrap any more types.
3254 break;
3255 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00003256
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003257 if (NeedConstBefore && NonStandardCompositeType) {
3258 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003259 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003260 // requirements of C++ [conv.qual]p4 bullet 3.
3261 for (unsigned I = 0; I != NeedConstBefore; ++I) {
3262 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
3263 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
3264 *NonStandardCompositeType = true;
3265 }
3266 }
3267 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003268
Douglas Gregor20b3e992009-08-24 17:42:35 +00003269 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003270 ContainingClassVector::reverse_iterator MOC
3271 = MemberOfClass.rbegin();
3272 for (QualifierVector::reverse_iterator
3273 I = QualifierUnion.rbegin(),
3274 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00003275 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00003276 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00003277 if (MOC->first && MOC->second) {
3278 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00003279 Composite1 = Context.getMemberPointerType(
3280 Context.getQualifiedType(Composite1, Quals),
3281 MOC->first);
3282 Composite2 = Context.getMemberPointerType(
3283 Context.getQualifiedType(Composite2, Quals),
3284 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00003285 } else {
3286 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00003287 Composite1
3288 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
3289 Composite2
3290 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00003291 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003292 }
3293
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003294 // Try to convert to the first composite pointer type.
3295 InitializedEntity Entity1
3296 = InitializedEntity::InitializeTemporary(Composite1);
3297 InitializationKind Kind
3298 = InitializationKind::CreateCopy(Loc, SourceLocation());
3299 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
3300 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00003301
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003302 if (E1ToC1 && E2ToC1) {
3303 // Conversion to Composite1 is viable.
3304 if (!Context.hasSameType(Composite1, Composite2)) {
3305 // Composite2 is a different type from Composite1. Check whether
3306 // Composite2 is also viable.
3307 InitializedEntity Entity2
3308 = InitializedEntity::InitializeTemporary(Composite2);
3309 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3310 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3311 if (E1ToC2 && E2ToC2) {
3312 // Both Composite1 and Composite2 are viable and are different;
3313 // this is an ambiguity.
3314 return QualType();
3315 }
3316 }
3317
3318 // Convert E1 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00003319 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00003320 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003321 if (E1Result.isInvalid())
3322 return QualType();
3323 E1 = E1Result.takeAs<Expr>();
3324
3325 // Convert E2 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00003326 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00003327 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003328 if (E2Result.isInvalid())
3329 return QualType();
3330 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003331
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003332 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003333 }
3334
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003335 // Check whether Composite2 is viable.
3336 InitializedEntity Entity2
3337 = InitializedEntity::InitializeTemporary(Composite2);
3338 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3339 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3340 if (!E1ToC2 || !E2ToC2)
3341 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003342
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003343 // Convert E1 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00003344 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00003345 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003346 if (E1Result.isInvalid())
3347 return QualType();
3348 E1 = E1Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003349
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003350 // Convert E2 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00003351 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00003352 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003353 if (E2Result.isInvalid())
3354 return QualType();
3355 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003356
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003357 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003358}
Anders Carlsson165a0a02009-05-17 18:41:29 +00003359
John McCall60d7b3a2010-08-24 06:29:42 +00003360ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor19cc1c72010-11-01 21:10:29 +00003361 if (!E)
3362 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003363
Anders Carlsson089c2602009-08-15 23:41:35 +00003364 if (!Context.getLangOptions().CPlusPlus)
3365 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003366
Douglas Gregor51326552009-12-24 18:51:59 +00003367 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
3368
Ted Kremenek6217b802009-07-29 21:53:49 +00003369 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00003370 if (!RT)
3371 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003372
Douglas Gregor5e6fcd42011-02-08 02:14:35 +00003373 // If the result is a glvalue, we shouldn't bind it.
3374 if (E->Classify(Context).isGLValue())
3375 return Owned(E);
John McCall86ff3082010-02-04 22:26:26 +00003376
3377 // That should be enough to guarantee that this type is complete.
3378 // If it has a trivial destructor, we can avoid the extra copy.
Jeffrey Yasskinb7ee2e52011-01-27 19:17:54 +00003379 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall507384f2010-08-12 02:40:37 +00003380 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall86ff3082010-02-04 22:26:26 +00003381 return Owned(E);
3382
Douglas Gregordb89f282010-07-01 22:47:18 +00003383 CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD));
Anders Carlsson860306e2009-05-30 21:21:49 +00003384 ExprTemporaries.push_back(Temp);
Douglas Gregordb89f282010-07-01 22:47:18 +00003385 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003386 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00003387 CheckDestructorAccess(E->getExprLoc(), Destructor,
3388 PDiag(diag::err_access_dtor_temp)
3389 << E->getType());
3390 }
Anders Carlssondef11992009-05-30 20:36:53 +00003391 // FIXME: Add the temporary to the temporaries vector.
3392 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
3393}
3394
John McCall4765fa02010-12-06 08:20:24 +00003395Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003396 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00003397
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00003398 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3399 assert(ExprTemporaries.size() >= FirstTemporary);
3400 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003401 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003402
John McCall4765fa02010-12-06 08:20:24 +00003403 Expr *E = ExprWithCleanups::Create(Context, SubExpr,
3404 &ExprTemporaries[FirstTemporary],
3405 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00003406 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
3407 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00003408
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003409 return E;
3410}
3411
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003412ExprResult
John McCall4765fa02010-12-06 08:20:24 +00003413Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregor90f93822009-12-22 22:17:25 +00003414 if (SubExpr.isInvalid())
3415 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003416
John McCall4765fa02010-12-06 08:20:24 +00003417 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregor90f93822009-12-22 22:17:25 +00003418}
3419
John McCall4765fa02010-12-06 08:20:24 +00003420Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003421 assert(SubStmt && "sub statement can't be null!");
3422
3423 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3424 assert(ExprTemporaries.size() >= FirstTemporary);
3425 if (ExprTemporaries.size() == FirstTemporary)
3426 return SubStmt;
3427
3428 // FIXME: In order to attach the temporaries, wrap the statement into
3429 // a StmtExpr; currently this is only used for asm statements.
3430 // This is hacky, either create a new CXXStmtWithTemporaries statement or
3431 // a new AsmStmtWithTemporaries.
3432 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
3433 SourceLocation(),
3434 SourceLocation());
3435 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
3436 SourceLocation());
John McCall4765fa02010-12-06 08:20:24 +00003437 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003438}
3439
John McCall60d7b3a2010-08-24 06:29:42 +00003440ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003441Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallb3d87482010-08-24 05:47:05 +00003442 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00003443 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003444 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003445 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003446 if (Result.isInvalid()) return ExprError();
3447 Base = Result.get();
Mike Stump1eb44332009-09-09 15:08:12 +00003448
John McCall9ae2f072010-08-23 23:25:46 +00003449 QualType BaseType = Base->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00003450 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003451 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00003452 // If we have a pointer to a dependent type and are using the -> operator,
3453 // the object type is the type that the pointer points to. We might still
3454 // have enough information about that type to do something useful.
3455 if (OpKind == tok::arrow)
3456 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3457 BaseType = Ptr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003458
John McCallb3d87482010-08-24 05:47:05 +00003459 ObjectType = ParsedType::make(BaseType);
Douglas Gregord4dca082010-02-24 18:44:31 +00003460 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00003461 return Owned(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003462 }
Mike Stump1eb44332009-09-09 15:08:12 +00003463
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003464 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00003465 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003466 // returned, with the original second operand.
3467 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00003468 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00003469 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00003470 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00003471 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003472
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003473 while (BaseType->isRecordType()) {
John McCall9ae2f072010-08-23 23:25:46 +00003474 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
3475 if (Result.isInvalid())
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003476 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00003477 Base = Result.get();
3478 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonde699e52009-10-13 22:55:59 +00003479 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCall9ae2f072010-08-23 23:25:46 +00003480 BaseType = Base->getType();
John McCallc4e83212009-09-30 01:01:30 +00003481 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00003482 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00003483 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00003484 for (unsigned i = 0; i < Locations.size(); i++)
3485 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00003486 return ExprError();
3487 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003488 }
Mike Stump1eb44332009-09-09 15:08:12 +00003489
Douglas Gregor31658df2009-11-20 19:58:21 +00003490 if (BaseType->isPointerType())
3491 BaseType = BaseType->getPointeeType();
3492 }
Mike Stump1eb44332009-09-09 15:08:12 +00003493
3494 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003495 // vector types or Objective-C interfaces. Just return early and let
3496 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00003497 if (!BaseType->isRecordType()) {
3498 // C++ [basic.lookup.classref]p2:
3499 // [...] If the type of the object expression is of pointer to scalar
3500 // type, the unqualified-id is looked up in the context of the complete
3501 // postfix-expression.
Douglas Gregord4dca082010-02-24 18:44:31 +00003502 //
3503 // This also indicates that we should be parsing a
3504 // pseudo-destructor-name.
John McCallb3d87482010-08-24 05:47:05 +00003505 ObjectType = ParsedType();
Douglas Gregord4dca082010-02-24 18:44:31 +00003506 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00003507 return Owned(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00003508 }
Mike Stump1eb44332009-09-09 15:08:12 +00003509
Douglas Gregor03c57052009-11-17 05:17:33 +00003510 // The object type must be complete (or dependent).
3511 if (!BaseType->isDependentType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003512 RequireCompleteType(OpLoc, BaseType,
Douglas Gregor03c57052009-11-17 05:17:33 +00003513 PDiag(diag::err_incomplete_member_access)))
3514 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003515
Douglas Gregorc68afe22009-09-03 21:38:09 +00003516 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00003517 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00003518 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00003519 // type C (or of pointer to a class type C), the unqualified-id is looked
3520 // up in the scope of class C. [...]
John McCallb3d87482010-08-24 05:47:05 +00003521 ObjectType = ParsedType::make(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00003522 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003523}
3524
John McCall60d7b3a2010-08-24 06:29:42 +00003525ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003526 Expr *MemExpr) {
Douglas Gregor77549082010-02-24 21:29:12 +00003527 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCall9ae2f072010-08-23 23:25:46 +00003528 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
3529 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregor849b2432010-03-31 17:46:05 +00003530 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003531
Douglas Gregor77549082010-02-24 21:29:12 +00003532 return ActOnCallExpr(/*Scope*/ 0,
John McCall9ae2f072010-08-23 23:25:46 +00003533 MemExpr,
Douglas Gregor77549082010-02-24 21:29:12 +00003534 /*LPLoc*/ ExpectedLParenLoc,
John McCallf312b1e2010-08-26 23:41:50 +00003535 MultiExprArg(),
Douglas Gregor77549082010-02-24 21:29:12 +00003536 /*RPLoc*/ ExpectedLParenLoc);
3537}
Douglas Gregord4dca082010-02-24 18:44:31 +00003538
John McCall60d7b3a2010-08-24 06:29:42 +00003539ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003540 SourceLocation OpLoc,
3541 tok::TokenKind OpKind,
3542 const CXXScopeSpec &SS,
Douglas Gregor26d4ac92010-02-24 23:40:28 +00003543 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003544 SourceLocation CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00003545 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003546 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003547 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003548 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003549
Douglas Gregorb57fb492010-02-24 22:38:50 +00003550 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003551 // The left-hand side of the dot operator shall be of scalar type. The
Douglas Gregorb57fb492010-02-24 22:38:50 +00003552 // left-hand side of the arrow operator shall be of pointer to scalar type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003553 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00003554 QualType ObjectType = Base->getType();
Douglas Gregorb57fb492010-02-24 22:38:50 +00003555 if (OpKind == tok::arrow) {
3556 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3557 ObjectType = Ptr->getPointeeType();
John McCall9ae2f072010-08-23 23:25:46 +00003558 } else if (!Base->isTypeDependent()) {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003559 // The user wrote "p->" when she probably meant "p."; fix it.
3560 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3561 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00003562 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb57fb492010-02-24 22:38:50 +00003563 if (isSFINAEContext())
3564 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003565
Douglas Gregorb57fb492010-02-24 22:38:50 +00003566 OpKind = tok::period;
3567 }
3568 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003569
Douglas Gregorb57fb492010-02-24 22:38:50 +00003570 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
3571 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
John McCall9ae2f072010-08-23 23:25:46 +00003572 << ObjectType << Base->getSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00003573 return ExprError();
3574 }
3575
3576 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003577 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb57fb492010-02-24 22:38:50 +00003578 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003579 if (DestructedTypeInfo) {
3580 QualType DestructedType = DestructedTypeInfo->getType();
3581 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003582 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003583 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
3584 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
3585 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00003586 << ObjectType << DestructedType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003587 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003588
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003589 // Recover by setting the destructed type to the object type.
3590 DestructedType = ObjectType;
3591 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
3592 DestructedTypeStart);
3593 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3594 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00003595 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003596
Douglas Gregorb57fb492010-02-24 22:38:50 +00003597 // C++ [expr.pseudo]p2:
3598 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
3599 // form
3600 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003601 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb57fb492010-02-24 22:38:50 +00003602 //
3603 // shall designate the same scalar type.
3604 if (ScopeTypeInfo) {
3605 QualType ScopeType = ScopeTypeInfo->getType();
3606 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00003607 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003608
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003609 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00003610 diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00003611 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003612 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003613
Douglas Gregorb57fb492010-02-24 22:38:50 +00003614 ScopeType = QualType();
3615 ScopeTypeInfo = 0;
3616 }
3617 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003618
John McCall9ae2f072010-08-23 23:25:46 +00003619 Expr *Result
3620 = new (Context) CXXPseudoDestructorExpr(Context, Base,
3621 OpKind == tok::arrow, OpLoc,
3622 SS.getScopeRep(), SS.getRange(),
3623 ScopeTypeInfo,
3624 CCLoc,
3625 TildeLoc,
3626 Destructed);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003627
Douglas Gregorb57fb492010-02-24 22:38:50 +00003628 if (HasTrailingLParen)
John McCall9ae2f072010-08-23 23:25:46 +00003629 return Owned(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003630
John McCall9ae2f072010-08-23 23:25:46 +00003631 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor77549082010-02-24 21:29:12 +00003632}
3633
John McCall60d7b3a2010-08-24 06:29:42 +00003634ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
Douglas Gregor77549082010-02-24 21:29:12 +00003635 SourceLocation OpLoc,
3636 tok::TokenKind OpKind,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003637 CXXScopeSpec &SS,
Douglas Gregor77549082010-02-24 21:29:12 +00003638 UnqualifiedId &FirstTypeName,
3639 SourceLocation CCLoc,
3640 SourceLocation TildeLoc,
3641 UnqualifiedId &SecondTypeName,
3642 bool HasTrailingLParen) {
3643 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3644 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3645 "Invalid first type name in pseudo-destructor");
3646 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3647 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3648 "Invalid second type name in pseudo-destructor");
3649
Douglas Gregor77549082010-02-24 21:29:12 +00003650 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003651 // The left-hand side of the dot operator shall be of scalar type. The
Douglas Gregor77549082010-02-24 21:29:12 +00003652 // left-hand side of the arrow operator shall be of pointer to scalar type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003653 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00003654 QualType ObjectType = Base->getType();
Douglas Gregor77549082010-02-24 21:29:12 +00003655 if (OpKind == tok::arrow) {
3656 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3657 ObjectType = Ptr->getPointeeType();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003658 } else if (!ObjectType->isDependentType()) {
Douglas Gregor77549082010-02-24 21:29:12 +00003659 // The user wrote "p->" when she probably meant "p."; fix it.
3660 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003661 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00003662 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor77549082010-02-24 21:29:12 +00003663 if (isSFINAEContext())
3664 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003665
Douglas Gregor77549082010-02-24 21:29:12 +00003666 OpKind = tok::period;
3667 }
3668 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003669
3670 // Compute the object type that we should use for name lookup purposes. Only
3671 // record types and dependent types matter.
John McCallb3d87482010-08-24 05:47:05 +00003672 ParsedType ObjectTypePtrForLookup;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003673 if (!SS.isSet()) {
John McCallb3d87482010-08-24 05:47:05 +00003674 if (const Type *T = ObjectType->getAs<RecordType>())
3675 ObjectTypePtrForLookup = ParsedType::make(QualType(T, 0));
3676 else if (ObjectType->isDependentType())
3677 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003678 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003679
3680 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb57fb492010-02-24 22:38:50 +00003681 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00003682 QualType DestructedType;
3683 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003684 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00003685 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003686 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00003687 SecondTypeName.StartLocation,
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +00003688 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003689 if (!T &&
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003690 ((SS.isSet() && !computeDeclContext(SS, false)) ||
3691 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003692 // The name of the type being destroyed is a dependent name, and we
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003693 // couldn't find anything useful in scope. Just store the identifier and
3694 // it's location, and we'll perform (qualified) name lookup again at
3695 // template instantiation time.
3696 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
3697 SecondTypeName.StartLocation);
3698 } else if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003699 Diag(SecondTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00003700 diag::err_pseudo_dtor_destructor_non_type)
3701 << SecondTypeName.Identifier << ObjectType;
3702 if (isSFINAEContext())
3703 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003704
Douglas Gregor77549082010-02-24 21:29:12 +00003705 // Recover by assuming we had the right type all along.
3706 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003707 } else
Douglas Gregor77549082010-02-24 21:29:12 +00003708 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003709 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003710 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00003711 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003712 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3713 TemplateId->getTemplateArgs(),
3714 TemplateId->NumArgs);
John McCall2b5289b2010-08-23 07:28:44 +00003715 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003716 TemplateId->TemplateNameLoc,
3717 TemplateId->LAngleLoc,
3718 TemplateArgsPtr,
3719 TemplateId->RAngleLoc);
3720 if (T.isInvalid() || !T.get()) {
3721 // Recover by assuming we had the right type all along.
3722 DestructedType = ObjectType;
3723 } else
3724 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003725 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003726
3727 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb57fb492010-02-24 22:38:50 +00003728 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003729 if (!DestructedType.isNull()) {
3730 if (!DestructedTypeInfo)
3731 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003732 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003733 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3734 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003735
Douglas Gregorb57fb492010-02-24 22:38:50 +00003736 // Convert the name of the scope type (the type prior to '::') into a type.
3737 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00003738 QualType ScopeType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003739 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor77549082010-02-24 21:29:12 +00003740 FirstTypeName.Identifier) {
3741 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003742 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00003743 FirstTypeName.StartLocation,
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +00003744 S, &SS, false, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00003745 if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003746 Diag(FirstTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00003747 diag::err_pseudo_dtor_destructor_non_type)
3748 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003749
Douglas Gregorb57fb492010-02-24 22:38:50 +00003750 if (isSFINAEContext())
3751 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003752
Douglas Gregorb57fb492010-02-24 22:38:50 +00003753 // Just drop this type. It's unnecessary anyway.
3754 ScopeType = QualType();
3755 } else
3756 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003757 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003758 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00003759 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003760 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3761 TemplateId->getTemplateArgs(),
3762 TemplateId->NumArgs);
John McCall2b5289b2010-08-23 07:28:44 +00003763 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003764 TemplateId->TemplateNameLoc,
3765 TemplateId->LAngleLoc,
3766 TemplateArgsPtr,
3767 TemplateId->RAngleLoc);
3768 if (T.isInvalid() || !T.get()) {
3769 // Recover by dropping this type.
3770 ScopeType = QualType();
3771 } else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003772 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003773 }
3774 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003775
Douglas Gregorb4a418f2010-02-24 23:02:30 +00003776 if (!ScopeType.isNull() && !ScopeTypeInfo)
3777 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
3778 FirstTypeName.StartLocation);
3779
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003780
John McCall9ae2f072010-08-23 23:25:46 +00003781 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00003782 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003783 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00003784}
3785
Douglas Gregorf2ae5262011-01-20 00:18:04 +00003786ExprResult Sema::BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
3787 CXXMethodDecl *Method) {
John McCall6bb80172010-03-30 21:47:33 +00003788 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
3789 FoundDecl, Method))
Douglas Gregorf2ae5262011-01-20 00:18:04 +00003790 return true;
Eli Friedman772fffa2009-12-09 04:53:56 +00003791
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003792 MemberExpr *ME =
Abramo Bagnara25777432010-08-11 22:01:17 +00003793 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
John McCallf89e55a2010-11-18 06:31:45 +00003794 SourceLocation(), Method->getType(),
3795 VK_RValue, OK_Ordinary);
3796 QualType ResultType = Method->getResultType();
3797 ExprValueKind VK = Expr::getValueKindForType(ResultType);
3798 ResultType = ResultType.getNonLValueExprType(Context);
3799
Douglas Gregor7edfb692009-11-23 12:27:39 +00003800 MarkDeclarationReferenced(Exp->getLocStart(), Method);
3801 CXXMemberCallExpr *CE =
John McCallf89e55a2010-11-18 06:31:45 +00003802 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
Douglas Gregor7edfb692009-11-23 12:27:39 +00003803 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003804 return CE;
3805}
3806
Sebastian Redl2e156222010-09-10 20:55:43 +00003807ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
3808 SourceLocation RParen) {
Sebastian Redl2e156222010-09-10 20:55:43 +00003809 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
3810 Operand->CanThrow(Context),
3811 KeyLoc, RParen));
3812}
3813
3814ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
3815 Expr *Operand, SourceLocation RParen) {
3816 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl02bc21a2010-09-10 20:55:37 +00003817}
3818
John McCallf6a16482010-12-04 03:47:34 +00003819/// Perform the conversions required for an expression used in a
3820/// context that ignores the result.
3821void Sema::IgnoredValueConversions(Expr *&E) {
John McCalla878cda2010-12-02 02:07:15 +00003822 // C99 6.3.2.1:
3823 // [Except in specific positions,] an lvalue that does not have
3824 // array type is converted to the value stored in the
3825 // designated object (and is no longer an lvalue).
John McCallf6a16482010-12-04 03:47:34 +00003826 if (E->isRValue()) return;
John McCalla878cda2010-12-02 02:07:15 +00003827
John McCallf6a16482010-12-04 03:47:34 +00003828 // We always want to do this on ObjC property references.
3829 if (E->getObjectKind() == OK_ObjCProperty) {
3830 ConvertPropertyForRValue(E);
3831 if (E->isRValue()) return;
3832 }
3833
3834 // Otherwise, this rule does not apply in C++, at least not for the moment.
3835 if (getLangOptions().CPlusPlus) return;
3836
3837 // GCC seems to also exclude expressions of incomplete enum type.
3838 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
3839 if (!T->getDecl()->isComplete()) {
3840 // FIXME: stupid workaround for a codegen bug!
3841 ImpCastExprToType(E, Context.VoidTy, CK_ToVoid);
3842 return;
3843 }
3844 }
3845
3846 DefaultFunctionArrayLvalueConversion(E);
John McCall85515d62010-12-04 12:29:11 +00003847 if (!E->getType()->isVoidType())
3848 RequireCompleteType(E->getExprLoc(), E->getType(),
3849 diag::err_incomplete_type);
John McCallf6a16482010-12-04 03:47:34 +00003850}
3851
3852ExprResult Sema::ActOnFinishFullExpr(Expr *FullExpr) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003853 if (!FullExpr)
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003854 return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00003855
Douglas Gregord0937222010-12-13 22:49:22 +00003856 if (DiagnoseUnexpandedParameterPack(FullExpr))
3857 return ExprError();
3858
John McCallf6a16482010-12-04 03:47:34 +00003859 IgnoredValueConversions(FullExpr);
John McCallb4eb64d2010-10-08 02:01:28 +00003860 CheckImplicitConversions(FullExpr);
John McCall4765fa02010-12-06 08:20:24 +00003861 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson165a0a02009-05-17 18:41:29 +00003862}
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003863
3864StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
3865 if (!FullStmt) return StmtError();
3866
John McCall4765fa02010-12-06 08:20:24 +00003867 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003868}