blob: f9c2c9a62ea3c312322dbe2ffc7aabff59a64ae3 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall2a7fb272010-08-25 05:32:35 +000015#include "clang/Sema/DeclSpec.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
John McCall2a7fb272010-08-25 05:32:35 +000018#include "clang/Sema/ParsedTemplate.h"
John McCall469a1eb2011-02-02 13:00:07 +000019#include "clang/Sema/ScopeInfo.h"
John McCall2a7fb272010-08-25 05:32:35 +000020#include "clang/Sema/TemplateDeduction.h"
Steve Naroff210679c2007-08-25 14:02:58 +000021#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000024#include "clang/AST/ExprCXX.h"
Fariborz Jahaniand4266622010-06-16 18:56:04 +000025#include "clang/AST/ExprObjC.h"
Douglas Gregorb57fb492010-02-24 22:38:50 +000026#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000027#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000028#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000029#include "clang/Lex/Preprocessor.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000030#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000031using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000032using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000033
John McCallb3d87482010-08-24 05:47:05 +000034ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000035 IdentifierInfo &II,
John McCallb3d87482010-08-24 05:47:05 +000036 SourceLocation NameLoc,
37 Scope *S, CXXScopeSpec &SS,
38 ParsedType ObjectTypePtr,
39 bool EnteringContext) {
Douglas Gregor124b8782010-02-16 19:09:40 +000040 // Determine where to perform name lookup.
41
42 // FIXME: This area of the standard is very messy, and the current
43 // wording is rather unclear about which scopes we search for the
44 // destructor name; see core issues 399 and 555. Issue 399 in
45 // particular shows where the current description of destructor name
46 // lookup is completely out of line with existing practice, e.g.,
47 // this appears to be ill-formed:
48 //
49 // namespace N {
50 // template <typename T> struct S {
51 // ~S();
52 // };
53 // }
54 //
55 // void f(N::S<int>* s) {
56 // s->N::S<int>::~S();
57 // }
58 //
Douglas Gregor93649fd2010-02-23 00:15:22 +000059 // See also PR6358 and PR6359.
Sebastian Redlc0fee502010-07-07 23:17:38 +000060 // For this reason, we're currently only doing the C++03 version of this
61 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregor124b8782010-02-16 19:09:40 +000062 QualType SearchType;
63 DeclContext *LookupCtx = 0;
64 bool isDependent = false;
65 bool LookInScope = false;
66
67 // If we have an object type, it's because we are in a
68 // pseudo-destructor-expression or a member access expression, and
69 // we know what type we're looking for.
70 if (ObjectTypePtr)
71 SearchType = GetTypeFromParser(ObjectTypePtr);
72
73 if (SS.isSet()) {
Douglas Gregor93649fd2010-02-23 00:15:22 +000074 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000075
Douglas Gregor93649fd2010-02-23 00:15:22 +000076 bool AlreadySearched = false;
77 bool LookAtPrefix = true;
Sebastian Redlc0fee502010-07-07 23:17:38 +000078 // C++ [basic.lookup.qual]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000079 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redlc0fee502010-07-07 23:17:38 +000080 // the type-names are looked up as types in the scope designated by the
81 // nested-name-specifier. In a qualified-id of the form:
NAKAMURA Takumi00995302011-01-27 07:09:49 +000082 //
83 // ::[opt] nested-name-specifier ~ class-name
Sebastian Redlc0fee502010-07-07 23:17:38 +000084 //
85 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth5e895a82010-02-21 10:19:54 +000086 // a qualified-id of the form:
Douglas Gregor124b8782010-02-16 19:09:40 +000087 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +000088 // ::opt nested-name-specifier class-name :: ~ class-name
Douglas Gregor124b8782010-02-16 19:09:40 +000089 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000090 // the class-names are looked up as types in the scope designated by
Sebastian Redlc0fee502010-07-07 23:17:38 +000091 // the nested-name-specifier.
Douglas Gregor124b8782010-02-16 19:09:40 +000092 //
Sebastian Redlc0fee502010-07-07 23:17:38 +000093 // Here, we check the first case (completely) and determine whether the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000094 // code below is permitted to look at the prefix of the
Sebastian Redlc0fee502010-07-07 23:17:38 +000095 // nested-name-specifier.
96 DeclContext *DC = computeDeclContext(SS, EnteringContext);
97 if (DC && DC->isFileContext()) {
98 AlreadySearched = true;
99 LookupCtx = DC;
100 isDependent = false;
101 } else if (DC && isa<CXXRecordDecl>(DC))
102 LookAtPrefix = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000103
Sebastian Redlc0fee502010-07-07 23:17:38 +0000104 // The second case from the C++03 rules quoted further above.
Douglas Gregor93649fd2010-02-23 00:15:22 +0000105 NestedNameSpecifier *Prefix = 0;
106 if (AlreadySearched) {
107 // Nothing left to do.
108 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
109 CXXScopeSpec PrefixSS;
110 PrefixSS.setScopeRep(Prefix);
111 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
112 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000113 } else if (ObjectTypePtr) {
Douglas Gregor124b8782010-02-16 19:09:40 +0000114 LookupCtx = computeDeclContext(SearchType);
115 isDependent = SearchType->isDependentType();
116 } else {
117 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000118 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregor124b8782010-02-16 19:09:40 +0000119 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000120
Douglas Gregoredc90502010-02-25 04:46:04 +0000121 LookInScope = false;
Douglas Gregor124b8782010-02-16 19:09:40 +0000122 } else if (ObjectTypePtr) {
123 // C++ [basic.lookup.classref]p3:
124 // If the unqualified-id is ~type-name, the type-name is looked up
125 // in the context of the entire postfix-expression. If the type T
126 // of the object expression is of a class type C, the type-name is
127 // also looked up in the scope of class C. At least one of the
128 // lookups shall find a name that refers to (possibly
129 // cv-qualified) T.
130 LookupCtx = computeDeclContext(SearchType);
131 isDependent = SearchType->isDependentType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000132 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregor124b8782010-02-16 19:09:40 +0000133 "Caller should have completed object type");
134
135 LookInScope = true;
136 } else {
137 // Perform lookup into the current scope (only).
138 LookInScope = true;
139 }
140
141 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
142 for (unsigned Step = 0; Step != 2; ++Step) {
143 // Look for the name first in the computed lookup context (if we
144 // have one) and, if that fails to find a match, in the sope (if
145 // we're allowed to look there).
146 Found.clear();
147 if (Step == 0 && LookupCtx)
148 LookupQualifiedName(Found, LookupCtx);
Douglas Gregora2e7dd22010-02-25 01:56:36 +0000149 else if (Step == 1 && LookInScope && S)
Douglas Gregor124b8782010-02-16 19:09:40 +0000150 LookupName(Found, S);
151 else
152 continue;
153
154 // FIXME: Should we be suppressing ambiguities here?
155 if (Found.isAmbiguous())
John McCallb3d87482010-08-24 05:47:05 +0000156 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000157
158 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
159 QualType T = Context.getTypeDeclType(Type);
Douglas Gregor124b8782010-02-16 19:09:40 +0000160
161 if (SearchType.isNull() || SearchType->isDependentType() ||
162 Context.hasSameUnqualifiedType(T, SearchType)) {
163 // We found our type!
164
John McCallb3d87482010-08-24 05:47:05 +0000165 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000166 }
167 }
168
169 // If the name that we found is a class template name, and it is
170 // the same name as the template name in the last part of the
171 // nested-name-specifier (if present) or the object type, then
172 // this is the destructor for that class.
173 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000174 // issue 399, for which there isn't even an obvious direction.
Douglas Gregor124b8782010-02-16 19:09:40 +0000175 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
176 QualType MemberOfType;
177 if (SS.isSet()) {
178 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
179 // Figure out the type of the context, if it has one.
John McCall3cb0ebd2010-03-10 03:28:59 +0000180 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
181 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregor124b8782010-02-16 19:09:40 +0000182 }
183 }
184 if (MemberOfType.isNull())
185 MemberOfType = SearchType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000186
Douglas Gregor124b8782010-02-16 19:09:40 +0000187 if (MemberOfType.isNull())
188 continue;
189
190 // We're referring into a class template specialization. If the
191 // class template we found is the same as the template being
192 // specialized, we found what we are looking for.
193 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
194 if (ClassTemplateSpecializationDecl *Spec
195 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
196 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
197 Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000198 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000199 }
200
201 continue;
202 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000203
Douglas Gregor124b8782010-02-16 19:09:40 +0000204 // We're referring to an unresolved class template
205 // specialization. Determine whether we class template we found
206 // is the same as the template being specialized or, if we don't
207 // know which template is being specialized, that it at least
208 // has the same name.
209 if (const TemplateSpecializationType *SpecType
210 = MemberOfType->getAs<TemplateSpecializationType>()) {
211 TemplateName SpecName = SpecType->getTemplateName();
212
213 // The class template we found is the same template being
214 // specialized.
215 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
216 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000217 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000218
219 continue;
220 }
221
222 // The class template we found has the same name as the
223 // (dependent) template name being specialized.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000224 if (DependentTemplateName *DepTemplate
Douglas Gregor124b8782010-02-16 19:09:40 +0000225 = SpecName.getAsDependentTemplateName()) {
226 if (DepTemplate->isIdentifier() &&
227 DepTemplate->getIdentifier() == Template->getIdentifier())
John McCallb3d87482010-08-24 05:47:05 +0000228 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000229
230 continue;
231 }
232 }
233 }
234 }
235
236 if (isDependent) {
237 // We didn't find our type, but that's okay: it's dependent
238 // anyway.
239 NestedNameSpecifier *NNS = 0;
240 SourceRange Range;
241 if (SS.isSet()) {
242 NNS = (NestedNameSpecifier *)SS.getScopeRep();
243 Range = SourceRange(SS.getRange().getBegin(), NameLoc);
244 } else {
245 NNS = NestedNameSpecifier::Create(Context, &II);
246 Range = SourceRange(NameLoc);
247 }
248
John McCallb3d87482010-08-24 05:47:05 +0000249 QualType T = CheckTypenameType(ETK_None, NNS, II,
250 SourceLocation(),
251 Range, NameLoc);
252 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000253 }
254
255 if (ObjectTypePtr)
256 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000257 << &II;
Douglas Gregor124b8782010-02-16 19:09:40 +0000258 else
259 Diag(NameLoc, diag::err_destructor_class_name);
260
John McCallb3d87482010-08-24 05:47:05 +0000261 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000262}
263
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000264/// \brief Build a C++ typeid expression with a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000265ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000266 SourceLocation TypeidLoc,
267 TypeSourceInfo *Operand,
268 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000269 // C++ [expr.typeid]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000270 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000271 // that is the operand of typeid are always ignored.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000272 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000273 // type, the class shall be completely-defined.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000274 Qualifiers Quals;
275 QualType T
276 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
277 Quals);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000278 if (T->getAs<RecordType>() &&
279 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
280 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000281
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000282 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
283 Operand,
284 SourceRange(TypeidLoc, RParenLoc)));
285}
286
287/// \brief Build a C++ typeid expression with an expression operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000288ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000289 SourceLocation TypeidLoc,
290 Expr *E,
291 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000292 bool isUnevaluatedOperand = true;
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000293 if (E && !E->isTypeDependent()) {
294 QualType T = E->getType();
295 if (const RecordType *RecordT = T->getAs<RecordType>()) {
296 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
297 // C++ [expr.typeid]p3:
298 // [...] If the type of the expression is a class type, the class
299 // shall be completely-defined.
300 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
301 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000302
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000303 // C++ [expr.typeid]p3:
Sebastian Redl906082e2010-07-20 04:20:21 +0000304 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000305 // polymorphic class type [...] [the] expression is an unevaluated
306 // operand. [...]
Sebastian Redl906082e2010-07-20 04:20:21 +0000307 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000308 isUnevaluatedOperand = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000309
310 // We require a vtable to query the type at run time.
311 MarkVTableUsed(TypeidLoc, RecordD);
312 }
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000313 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000314
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000315 // C++ [expr.typeid]p4:
316 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000317 // cv-qualified type, the result of the typeid expression refers to a
318 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000319 // type.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000320 Qualifiers Quals;
321 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
322 if (!Context.hasSameType(T, UnqualT)) {
323 T = UnqualT;
John McCall2de56d12010-08-25 11:45:40 +0000324 ImpCastExprToType(E, UnqualT, CK_NoOp, CastCategory(E));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000325 }
326 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000327
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000328 // If this is an unevaluated operand, clear out the set of
329 // declaration references we have been computing and eliminate any
330 // temporaries introduced in its computation.
331 if (isUnevaluatedOperand)
332 ExprEvalContexts.back().Context = Unevaluated;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000333
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000334 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCall9ae2f072010-08-23 23:25:46 +0000335 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000336 SourceRange(TypeidLoc, RParenLoc)));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000337}
338
339/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCall60d7b3a2010-08-24 06:29:42 +0000340ExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000341Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
342 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000343 // Find the std::type_info type.
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000344 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000345 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000346
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000347 if (!CXXTypeInfoDecl) {
348 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
349 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
350 LookupQualifiedName(R, getStdNamespace());
351 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
352 if (!CXXTypeInfoDecl)
353 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
354 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000355
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000356 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000357
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000358 if (isType) {
359 // The operand is a type; handle it as such.
360 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +0000361 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
362 &TInfo);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000363 if (T.isNull())
364 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000365
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000366 if (!TInfo)
367 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000368
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000369 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000370 }
Mike Stump1eb44332009-09-09 15:08:12 +0000371
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000372 // The operand is an expression.
John McCall9ae2f072010-08-23 23:25:46 +0000373 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000374}
375
Francois Pichet6915c522010-12-27 01:32:00 +0000376/// Retrieve the UuidAttr associated with QT.
377static UuidAttr *GetUuidAttrOfType(QualType QT) {
378 // Optionally remove one level of pointer, reference or array indirection.
John McCallf4c73712011-01-19 06:33:43 +0000379 const Type *Ty = QT.getTypePtr();;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000380 if (QT->isPointerType() || QT->isReferenceType())
381 Ty = QT->getPointeeType().getTypePtr();
382 else if (QT->isArrayType())
383 Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
384
Francois Pichet6915c522010-12-27 01:32:00 +0000385 // Loop all class definition and declaration looking for an uuid attribute.
386 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
387 while (RD) {
388 if (UuidAttr *Uuid = RD->getAttr<UuidAttr>())
389 return Uuid;
390 RD = RD->getPreviousDeclaration();
391 }
392 return 0;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000393}
394
Francois Pichet01b7c302010-09-08 12:20:18 +0000395/// \brief Build a Microsoft __uuidof expression with a type operand.
396ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
397 SourceLocation TypeidLoc,
398 TypeSourceInfo *Operand,
399 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000400 if (!Operand->getType()->isDependentType()) {
401 if (!GetUuidAttrOfType(Operand->getType()))
402 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
403 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000404
Francois Pichet01b7c302010-09-08 12:20:18 +0000405 // FIXME: add __uuidof semantic analysis for type operand.
406 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
407 Operand,
408 SourceRange(TypeidLoc, RParenLoc)));
409}
410
411/// \brief Build a Microsoft __uuidof expression with an expression operand.
412ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
413 SourceLocation TypeidLoc,
414 Expr *E,
415 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000416 if (!E->getType()->isDependentType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000417 if (!GetUuidAttrOfType(E->getType()) &&
Francois Pichet6915c522010-12-27 01:32:00 +0000418 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
419 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
420 }
421 // FIXME: add __uuidof semantic analysis for type operand.
Francois Pichet01b7c302010-09-08 12:20:18 +0000422 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
423 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000424 SourceRange(TypeidLoc, RParenLoc)));
Francois Pichet01b7c302010-09-08 12:20:18 +0000425}
426
427/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
428ExprResult
429Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
430 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000431 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet01b7c302010-09-08 12:20:18 +0000432 if (!MSVCGuidDecl) {
433 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
434 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
435 LookupQualifiedName(R, Context.getTranslationUnitDecl());
436 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
437 if (!MSVCGuidDecl)
438 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000439 }
440
Francois Pichet01b7c302010-09-08 12:20:18 +0000441 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000442
Francois Pichet01b7c302010-09-08 12:20:18 +0000443 if (isType) {
444 // The operand is a type; handle it as such.
445 TypeSourceInfo *TInfo = 0;
446 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
447 &TInfo);
448 if (T.isNull())
449 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000450
Francois Pichet01b7c302010-09-08 12:20:18 +0000451 if (!TInfo)
452 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
453
454 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
455 }
456
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000457 // The operand is an expression.
Francois Pichet01b7c302010-09-08 12:20:18 +0000458 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
459}
460
Steve Naroff1b273c42007-09-16 14:56:35 +0000461/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCall60d7b3a2010-08-24 06:29:42 +0000462ExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000463Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000464 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000465 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000466 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
467 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000468}
Chris Lattner50dd2892008-02-26 00:51:44 +0000469
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000470/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCall60d7b3a2010-08-24 06:29:42 +0000471ExprResult
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000472Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
473 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
474}
475
Chris Lattner50dd2892008-02-26 00:51:44 +0000476/// ActOnCXXThrow - Parse throw expressions.
John McCall60d7b3a2010-08-24 06:29:42 +0000477ExprResult
John McCall9ae2f072010-08-23 23:25:46 +0000478Sema::ActOnCXXThrow(SourceLocation OpLoc, Expr *Ex) {
Anders Carlsson7f11d9c2011-02-19 19:26:44 +0000479 if (!getLangOptions().Exceptions)
Anders Carlssonb1fba312011-02-19 21:53:09 +0000480 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Anders Carlsson7f11d9c2011-02-19 19:26:44 +0000481
Sebastian Redl972041f2009-04-27 20:27:31 +0000482 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
483 return ExprError();
484 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
485}
486
487/// CheckCXXThrowOperand - Validate the operand of a throw.
488bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
489 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000490 // A throw-expression initializes a temporary object, called the exception
491 // object, the type of which is determined by removing any top-level
492 // cv-qualifiers from the static type of the operand of throw and adjusting
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000493 // the type from "array of T" or "function returning T" to "pointer to T"
Douglas Gregor154fe982009-12-23 22:04:40 +0000494 // or "pointer to function returning T", [...]
495 if (E->getType().hasQualifiers())
John McCall2de56d12010-08-25 11:45:40 +0000496 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
Sebastian Redl906082e2010-07-20 04:20:21 +0000497 CastCategory(E));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000498
Sebastian Redl972041f2009-04-27 20:27:31 +0000499 DefaultFunctionArrayConversion(E);
500
501 // If the type of the exception would be an incomplete type or a pointer
502 // to an incomplete type other than (cv) void the program is ill-formed.
503 QualType Ty = E->getType();
John McCallac418162010-04-22 01:10:34 +0000504 bool isPointer = false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000505 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000506 Ty = Ptr->getPointeeType();
John McCallac418162010-04-22 01:10:34 +0000507 isPointer = true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000508 }
509 if (!isPointer || !Ty->isVoidType()) {
510 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000511 PDiag(isPointer ? diag::err_throw_incomplete_ptr
512 : diag::err_throw_incomplete)
513 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000514 return true;
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000515
Douglas Gregorbf422f92010-04-15 18:05:39 +0000516 if (RequireNonAbstractType(ThrowLoc, E->getType(),
517 PDiag(diag::err_throw_abstract_type)
518 << E->getSourceRange()))
519 return true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000520 }
521
John McCallac418162010-04-22 01:10:34 +0000522 // Initialize the exception result. This implicitly weeds out
523 // abstract types or types with inaccessible copy constructors.
Douglas Gregor72dfa272011-01-21 22:46:35 +0000524 const VarDecl *NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
525
Douglas Gregorf5d8f462011-01-21 18:05:27 +0000526 // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p32.
John McCallac418162010-04-22 01:10:34 +0000527 InitializedEntity Entity =
Douglas Gregor72dfa272011-01-21 22:46:35 +0000528 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
529 /*NRVO=*/false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000530 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
Douglas Gregor72dfa272011-01-21 22:46:35 +0000531 QualType(), E);
John McCallac418162010-04-22 01:10:34 +0000532 if (Res.isInvalid())
533 return true;
534 E = Res.takeAs<Expr>();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000535
Eli Friedman5ed9b932010-06-03 20:39:03 +0000536 // If the exception has class type, we need additional handling.
537 const RecordType *RecordTy = Ty->getAs<RecordType>();
538 if (!RecordTy)
539 return false;
540 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
541
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000542 // If we are throwing a polymorphic class type or pointer thereof,
543 // exception handling will make use of the vtable.
Eli Friedman5ed9b932010-06-03 20:39:03 +0000544 MarkVTableUsed(ThrowLoc, RD);
545
Eli Friedman98efb9f2010-10-12 20:32:36 +0000546 // If a pointer is thrown, the referenced object will not be destroyed.
547 if (isPointer)
548 return false;
549
Eli Friedman5ed9b932010-06-03 20:39:03 +0000550 // If the class has a non-trivial destructor, we must be able to call it.
551 if (RD->hasTrivialDestructor())
552 return false;
553
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000554 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +0000555 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman5ed9b932010-06-03 20:39:03 +0000556 if (!Destructor)
557 return false;
558
559 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
560 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregored8abf12010-07-08 06:14:04 +0000561 PDiag(diag::err_access_dtor_exception) << Ty);
Sebastian Redl972041f2009-04-27 20:27:31 +0000562 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000563}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000564
John McCall5808ce42011-02-03 08:15:49 +0000565CXXMethodDecl *Sema::tryCaptureCXXThis() {
566 // Ignore block scopes: we can capture through them.
567 // Ignore nested enum scopes: we'll diagnose non-constant expressions
568 // where they're invalid, and other uses are legitimate.
569 // Don't ignore nested class scopes: you can't use 'this' in a local class.
John McCall469a1eb2011-02-02 13:00:07 +0000570 DeclContext *DC = CurContext;
John McCall5808ce42011-02-03 08:15:49 +0000571 while (true) {
572 if (isa<BlockDecl>(DC)) DC = cast<BlockDecl>(DC)->getDeclContext();
573 else if (isa<EnumDecl>(DC)) DC = cast<EnumDecl>(DC)->getDeclContext();
574 else break;
575 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000576
John McCall5808ce42011-02-03 08:15:49 +0000577 // If we're not in an instance method, error out.
John McCall469a1eb2011-02-02 13:00:07 +0000578 CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC);
579 if (!method || !method->isInstance())
John McCall5808ce42011-02-03 08:15:49 +0000580 return 0;
John McCall469a1eb2011-02-02 13:00:07 +0000581
582 // Mark that we're closing on 'this' in all the block scopes, if applicable.
583 for (unsigned idx = FunctionScopes.size() - 1;
584 isa<BlockScopeInfo>(FunctionScopes[idx]);
585 --idx)
586 cast<BlockScopeInfo>(FunctionScopes[idx])->CapturesCXXThis = true;
587
John McCall5808ce42011-02-03 08:15:49 +0000588 return method;
589}
590
591ExprResult Sema::ActOnCXXThis(SourceLocation loc) {
592 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
593 /// is a non-lvalue expression whose value is the address of the object for
594 /// which the function is called.
595
596 CXXMethodDecl *method = tryCaptureCXXThis();
597 if (!method) return Diag(loc, diag::err_invalid_this_use);
598
599 return Owned(new (Context) CXXThisExpr(loc, method->getThisType(Context),
John McCall469a1eb2011-02-02 13:00:07 +0000600 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000601}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000602
John McCall60d7b3a2010-08-24 06:29:42 +0000603ExprResult
Douglas Gregorab6677e2010-09-08 00:15:04 +0000604Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000605 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000606 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000607 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000608 if (!TypeRep)
609 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000610
John McCall9d125032010-01-15 18:39:57 +0000611 TypeSourceInfo *TInfo;
612 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
613 if (!TInfo)
614 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregorab6677e2010-09-08 00:15:04 +0000615
616 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
617}
618
619/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
620/// Can be interpreted either as function-style casting ("int(x)")
621/// or class type construction ("ClassType(x,y,z)")
622/// or creation of a value-initialized type ("int()").
623ExprResult
624Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
625 SourceLocation LParenLoc,
626 MultiExprArg exprs,
627 SourceLocation RParenLoc) {
628 QualType Ty = TInfo->getType();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000629 unsigned NumExprs = exprs.size();
630 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000631 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000632 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
633
Sebastian Redlf53597f2009-03-15 17:47:39 +0000634 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000635 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000636 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000637
Douglas Gregorab6677e2010-09-08 00:15:04 +0000638 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000639 LParenLoc,
640 Exprs, NumExprs,
641 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000642 }
643
Anders Carlssonbb60a502009-08-27 03:53:50 +0000644 if (Ty->isArrayType())
645 return ExprError(Diag(TyBeginLoc,
646 diag::err_value_init_for_array_type) << FullRange);
647 if (!Ty->isVoidType() &&
648 RequireCompleteType(TyBeginLoc, Ty,
649 PDiag(diag::err_invalid_incomplete_type_use)
650 << FullRange))
651 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000652
Anders Carlssonbb60a502009-08-27 03:53:50 +0000653 if (RequireNonAbstractType(TyBeginLoc, Ty,
654 diag::err_allocation_of_abstract_type))
655 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000656
657
Douglas Gregor506ae412009-01-16 18:33:17 +0000658 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000659 // If the expression list is a single expression, the type conversion
660 // expression is equivalent (in definedness, and if defined in meaning) to the
661 // corresponding cast expression.
662 //
663 if (NumExprs == 1) {
John McCalldaa8e4e2010-11-15 09:13:47 +0000664 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +0000665 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +0000666 CXXCastPath BasePath;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000667 if (CheckCastTypes(TInfo->getTypeLoc().getSourceRange(), Ty, Exprs[0],
John McCallf89e55a2010-11-18 06:31:45 +0000668 Kind, VK, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000669 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000670 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000671
672 exprs.release();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000673
John McCallf871d0c2010-08-07 06:22:56 +0000674 return Owned(CXXFunctionalCastExpr::Create(Context,
Douglas Gregorab6677e2010-09-08 00:15:04 +0000675 Ty.getNonLValueExprType(Context),
John McCallf89e55a2010-11-18 06:31:45 +0000676 VK, TInfo, TyBeginLoc, Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000677 Exprs[0], &BasePath,
678 RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000679 }
680
Douglas Gregor19311e72010-09-08 21:40:08 +0000681 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
682 InitializationKind Kind
683 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
684 LParenLoc, RParenLoc)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000685 : InitializationKind::CreateValue(TyBeginLoc,
Douglas Gregor19311e72010-09-08 21:40:08 +0000686 LParenLoc, RParenLoc);
687 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
688 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redlf53597f2009-03-15 17:47:39 +0000689
Douglas Gregor19311e72010-09-08 21:40:08 +0000690 // FIXME: Improve AST representation?
691 return move(Result);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000692}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000693
John McCall6ec278d2011-01-27 09:37:56 +0000694/// doesUsualArrayDeleteWantSize - Answers whether the usual
695/// operator delete[] for the given type has a size_t parameter.
696static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
697 QualType allocType) {
698 const RecordType *record =
699 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
700 if (!record) return false;
701
702 // Try to find an operator delete[] in class scope.
703
704 DeclarationName deleteName =
705 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
706 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
707 S.LookupQualifiedName(ops, record->getDecl());
708
709 // We're just doing this for information.
710 ops.suppressDiagnostics();
711
712 // Very likely: there's no operator delete[].
713 if (ops.empty()) return false;
714
715 // If it's ambiguous, it should be illegal to call operator delete[]
716 // on this thing, so it doesn't matter if we allocate extra space or not.
717 if (ops.isAmbiguous()) return false;
718
719 LookupResult::Filter filter = ops.makeFilter();
720 while (filter.hasNext()) {
721 NamedDecl *del = filter.next()->getUnderlyingDecl();
722
723 // C++0x [basic.stc.dynamic.deallocation]p2:
724 // A template instance is never a usual deallocation function,
725 // regardless of its signature.
726 if (isa<FunctionTemplateDecl>(del)) {
727 filter.erase();
728 continue;
729 }
730
731 // C++0x [basic.stc.dynamic.deallocation]p2:
732 // If class T does not declare [an operator delete[] with one
733 // parameter] but does declare a member deallocation function
734 // named operator delete[] with exactly two parameters, the
735 // second of which has type std::size_t, then this function
736 // is a usual deallocation function.
737 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
738 filter.erase();
739 continue;
740 }
741 }
742 filter.done();
743
744 if (!ops.isSingleResult()) return false;
745
746 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
747 return (del->getNumParams() == 2);
748}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000749
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000750/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
751/// @code new (memory) int[size][4] @endcode
752/// or
753/// @code ::new Foo(23, "hello") @endcode
754/// For the interpretation of this heap of arguments, consult the base version.
John McCall60d7b3a2010-08-24 06:29:42 +0000755ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000756Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000757 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000758 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000759 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000760 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000761 SourceLocation ConstructorRParen) {
Richard Smith34b41d92011-02-20 03:19:35 +0000762 bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
763
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000764 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000765 // If the specified type is an array, unwrap it and save the expression.
766 if (D.getNumTypeObjects() > 0 &&
767 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
768 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smith34b41d92011-02-20 03:19:35 +0000769 if (TypeContainsAuto)
770 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
771 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000772 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000773 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
774 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000775 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000776 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
777 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000778
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000779 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000780 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000781 }
782
Douglas Gregor043cad22009-09-11 00:18:58 +0000783 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000784 if (ArraySize) {
785 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000786 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
787 break;
788
789 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
790 if (Expr *NumElts = (Expr *)Array.NumElts) {
791 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
792 !NumElts->isIntegerConstantExpr(Context)) {
793 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
794 << NumElts->getSourceRange();
795 return ExprError();
796 }
797 }
798 }
799 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000800
Richard Smith34b41d92011-02-20 03:19:35 +0000801 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0, /*OwnedDecl=*/0,
802 /*AllowAuto=*/true);
John McCallbf1a0282010-06-04 23:28:52 +0000803 QualType AllocType = TInfo->getType();
Chris Lattnereaaebc72009-04-25 08:06:05 +0000804 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000805 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000806
Mike Stump1eb44332009-09-09 15:08:12 +0000807 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000808 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000809 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000810 PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000811 TypeIdParens,
Mike Stump1eb44332009-09-09 15:08:12 +0000812 AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000813 TInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000814 ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000815 ConstructorLParen,
816 move(ConstructorArgs),
Richard Smith34b41d92011-02-20 03:19:35 +0000817 ConstructorRParen,
818 TypeContainsAuto);
Douglas Gregor3433cf72009-05-21 00:00:09 +0000819}
820
John McCall60d7b3a2010-08-24 06:29:42 +0000821ExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000822Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
823 SourceLocation PlacementLParen,
824 MultiExprArg PlacementArgs,
825 SourceLocation PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000826 SourceRange TypeIdParens,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000827 QualType AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000828 TypeSourceInfo *AllocTypeInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000829 Expr *ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000830 SourceLocation ConstructorLParen,
831 MultiExprArg ConstructorArgs,
Richard Smith34b41d92011-02-20 03:19:35 +0000832 SourceLocation ConstructorRParen,
833 bool TypeMayContainAuto) {
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000834 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000835
Richard Smith34b41d92011-02-20 03:19:35 +0000836 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
837 if (TypeMayContainAuto && AllocType->getContainedAutoType()) {
838 if (ConstructorArgs.size() == 0)
839 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
840 << AllocType << TypeRange);
841 if (ConstructorArgs.size() != 1) {
842 Expr *FirstBad = ConstructorArgs.get()[1];
843 return ExprError(Diag(FirstBad->getSourceRange().getBegin(),
844 diag::err_auto_new_ctor_multiple_expressions)
845 << AllocType << TypeRange);
846 }
847 QualType DeducedType;
848 if (!DeduceAutoType(AllocType, ConstructorArgs.get()[0], DeducedType))
849 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
850 << AllocType
851 << ConstructorArgs.get()[0]->getType()
852 << TypeRange
853 << ConstructorArgs.get()[0]->getSourceRange());
854
855 AllocType = DeducedType;
856 AllocTypeInfo = Context.getTrivialTypeSourceInfo(AllocType, StartLoc);
857 }
858
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000859 // Per C++0x [expr.new]p5, the type being constructed may be a
860 // typedef of an array type.
John McCall9ae2f072010-08-23 23:25:46 +0000861 if (!ArraySize) {
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000862 if (const ConstantArrayType *Array
863 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000864 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
865 Context.getSizeType(),
866 TypeRange.getEnd());
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000867 AllocType = Array->getElementType();
868 }
869 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000870
Douglas Gregora0750762010-10-06 16:00:31 +0000871 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
872 return ExprError();
873
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000874 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000875
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000876 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
877 // or enumeration type with a non-negative value."
Sebastian Redl28507842009-02-26 14:39:58 +0000878 if (ArraySize && !ArraySize->isTypeDependent()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000879
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000880 QualType SizeType = ArraySize->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000881
John McCall60d7b3a2010-08-24 06:29:42 +0000882 ExprResult ConvertedSize
John McCall9ae2f072010-08-23 23:25:46 +0000883 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000884 PDiag(diag::err_array_size_not_integral),
885 PDiag(diag::err_array_size_incomplete_type)
886 << ArraySize->getSourceRange(),
887 PDiag(diag::err_array_size_explicit_conversion),
888 PDiag(diag::note_array_size_conversion),
889 PDiag(diag::err_array_size_ambiguous_conversion),
890 PDiag(diag::note_array_size_conversion),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000891 PDiag(getLangOptions().CPlusPlus0x? 0
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000892 : diag::ext_array_size_conversion));
893 if (ConvertedSize.isInvalid())
894 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000895
John McCall9ae2f072010-08-23 23:25:46 +0000896 ArraySize = ConvertedSize.take();
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000897 SizeType = ArraySize->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000898 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000899 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000900
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000901 // Let's see if this is a constant < 0. If so, we reject it out of hand.
902 // We don't care about special rules, so we tell the machinery it's not
903 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000904 if (!ArraySize->isValueDependent()) {
905 llvm::APSInt Value;
906 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
907 if (Value < llvm::APSInt(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000908 llvm::APInt::getNullValue(Value.getBitWidth()),
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000909 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000910 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +0000911 diag::err_typecheck_negative_array_size)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000912 << ArraySize->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000913
Douglas Gregor2767ce22010-08-18 00:39:00 +0000914 if (!AllocType->isDependentType()) {
915 unsigned ActiveSizeBits
916 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
917 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000918 Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +0000919 diag::err_array_too_large)
920 << Value.toString(10)
921 << ArraySize->getSourceRange();
922 return ExprError();
923 }
924 }
Douglas Gregor4bd40312010-07-13 15:54:32 +0000925 } else if (TypeIdParens.isValid()) {
926 // Can't have dynamic array size when the type-id is in parentheses.
927 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
928 << ArraySize->getSourceRange()
929 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
930 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000931
Douglas Gregor4bd40312010-07-13 15:54:32 +0000932 TypeIdParens = SourceRange();
Sebastian Redl28507842009-02-26 14:39:58 +0000933 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000934 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000935
Eli Friedman73c39ab2009-10-20 08:27:19 +0000936 ImpCastExprToType(ArraySize, Context.getSizeType(),
John McCall2de56d12010-08-25 11:45:40 +0000937 CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000938 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000939
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000940 FunctionDecl *OperatorNew = 0;
941 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000942 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
943 unsigned NumPlaceArgs = PlacementArgs.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000944
Sebastian Redl28507842009-02-26 14:39:58 +0000945 if (!AllocType->isDependentType() &&
946 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
947 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000948 SourceRange(PlacementLParen, PlacementRParen),
949 UseGlobal, AllocType, ArraySize, PlaceArgs,
950 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000951 return ExprError();
John McCall6ec278d2011-01-27 09:37:56 +0000952
953 // If this is an array allocation, compute whether the usual array
954 // deallocation function for the type has a size_t parameter.
955 bool UsualArrayDeleteWantsSize = false;
956 if (ArraySize && !AllocType->isDependentType())
957 UsualArrayDeleteWantsSize
958 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
959
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000960 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000961 if (OperatorNew) {
962 // Add default arguments, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000963 const FunctionProtoType *Proto =
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000964 OperatorNew->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000965 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000966 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000967
Anders Carlsson28e94832010-05-03 02:07:56 +0000968 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000969 Proto, 1, PlaceArgs, NumPlaceArgs,
Anders Carlsson28e94832010-05-03 02:07:56 +0000970 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000971 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000972
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000973 NumPlaceArgs = AllPlaceArgs.size();
974 if (NumPlaceArgs > 0)
975 PlaceArgs = &AllPlaceArgs[0];
976 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000977
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000978 bool Init = ConstructorLParen.isValid();
979 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000980 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000981 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
982 unsigned NumConsArgs = ConstructorArgs.size();
John McCallca0408f2010-08-23 06:44:23 +0000983 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000984
Anders Carlsson48c95012010-05-03 15:45:23 +0000985 // Array 'new' can't have any initializers.
Anders Carlsson55cbd6e2010-05-16 16:24:20 +0000986 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlsson48c95012010-05-03 15:45:23 +0000987 SourceRange InitRange(ConsArgs[0]->getLocStart(),
988 ConsArgs[NumConsArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000989
Anders Carlsson48c95012010-05-03 15:45:23 +0000990 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
991 return ExprError();
992 }
993
Douglas Gregor99a2e602009-12-16 01:38:02 +0000994 if (!AllocType->isDependentType() &&
995 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
996 // C++0x [expr.new]p15:
997 // A new-expression that creates an object of type T initializes that
998 // object as follows:
999 InitializationKind Kind
1000 // - If the new-initializer is omitted, the object is default-
1001 // initialized (8.5); if no initialization is performed,
1002 // the object has indeterminate value
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001003 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001004 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor99a2e602009-12-16 01:38:02 +00001005 // initialization rules of 8.5 for direct-initialization.
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001006 : InitializationKind::CreateDirect(TypeRange.getBegin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001007 ConstructorLParen,
Douglas Gregor99a2e602009-12-16 01:38:02 +00001008 ConstructorRParen);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001009
Douglas Gregor99a2e602009-12-16 01:38:02 +00001010 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00001011 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001012 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001013 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor99a2e602009-12-16 01:38:02 +00001014 move(ConstructorArgs));
1015 if (FullInit.isInvalid())
1016 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001017
1018 // FullInit is our initializer; walk through it to determine if it's a
Douglas Gregor99a2e602009-12-16 01:38:02 +00001019 // constructor call, which CXXNewExpr handles directly.
1020 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
1021 if (CXXBindTemporaryExpr *Binder
1022 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
1023 FullInitExpr = Binder->getSubExpr();
1024 if (CXXConstructExpr *Construct
1025 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
1026 Constructor = Construct->getConstructor();
1027 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
1028 AEnd = Construct->arg_end();
1029 A != AEnd; ++A)
John McCall3fa5cae2010-10-26 07:05:15 +00001030 ConvertedConstructorArgs.push_back(*A);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001031 } else {
1032 // Take the converted initializer.
1033 ConvertedConstructorArgs.push_back(FullInit.release());
1034 }
1035 } else {
1036 // No initialization required.
1037 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001038
Douglas Gregor99a2e602009-12-16 01:38:02 +00001039 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +00001040 NumConsArgs = ConvertedConstructorArgs.size();
1041 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001042 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001043
Douglas Gregor6d908702010-02-26 05:06:18 +00001044 // Mark the new and delete operators as referenced.
1045 if (OperatorNew)
1046 MarkDeclarationReferenced(StartLoc, OperatorNew);
1047 if (OperatorDelete)
1048 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1049
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001050 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001051
Sebastian Redlf53597f2009-03-15 17:47:39 +00001052 PlacementArgs.release();
1053 ConstructorArgs.release();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001054
Ted Kremenekad7fe862010-02-11 22:51:03 +00001055 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregor4bd40312010-07-13 15:54:32 +00001056 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001057 ArraySize, Constructor, Init,
1058 ConsArgs, NumConsArgs, OperatorDelete,
John McCall6ec278d2011-01-27 09:37:56 +00001059 UsualArrayDeleteWantsSize,
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001060 ResultType, AllocTypeInfo,
1061 StartLoc,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001062 Init ? ConstructorRParen :
Chandler Carruth428edaf2010-10-25 08:47:36 +00001063 TypeRange.getEnd(),
1064 ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001065}
1066
1067/// CheckAllocatedType - Checks that a type is suitable as the allocated type
1068/// in a new-expression.
1069/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +00001070bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00001071 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001072 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1073 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +00001074 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001075 return Diag(Loc, diag::err_bad_new_type)
1076 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001077 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001078 return Diag(Loc, diag::err_bad_new_type)
1079 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001080 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +00001081 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001082 PDiag(diag::err_new_incomplete_type)
1083 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001084 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +00001085 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +00001086 diag::err_allocation_of_abstract_type))
1087 return true;
Douglas Gregora0750762010-10-06 16:00:31 +00001088 else if (AllocType->isVariablyModifiedType())
1089 return Diag(Loc, diag::err_variably_modified_new_type)
1090 << AllocType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001091
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001092 return false;
1093}
1094
Douglas Gregor6d908702010-02-26 05:06:18 +00001095/// \brief Determine whether the given function is a non-placement
1096/// deallocation function.
1097static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1098 if (FD->isInvalidDecl())
1099 return false;
1100
1101 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1102 return Method->isUsualDeallocationFunction();
1103
1104 return ((FD->getOverloadedOperator() == OO_Delete ||
1105 FD->getOverloadedOperator() == OO_Array_Delete) &&
1106 FD->getNumParams() == 1);
1107}
1108
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001109/// FindAllocationFunctions - Finds the overloads of operator new and delete
1110/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001111bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1112 bool UseGlobal, QualType AllocType,
1113 bool IsArray, Expr **PlaceArgs,
1114 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001115 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +00001116 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001117 // --- Choosing an allocation function ---
1118 // C++ 5.3.4p8 - 14 & 18
1119 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1120 // in the scope of the allocated class.
1121 // 2) If an array size is given, look for operator new[], else look for
1122 // operator new.
1123 // 3) The first argument is always size_t. Append the arguments from the
1124 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001125
1126 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
1127 // We don't care about the actual value of this argument.
1128 // FIXME: Should the Sema create the expression and embed it in the syntax
1129 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00001130 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Anders Carlssond67c4c32009-08-16 20:29:29 +00001131 Context.Target.getPointerWidth(0)),
1132 Context.getSizeType(),
1133 SourceLocation());
1134 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001135 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1136
Douglas Gregor6d908702010-02-26 05:06:18 +00001137 // C++ [expr.new]p8:
1138 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001139 // function's name is operator new and the deallocation function's
Douglas Gregor6d908702010-02-26 05:06:18 +00001140 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001141 // type, the allocation function's name is operator new[] and the
1142 // deallocation function's name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001143 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1144 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +00001145 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1146 IsArray ? OO_Array_Delete : OO_Delete);
1147
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001148 QualType AllocElemType = Context.getBaseElementType(AllocType);
1149
1150 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +00001151 CXXRecordDecl *Record
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001152 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +00001153 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001154 AllocArgs.size(), Record, /*AllowMissing=*/true,
1155 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001156 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001157 }
1158 if (!OperatorNew) {
1159 // Didn't find a member overload. Look for a global one.
1160 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +00001161 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +00001162 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001163 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1164 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001165 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001166 }
1167
John McCall9c82afc2010-04-20 02:18:25 +00001168 // We don't need an operator delete if we're running under
1169 // -fno-exceptions.
1170 if (!getLangOptions().Exceptions) {
1171 OperatorDelete = 0;
1172 return false;
1173 }
1174
Anders Carlssond9583892009-05-31 20:26:12 +00001175 // FindAllocationOverload can change the passed in arguments, so we need to
1176 // copy them back.
1177 if (NumPlaceArgs > 0)
1178 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001179
Douglas Gregor6d908702010-02-26 05:06:18 +00001180 // C++ [expr.new]p19:
1181 //
1182 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001183 // deallocation function's name is looked up in the global
Douglas Gregor6d908702010-02-26 05:06:18 +00001184 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001185 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6d908702010-02-26 05:06:18 +00001186 // the scope of T. If this lookup fails to find the name, or if
1187 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001188 // deallocation function's name is looked up in the global scope.
Douglas Gregor6d908702010-02-26 05:06:18 +00001189 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001190 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001191 CXXRecordDecl *RD
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001192 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6d908702010-02-26 05:06:18 +00001193 LookupQualifiedName(FoundDelete, RD);
1194 }
John McCall90c8c572010-03-18 08:19:33 +00001195 if (FoundDelete.isAmbiguous())
1196 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +00001197
1198 if (FoundDelete.empty()) {
1199 DeclareGlobalNewDelete();
1200 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1201 }
1202
1203 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +00001204
1205 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1206
John McCalledeb6c92010-09-14 21:34:24 +00001207 // Whether we're looking for a placement operator delete is dictated
1208 // by whether we selected a placement operator new, not by whether
1209 // we had explicit placement arguments. This matters for things like
1210 // struct A { void *operator new(size_t, int = 0); ... };
1211 // A *a = new A()
1212 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1213
1214 if (isPlacementNew) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001215 // C++ [expr.new]p20:
1216 // A declaration of a placement deallocation function matches the
1217 // declaration of a placement allocation function if it has the
1218 // same number of parameters and, after parameter transformations
1219 // (8.3.5), all parameter types except the first are
1220 // identical. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001221 //
Douglas Gregor6d908702010-02-26 05:06:18 +00001222 // To perform this comparison, we compute the function type that
1223 // the deallocation function should have, and use that type both
1224 // for template argument deduction and for comparison purposes.
John McCalle23cf432010-12-14 08:05:40 +00001225 //
1226 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6d908702010-02-26 05:06:18 +00001227 QualType ExpectedFunctionType;
1228 {
1229 const FunctionProtoType *Proto
1230 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00001231
Douglas Gregor6d908702010-02-26 05:06:18 +00001232 llvm::SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001233 ArgTypes.push_back(Context.VoidPtrTy);
Douglas Gregor6d908702010-02-26 05:06:18 +00001234 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1235 ArgTypes.push_back(Proto->getArgType(I));
1236
John McCalle23cf432010-12-14 08:05:40 +00001237 FunctionProtoType::ExtProtoInfo EPI;
1238 EPI.Variadic = Proto->isVariadic();
1239
Douglas Gregor6d908702010-02-26 05:06:18 +00001240 ExpectedFunctionType
1241 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
John McCalle23cf432010-12-14 08:05:40 +00001242 ArgTypes.size(), EPI);
Douglas Gregor6d908702010-02-26 05:06:18 +00001243 }
1244
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001245 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001246 DEnd = FoundDelete.end();
1247 D != DEnd; ++D) {
1248 FunctionDecl *Fn = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001249 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6d908702010-02-26 05:06:18 +00001250 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1251 // Perform template argument deduction to try to match the
1252 // expected function type.
1253 TemplateDeductionInfo Info(Context, StartLoc);
1254 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1255 continue;
1256 } else
1257 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1258
1259 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001260 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001261 }
1262 } else {
1263 // C++ [expr.new]p20:
1264 // [...] Any non-placement deallocation function matches a
1265 // non-placement allocation function. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001266 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001267 DEnd = FoundDelete.end();
1268 D != DEnd; ++D) {
1269 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1270 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001271 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001272 }
1273 }
1274
1275 // C++ [expr.new]p20:
1276 // [...] If the lookup finds a single matching deallocation
1277 // function, that function will be called; otherwise, no
1278 // deallocation function will be called.
1279 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001280 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001281
1282 // C++0x [expr.new]p20:
1283 // If the lookup finds the two-parameter form of a usual
1284 // deallocation function (3.7.4.2) and that function, considered
1285 // as a placement deallocation function, would have been
1286 // selected as a match for the allocation function, the program
1287 // is ill-formed.
1288 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1289 isNonPlacementDeallocationFunction(OperatorDelete)) {
1290 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001291 << SourceRange(PlaceArgs[0]->getLocStart(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001292 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1293 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1294 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001295 } else {
1296 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001297 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001298 }
1299 }
1300
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001301 return false;
1302}
1303
Sebastian Redl7f662392008-12-04 22:20:51 +00001304/// FindAllocationOverload - Find an fitting overload for the allocation
1305/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001306bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1307 DeclarationName Name, Expr** Args,
1308 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +00001309 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001310 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1311 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001312 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001313 if (AllowMissing)
1314 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001315 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001316 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001317 }
1318
John McCall90c8c572010-03-18 08:19:33 +00001319 if (R.isAmbiguous())
1320 return true;
1321
1322 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001323
John McCall5769d612010-02-08 23:07:23 +00001324 OverloadCandidateSet Candidates(StartLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001325 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001326 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001327 // Even member operator new/delete are implicitly treated as
1328 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001329 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001330
John McCall9aa472c2010-03-19 07:35:19 +00001331 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1332 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001333 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1334 Candidates,
1335 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001336 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001337 }
1338
John McCall9aa472c2010-03-19 07:35:19 +00001339 FunctionDecl *Fn = cast<FunctionDecl>(D);
1340 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001341 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001342 }
1343
1344 // Do the resolution.
1345 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00001346 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001347 case OR_Success: {
1348 // Got one!
1349 FunctionDecl *FnDecl = Best->Function;
1350 // The first argument is size_t, and the first parameter must be size_t,
1351 // too. This is checked on declaration and can be assumed. (It can't be
1352 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001353 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001354 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1355 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
John McCall60d7b3a2010-08-24 06:29:42 +00001356 ExprResult Result
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001357 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001358 Context,
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001359 FnDecl->getParamDecl(i)),
1360 SourceLocation(),
John McCall3fa5cae2010-10-26 07:05:15 +00001361 Owned(Args[i]));
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001362 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001363 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001364
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001365 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001366 }
1367 Operator = FnDecl;
John McCall9aa472c2010-03-19 07:35:19 +00001368 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001369 return false;
1370 }
1371
1372 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +00001373 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001374 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001375 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001376 return true;
1377
1378 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +00001379 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +00001380 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001381 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001382 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001383
1384 case OR_Deleted:
1385 Diag(StartLoc, diag::err_ovl_deleted_call)
1386 << Best->Function->isDeleted()
1387 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001388 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001389 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001390 }
1391 assert(false && "Unreachable, bad result from BestViableFunction");
1392 return true;
1393}
1394
1395
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001396/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1397/// delete. These are:
1398/// @code
1399/// void* operator new(std::size_t) throw(std::bad_alloc);
1400/// void* operator new[](std::size_t) throw(std::bad_alloc);
1401/// void operator delete(void *) throw();
1402/// void operator delete[](void *) throw();
1403/// @endcode
1404/// Note that the placement and nothrow forms of new are *not* implicitly
1405/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001406void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001407 if (GlobalNewDeleteDeclared)
1408 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001409
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001410 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001411 // [...] The following allocation and deallocation functions (18.4) are
1412 // implicitly declared in global scope in each translation unit of a
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001413 // program
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001414 //
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001415 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001416 // void* operator new[](std::size_t) throw(std::bad_alloc);
1417 // void operator delete(void*) throw();
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001418 // void operator delete[](void*) throw();
1419 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001420 // These implicit declarations introduce only the function names operator
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001421 // new, operator new[], operator delete, operator delete[].
1422 //
1423 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1424 // "std" or "bad_alloc" as necessary to form the exception specification.
1425 // However, we do not make these implicit declarations visible to name
1426 // lookup.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001427 if (!StdBadAlloc) {
1428 // The "std::bad_alloc" class has not yet been declared, so build it
1429 // implicitly.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001430 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1431 getOrCreateStdNamespace(),
1432 SourceLocation(),
1433 &PP.getIdentifierTable().get("bad_alloc"),
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001434 SourceLocation(), 0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001435 getStdBadAlloc()->setImplicit(true);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001436 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001437
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001438 GlobalNewDeleteDeclared = true;
1439
1440 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1441 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001442 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001443
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001444 DeclareGlobalAllocationFunction(
1445 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001446 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001447 DeclareGlobalAllocationFunction(
1448 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001449 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001450 DeclareGlobalAllocationFunction(
1451 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1452 Context.VoidTy, VoidPtr);
1453 DeclareGlobalAllocationFunction(
1454 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1455 Context.VoidTy, VoidPtr);
1456}
1457
1458/// DeclareGlobalAllocationFunction - Declares a single implicit global
1459/// allocation function if it doesn't already exist.
1460void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001461 QualType Return, QualType Argument,
1462 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001463 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1464
1465 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001466 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001467 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001468 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001469 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001470 // Only look at non-template functions, as it is the predefined,
1471 // non-templated allocation function we are trying to declare here.
1472 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1473 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001474 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001475 Func->getParamDecl(0)->getType().getUnqualifiedType());
1476 // FIXME: Do we need to check for default arguments here?
Douglas Gregor7b868622010-08-18 15:06:25 +00001477 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1478 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00001479 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001480 return;
Douglas Gregor7b868622010-08-18 15:06:25 +00001481 }
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001482 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001483 }
1484 }
1485
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001486 QualType BadAllocType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001487 bool HasBadAllocExceptionSpec
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001488 = (Name.getCXXOverloadedOperator() == OO_New ||
1489 Name.getCXXOverloadedOperator() == OO_Array_New);
1490 if (HasBadAllocExceptionSpec) {
1491 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001492 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001493 }
John McCalle23cf432010-12-14 08:05:40 +00001494
1495 FunctionProtoType::ExtProtoInfo EPI;
1496 EPI.HasExceptionSpec = true;
1497 if (HasBadAllocExceptionSpec) {
1498 EPI.NumExceptions = 1;
1499 EPI.Exceptions = &BadAllocType;
1500 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001501
John McCalle23cf432010-12-14 08:05:40 +00001502 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001503 FunctionDecl *Alloc =
1504 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCalld931b082010-08-26 03:08:43 +00001505 FnType, /*TInfo=*/0, SC_None,
1506 SC_None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001507 Alloc->setImplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001508
Nuno Lopesfc284482009-12-16 16:59:22 +00001509 if (AddMallocAttr)
Sean Huntcf807c42010-08-18 23:23:40 +00001510 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001511
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001512 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00001513 0, Argument, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00001514 SC_None,
1515 SC_None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00001516 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001517
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001518 // FIXME: Also add this declaration to the IdentifierResolver, but
1519 // make sure it is at the end of the chain to coincide with the
1520 // global scope.
John McCall5f1e0942010-08-24 08:50:51 +00001521 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001522}
1523
Anders Carlsson78f74552009-11-15 18:45:20 +00001524bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1525 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00001526 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001527 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001528 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001529 LookupQualifiedName(Found, RD);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001530
John McCalla24dc2e2009-11-17 02:14:36 +00001531 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001532 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001533
Chandler Carruth23893242010-06-28 00:30:51 +00001534 Found.suppressDiagnostics();
1535
John McCall046a7462010-08-04 00:31:26 +00001536 llvm::SmallVector<DeclAccessPair,4> Matches;
Anders Carlsson78f74552009-11-15 18:45:20 +00001537 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1538 F != FEnd; ++F) {
Chandler Carruth09556fd2010-08-08 07:04:00 +00001539 NamedDecl *ND = (*F)->getUnderlyingDecl();
1540
1541 // Ignore template operator delete members from the check for a usual
1542 // deallocation function.
1543 if (isa<FunctionTemplateDecl>(ND))
1544 continue;
1545
1546 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall046a7462010-08-04 00:31:26 +00001547 Matches.push_back(F.getPair());
1548 }
1549
1550 // There's exactly one suitable operator; pick it.
1551 if (Matches.size() == 1) {
1552 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
1553 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1554 Matches[0]);
1555 return false;
1556
1557 // We found multiple suitable operators; complain about the ambiguity.
1558 } else if (!Matches.empty()) {
1559 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1560 << Name << RD;
1561
1562 for (llvm::SmallVectorImpl<DeclAccessPair>::iterator
1563 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1564 Diag((*F)->getUnderlyingDecl()->getLocation(),
1565 diag::note_member_declared_here) << Name;
1566 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001567 }
1568
1569 // We did find operator delete/operator delete[] declarations, but
1570 // none of them were suitable.
1571 if (!Found.empty()) {
1572 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1573 << Name << RD;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001574
Anders Carlsson78f74552009-11-15 18:45:20 +00001575 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
John McCall046a7462010-08-04 00:31:26 +00001576 F != FEnd; ++F)
1577 Diag((*F)->getUnderlyingDecl()->getLocation(),
1578 diag::note_member_declared_here) << Name;
Anders Carlsson78f74552009-11-15 18:45:20 +00001579
1580 return true;
1581 }
1582
1583 // Look for a global declaration.
1584 DeclareGlobalNewDelete();
1585 DeclContext *TUDecl = Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001586
Anders Carlsson78f74552009-11-15 18:45:20 +00001587 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1588 Expr* DeallocArgs[1];
1589 DeallocArgs[0] = &Null;
1590 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1591 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1592 Operator))
1593 return true;
1594
1595 assert(Operator && "Did not find a deallocation function!");
1596 return false;
1597}
1598
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001599/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1600/// @code ::delete ptr; @endcode
1601/// or
1602/// @code delete [] ptr; @endcode
John McCall60d7b3a2010-08-24 06:29:42 +00001603ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001604Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John McCall9ae2f072010-08-23 23:25:46 +00001605 bool ArrayForm, Expr *Ex) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001606 // C++ [expr.delete]p1:
1607 // The operand shall have a pointer type, or a class type having a single
1608 // conversion function to a pointer type. The result has type void.
1609 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001610 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1611
Anders Carlssond67c4c32009-08-16 20:29:29 +00001612 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001613 bool ArrayFormAsWritten = ArrayForm;
John McCall6ec278d2011-01-27 09:37:56 +00001614 bool UsualArrayDeleteWantsSize = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001615
Sebastian Redl28507842009-02-26 14:39:58 +00001616 if (!Ex->isTypeDependent()) {
1617 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001618
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001619 if (const RecordType *Record = Type->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001620 if (RequireCompleteType(StartLoc, Type,
Douglas Gregor254a9422010-07-29 14:44:35 +00001621 PDiag(diag::err_delete_incomplete_class_type)))
1622 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001623
John McCall32daa422010-03-31 01:36:47 +00001624 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1625
Fariborz Jahanian53462782009-09-11 21:44:33 +00001626 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001627 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001628 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001629 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001630 NamedDecl *D = I.getDecl();
1631 if (isa<UsingShadowDecl>(D))
1632 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1633
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001634 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001635 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001636 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001637
John McCall32daa422010-03-31 01:36:47 +00001638 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001639
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001640 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1641 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedman13578692010-08-05 02:49:48 +00001642 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001643 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001644 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001645 if (ObjectPtrConversions.size() == 1) {
1646 // We have a single conversion to a pointer-to-object type. Perform
1647 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001648 // TODO: don't redo the conversion calculation.
John McCall32daa422010-03-31 01:36:47 +00001649 if (!PerformImplicitConversion(Ex,
1650 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +00001651 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001652 Type = Ex->getType();
1653 }
1654 }
1655 else if (ObjectPtrConversions.size() > 1) {
1656 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1657 << Type << Ex->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001658 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1659 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001660 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001661 }
Sebastian Redl28507842009-02-26 14:39:58 +00001662 }
1663
Sebastian Redlf53597f2009-03-15 17:47:39 +00001664 if (!Type->isPointerType())
1665 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1666 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001667
Ted Kremenek6217b802009-07-29 21:53:49 +00001668 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor94a61572010-05-24 17:01:56 +00001669 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001670 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregor94a61572010-05-24 17:01:56 +00001671 // effectively bans deletion of "void*". However, most compilers support
1672 // this, so we treat it as a warning unless we're in a SFINAE context.
1673 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1674 << Type << Ex->getSourceRange();
1675 } else if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001676 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1677 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001678 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001679 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +00001680 PDiag(diag::warn_delete_incomplete)
1681 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001682 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +00001683
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001684 // C++ [expr.delete]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001685 // [Note: a pointer to a const type can be the operand of a
1686 // delete-expression; it is not necessary to cast away the constness
1687 // (5.2.11) of the pointer expression before it is used as the operand
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001688 // of the delete-expression. ]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001689 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
John McCall2de56d12010-08-25 11:45:40 +00001690 CK_NoOp);
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001691
1692 if (Pointee->isArrayType() && !ArrayForm) {
1693 Diag(StartLoc, diag::warn_delete_array_type)
1694 << Type << Ex->getSourceRange()
1695 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1696 ArrayForm = true;
1697 }
1698
Anders Carlssond67c4c32009-08-16 20:29:29 +00001699 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1700 ArrayForm ? OO_Array_Delete : OO_Delete);
1701
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001702 QualType PointeeElem = Context.getBaseElementType(Pointee);
1703 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001704 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1705
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001706 if (!UseGlobal &&
Anders Carlsson78f74552009-11-15 18:45:20 +00001707 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001708 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001709
John McCall6ec278d2011-01-27 09:37:56 +00001710 // If we're allocating an array of records, check whether the
1711 // usual operator delete[] has a size_t parameter.
1712 if (ArrayForm) {
1713 // If the user specifically asked to use the global allocator,
1714 // we'll need to do the lookup into the class.
1715 if (UseGlobal)
1716 UsualArrayDeleteWantsSize =
1717 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
1718
1719 // Otherwise, the usual operator delete[] should be the
1720 // function we just found.
1721 else if (isa<CXXMethodDecl>(OperatorDelete))
1722 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
1723 }
1724
Anders Carlsson78f74552009-11-15 18:45:20 +00001725 if (!RD->hasTrivialDestructor())
Douglas Gregor9b623632010-10-12 23:32:35 +00001726 if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001727 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001728 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor9b623632010-10-12 23:32:35 +00001729 DiagnoseUseOfDecl(Dtor, StartLoc);
1730 }
Anders Carlssond67c4c32009-08-16 20:29:29 +00001731 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001732
Anders Carlssond67c4c32009-08-16 20:29:29 +00001733 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001734 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001735 DeclareGlobalNewDelete();
1736 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001737 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +00001738 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001739 OperatorDelete))
1740 return ExprError();
1741 }
Mike Stump1eb44332009-09-09 15:08:12 +00001742
John McCall9c82afc2010-04-20 02:18:25 +00001743 MarkDeclarationReferenced(StartLoc, OperatorDelete);
John McCall6ec278d2011-01-27 09:37:56 +00001744
Douglas Gregord880f522011-02-01 15:50:11 +00001745 // Check access and ambiguity of operator delete and destructor.
1746 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
1747 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1748 if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
1749 CheckDestructorAccess(Ex->getExprLoc(), Dtor,
1750 PDiag(diag::err_access_dtor) << PointeeElem);
1751 }
1752 }
1753
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001754 }
1755
Sebastian Redlf53597f2009-03-15 17:47:39 +00001756 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
John McCall6ec278d2011-01-27 09:37:56 +00001757 ArrayFormAsWritten,
1758 UsualArrayDeleteWantsSize,
1759 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001760}
1761
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001762/// \brief Check the use of the given variable as a C++ condition in an if,
1763/// while, do-while, or switch statement.
John McCall60d7b3a2010-08-24 06:29:42 +00001764ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCallf89e55a2010-11-18 06:31:45 +00001765 SourceLocation StmtLoc,
1766 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001767 QualType T = ConditionVar->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001768
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001769 // C++ [stmt.select]p2:
1770 // The declarator shall not specify a function or an array.
1771 if (T->isFunctionType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001772 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001773 diag::err_invalid_use_of_function_type)
1774 << ConditionVar->getSourceRange());
1775 else if (T->isArrayType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001776 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001777 diag::err_invalid_use_of_array_type)
1778 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001779
Douglas Gregor586596f2010-05-06 17:25:47 +00001780 Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001781 ConditionVar->getLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00001782 ConditionVar->getType().getNonReferenceType(),
John McCall09431682010-11-18 19:01:18 +00001783 VK_LValue);
Douglas Gregorff331c12010-07-25 18:17:45 +00001784 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc))
Douglas Gregor586596f2010-05-06 17:25:47 +00001785 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001786
Douglas Gregor586596f2010-05-06 17:25:47 +00001787 return Owned(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001788}
1789
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001790/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1791bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1792 // C++ 6.4p4:
1793 // The value of a condition that is an initialized declaration in a statement
1794 // other than a switch statement is the value of the declared variable
1795 // implicitly converted to type bool. If that conversion is ill-formed, the
1796 // program is ill-formed.
1797 // The value of a condition that is an expression is the value of the
1798 // expression, implicitly converted to bool.
1799 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001800 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001801}
Douglas Gregor77a52232008-09-12 00:47:35 +00001802
1803/// Helper function to determine whether this is the (deprecated) C++
1804/// conversion from a string literal to a pointer to non-const char or
1805/// non-const wchar_t (for narrow and wide string literals,
1806/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001807bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001808Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1809 // Look inside the implicit cast, if it exists.
1810 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1811 From = Cast->getSubExpr();
1812
1813 // A string literal (2.13.4) that is not a wide string literal can
1814 // be converted to an rvalue of type "pointer to char"; a wide
1815 // string literal can be converted to an rvalue of type "pointer
1816 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00001817 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00001818 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001819 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001820 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001821 // This conversion is considered only when there is an
1822 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001823 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001824 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1825 (!StrLit->isWide() &&
1826 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1827 ToPointeeType->getKind() == BuiltinType::Char_S))))
1828 return true;
1829 }
1830
1831 return false;
1832}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001833
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001834static ExprResult BuildCXXCastArgument(Sema &S,
John McCall2de56d12010-08-25 11:45:40 +00001835 SourceLocation CastLoc,
1836 QualType Ty,
1837 CastKind Kind,
1838 CXXMethodDecl *Method,
Douglas Gregor83eecbe2011-01-20 01:32:05 +00001839 NamedDecl *FoundDecl,
John McCall2de56d12010-08-25 11:45:40 +00001840 Expr *From) {
Douglas Gregorba70ab62010-04-16 22:17:36 +00001841 switch (Kind) {
1842 default: assert(0 && "Unhandled cast kind!");
John McCall2de56d12010-08-25 11:45:40 +00001843 case CK_ConstructorConversion: {
John McCallca0408f2010-08-23 06:44:23 +00001844 ASTOwningVector<Expr*> ConstructorArgs(S);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001845
Douglas Gregorba70ab62010-04-16 22:17:36 +00001846 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
John McCallf312b1e2010-08-26 23:41:50 +00001847 MultiExprArg(&From, 1),
Douglas Gregorba70ab62010-04-16 22:17:36 +00001848 CastLoc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00001849 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001850
1851 ExprResult Result =
1852 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
John McCall7a1fad32010-08-24 07:32:53 +00001853 move_arg(ConstructorArgs),
Chandler Carruth428edaf2010-10-25 08:47:36 +00001854 /*ZeroInit*/ false, CXXConstructExpr::CK_Complete,
1855 SourceRange());
Douglas Gregorba70ab62010-04-16 22:17:36 +00001856 if (Result.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00001857 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001858
Douglas Gregorba70ab62010-04-16 22:17:36 +00001859 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1860 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001861
John McCall2de56d12010-08-25 11:45:40 +00001862 case CK_UserDefinedConversion: {
Douglas Gregorba70ab62010-04-16 22:17:36 +00001863 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001864
Douglas Gregorba70ab62010-04-16 22:17:36 +00001865 // Create an implicit call expr that calls it.
Douglas Gregor83eecbe2011-01-20 01:32:05 +00001866 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00001867 if (Result.isInvalid())
1868 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001869
Douglas Gregorf2ae5262011-01-20 00:18:04 +00001870 return S.MaybeBindToTemporary(Result.get());
Douglas Gregorba70ab62010-04-16 22:17:36 +00001871 }
1872 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001873}
Douglas Gregorba70ab62010-04-16 22:17:36 +00001874
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001875/// PerformImplicitConversion - Perform an implicit conversion of the
1876/// expression From to the type ToType using the pre-computed implicit
1877/// conversion sequence ICS. Returns true if there was an error, false
1878/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001879/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001880/// used in the error message.
1881bool
1882Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1883 const ImplicitConversionSequence &ICS,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001884 AssignmentAction Action, bool CStyle) {
John McCall1d318332010-01-12 00:44:57 +00001885 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001886 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001887 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001888 CStyle))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001889 return true;
1890 break;
1891
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001892 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001893
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001894 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCalldaa8e4e2010-11-15 09:13:47 +00001895 CastKind CastKind;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001896 QualType BeforeToType;
1897 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCall2de56d12010-08-25 11:45:40 +00001898 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001899
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001900 // If the user-defined conversion is specified by a conversion function,
1901 // the initial standard conversion sequence converts the source type to
1902 // the implicit object parameter of the conversion function.
1903 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCall9ec94452010-12-04 09:57:16 +00001904 } else {
1905 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCall2de56d12010-08-25 11:45:40 +00001906 CastKind = CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001907 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001908 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001909 // If the user-defined conversion is specified by a constructor, the
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001910 // initial standard conversion sequence converts the source type to the
1911 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001912 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1913 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001914 }
Douglas Gregora3998bd2010-12-02 21:47:04 +00001915 // Watch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001916 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001917 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001918 ICS.UserDefined.Before, AA_Converting,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001919 CStyle))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001920 return true;
1921 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001922
1923 ExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00001924 = BuildCXXCastArgument(*this,
1925 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00001926 ToType.getNonReferenceType(),
Douglas Gregor83eecbe2011-01-20 01:32:05 +00001927 CastKind, cast<CXXMethodDecl>(FD),
1928 ICS.UserDefined.FoundConversionFunction,
John McCall9ae2f072010-08-23 23:25:46 +00001929 From);
Anders Carlsson0aebc812009-09-09 21:33:21 +00001930
1931 if (CastArg.isInvalid())
1932 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001933
1934 From = CastArg.takeAs<Expr>();
1935
Eli Friedmand8889622009-11-27 04:41:50 +00001936 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001937 AA_Converting, CStyle);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001938 }
John McCall1d318332010-01-12 00:44:57 +00001939
1940 case ImplicitConversionSequence::AmbiguousConversion:
John McCall120d63c2010-08-24 20:38:10 +00001941 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall1d318332010-01-12 00:44:57 +00001942 PDiag(diag::err_typecheck_ambiguous_condition)
1943 << From->getSourceRange());
1944 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001945
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001946 case ImplicitConversionSequence::EllipsisConversion:
1947 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001948 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001949
1950 case ImplicitConversionSequence::BadConversion:
1951 return true;
1952 }
1953
1954 // Everything went well.
1955 return false;
1956}
1957
1958/// PerformImplicitConversion - Perform an implicit conversion of the
1959/// expression From to the type ToType by following the standard
1960/// conversion sequence SCS. Returns true if there was an error, false
1961/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001962/// expression. Flavor is the context in which we're performing this
1963/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001964bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001965Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001966 const StandardConversionSequence& SCS,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001967 AssignmentAction Action, bool CStyle) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001968 // Overall FIXME: we are recomputing too many types here and doing far too
1969 // much extra work. What this means is that we need to keep track of more
1970 // information that is computed when we try the implicit conversion initially,
1971 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001972 QualType FromType = From->getType();
1973
Douglas Gregor225c41e2008-11-03 19:09:14 +00001974 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001975 // FIXME: When can ToType be a reference type?
1976 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001977 if (SCS.Second == ICK_Derived_To_Base) {
John McCallca0408f2010-08-23 06:44:23 +00001978 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001979 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCallca0408f2010-08-23 06:44:23 +00001980 MultiExprArg(*this, &From, 1),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001981 /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001982 ConstructorArgs))
1983 return true;
John McCall60d7b3a2010-08-24 06:29:42 +00001984 ExprResult FromResult =
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001985 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1986 ToType, SCS.CopyConstructor,
John McCall7a1fad32010-08-24 07:32:53 +00001987 move_arg(ConstructorArgs),
1988 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00001989 CXXConstructExpr::CK_Complete,
1990 SourceRange());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001991 if (FromResult.isInvalid())
1992 return true;
1993 From = FromResult.takeAs<Expr>();
1994 return false;
1995 }
John McCall60d7b3a2010-08-24 06:29:42 +00001996 ExprResult FromResult =
Mike Stump1eb44332009-09-09 15:08:12 +00001997 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1998 ToType, SCS.CopyConstructor,
John McCall7a1fad32010-08-24 07:32:53 +00001999 MultiExprArg(*this, &From, 1),
2000 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00002001 CXXConstructExpr::CK_Complete,
2002 SourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +00002003
Anders Carlssonda3f4e22009-08-25 05:12:04 +00002004 if (FromResult.isInvalid())
2005 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002006
Anders Carlssonda3f4e22009-08-25 05:12:04 +00002007 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00002008 return false;
2009 }
2010
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002011 // Resolve overloaded function references.
2012 if (Context.hasSameType(FromType, Context.OverloadTy)) {
2013 DeclAccessPair Found;
2014 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2015 true, Found);
2016 if (!Fn)
2017 return true;
2018
2019 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
2020 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002021
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002022 From = FixOverloadedFunctionReference(From, Found, Fn);
2023 FromType = From->getType();
2024 }
2025
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002026 // Perform the first implicit conversion.
2027 switch (SCS.First) {
2028 case ICK_Identity:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002029 // Nothing to do.
2030 break;
2031
John McCallf6a16482010-12-04 03:47:34 +00002032 case ICK_Lvalue_To_Rvalue:
2033 // Should this get its own ICK?
2034 if (From->getObjectKind() == OK_ObjCProperty) {
2035 ConvertPropertyForRValue(From);
John McCall241d5582010-12-07 22:54:16 +00002036 if (!From->isGLValue()) break;
John McCallf6a16482010-12-04 03:47:34 +00002037 }
2038
Chandler Carruth35001ca2011-02-17 21:10:52 +00002039 // Check for trivial buffer overflows.
2040 if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(From))
2041 CheckArrayAccess(AE);
2042
John McCallf6a16482010-12-04 03:47:34 +00002043 FromType = FromType.getUnqualifiedType();
2044 From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
2045 From, 0, VK_RValue);
2046 break;
2047
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002048 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002049 FromType = Context.getArrayDecayedType(FromType);
John McCall2de56d12010-08-25 11:45:40 +00002050 ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002051 break;
2052
2053 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002054 FromType = Context.getPointerType(FromType);
John McCall2de56d12010-08-25 11:45:40 +00002055 ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002056 break;
2057
2058 default:
2059 assert(false && "Improper first standard conversion");
2060 break;
2061 }
2062
2063 // Perform the second implicit conversion
2064 switch (SCS.Second) {
2065 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002066 // If both sides are functions (or pointers/references to them), there could
2067 // be incompatible exception declarations.
2068 if (CheckExceptionSpecCompatibility(From, ToType))
2069 return true;
2070 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002071 break;
2072
Douglas Gregor43c79c22009-12-09 00:47:37 +00002073 case ICK_NoReturn_Adjustment:
2074 // If both sides are functions (or pointers/references to them), there could
2075 // be incompatible exception declarations.
2076 if (CheckExceptionSpecCompatibility(From, ToType))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002077 return true;
2078
John McCalle6a365d2010-12-19 02:44:49 +00002079 ImpCastExprToType(From, ToType, CK_NoOp);
Douglas Gregor43c79c22009-12-09 00:47:37 +00002080 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002081
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002082 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002083 case ICK_Integral_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00002084 ImpCastExprToType(From, ToType, CK_IntegralCast);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002085 break;
2086
2087 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002088 case ICK_Floating_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00002089 ImpCastExprToType(From, ToType, CK_FloatingCast);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002090 break;
2091
2092 case ICK_Complex_Promotion:
John McCalldaa8e4e2010-11-15 09:13:47 +00002093 case ICK_Complex_Conversion: {
2094 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2095 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2096 CastKind CK;
2097 if (FromEl->isRealFloatingType()) {
2098 if (ToEl->isRealFloatingType())
2099 CK = CK_FloatingComplexCast;
2100 else
2101 CK = CK_FloatingComplexToIntegralComplex;
2102 } else if (ToEl->isRealFloatingType()) {
2103 CK = CK_IntegralComplexToFloatingComplex;
2104 } else {
2105 CK = CK_IntegralComplexCast;
2106 }
2107 ImpCastExprToType(From, ToType, CK);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002108 break;
John McCalldaa8e4e2010-11-15 09:13:47 +00002109 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00002110
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002111 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00002112 if (ToType->isRealFloatingType())
John McCall2de56d12010-08-25 11:45:40 +00002113 ImpCastExprToType(From, ToType, CK_IntegralToFloating);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002114 else
John McCall2de56d12010-08-25 11:45:40 +00002115 ImpCastExprToType(From, ToType, CK_FloatingToIntegral);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002116 break;
2117
Douglas Gregorf9201e02009-02-11 23:02:49 +00002118 case ICK_Compatible_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00002119 ImpCastExprToType(From, ToType, CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002120 break;
2121
Anders Carlsson61faec12009-09-12 04:46:44 +00002122 case ICK_Pointer_Conversion: {
Douglas Gregora3998bd2010-12-02 21:47:04 +00002123 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor45920e82008-12-19 17:40:08 +00002124 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00002125 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00002126 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00002127 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00002128 << From->getSourceRange();
2129 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002130
John McCalldaa8e4e2010-11-15 09:13:47 +00002131 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002132 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002133 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002134 return true;
John McCall5baba9d2010-08-25 10:28:54 +00002135 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002136 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00002137 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002138
Anders Carlsson61faec12009-09-12 04:46:44 +00002139 case ICK_Pointer_Member: {
John McCalldaa8e4e2010-11-15 09:13:47 +00002140 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002141 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002142 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
Anders Carlsson61faec12009-09-12 04:46:44 +00002143 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002144 if (CheckExceptionSpecCompatibility(From, ToType))
2145 return true;
John McCall5baba9d2010-08-25 10:28:54 +00002146 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
Anders Carlsson61faec12009-09-12 04:46:44 +00002147 break;
2148 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00002149 case ICK_Boolean_Conversion: {
John McCalldaa8e4e2010-11-15 09:13:47 +00002150 CastKind Kind = CK_Invalid;
2151 switch (FromType->getScalarTypeKind()) {
2152 case Type::STK_Pointer: Kind = CK_PointerToBoolean; break;
2153 case Type::STK_MemberPointer: Kind = CK_MemberPointerToBoolean; break;
2154 case Type::STK_Bool: llvm_unreachable("bool -> bool conversion?");
2155 case Type::STK_Integral: Kind = CK_IntegralToBoolean; break;
2156 case Type::STK_Floating: Kind = CK_FloatingToBoolean; break;
2157 case Type::STK_IntegralComplex: Kind = CK_IntegralComplexToBoolean; break;
2158 case Type::STK_FloatingComplex: Kind = CK_FloatingComplexToBoolean; break;
2159 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002160
Anders Carlssonbc0e0782009-11-23 20:04:44 +00002161 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002162 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00002163 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002164
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002165 case ICK_Derived_To_Base: {
John McCallf871d0c2010-08-07 06:22:56 +00002166 CXXCastPath BasePath;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002167 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002168 ToType.getNonReferenceType(),
2169 From->getLocStart(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002170 From->getSourceRange(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002171 &BasePath,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002172 CStyle))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002173 return true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002174
Sebastian Redl906082e2010-07-20 04:20:21 +00002175 ImpCastExprToType(From, ToType.getNonReferenceType(),
John McCall2de56d12010-08-25 11:45:40 +00002176 CK_DerivedToBase, CastCategory(From),
John McCallf871d0c2010-08-07 06:22:56 +00002177 &BasePath);
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002178 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002179 }
2180
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002181 case ICK_Vector_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00002182 ImpCastExprToType(From, ToType, CK_BitCast);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002183 break;
2184
2185 case ICK_Vector_Splat:
John McCall2de56d12010-08-25 11:45:40 +00002186 ImpCastExprToType(From, ToType, CK_VectorSplat);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002187 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002188
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002189 case ICK_Complex_Real:
John McCalldaa8e4e2010-11-15 09:13:47 +00002190 // Case 1. x -> _Complex y
2191 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2192 QualType ElType = ToComplex->getElementType();
2193 bool isFloatingComplex = ElType->isRealFloatingType();
2194
2195 // x -> y
2196 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2197 // do nothing
2198 } else if (From->getType()->isRealFloatingType()) {
2199 ImpCastExprToType(From, ElType,
2200 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral);
2201 } else {
2202 assert(From->getType()->isIntegerType());
2203 ImpCastExprToType(From, ElType,
2204 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast);
2205 }
2206 // y -> _Complex y
2207 ImpCastExprToType(From, ToType,
2208 isFloatingComplex ? CK_FloatingRealToComplex
2209 : CK_IntegralRealToComplex);
2210
2211 // Case 2. _Complex x -> y
2212 } else {
2213 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2214 assert(FromComplex);
2215
2216 QualType ElType = FromComplex->getElementType();
2217 bool isFloatingComplex = ElType->isRealFloatingType();
2218
2219 // _Complex x -> x
2220 ImpCastExprToType(From, ElType,
2221 isFloatingComplex ? CK_FloatingComplexToReal
2222 : CK_IntegralComplexToReal);
2223
2224 // x -> y
2225 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2226 // do nothing
2227 } else if (ToType->isRealFloatingType()) {
2228 ImpCastExprToType(From, ToType,
2229 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating);
2230 } else {
2231 assert(ToType->isIntegerType());
2232 ImpCastExprToType(From, ToType,
2233 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast);
2234 }
2235 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002236 break;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002237
2238 case ICK_Block_Pointer_Conversion: {
2239 ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast, VK_RValue);
2240 break;
2241 }
2242
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002243 case ICK_Lvalue_To_Rvalue:
2244 case ICK_Array_To_Pointer:
2245 case ICK_Function_To_Pointer:
2246 case ICK_Qualification:
2247 case ICK_Num_Conversion_Kinds:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002248 assert(false && "Improper second standard conversion");
2249 break;
2250 }
2251
2252 switch (SCS.Third) {
2253 case ICK_Identity:
2254 // Nothing to do.
2255 break;
2256
Sebastian Redl906082e2010-07-20 04:20:21 +00002257 case ICK_Qualification: {
2258 // The qualification keeps the category of the inner expression, unless the
2259 // target type isn't a reference.
John McCall5baba9d2010-08-25 10:28:54 +00002260 ExprValueKind VK = ToType->isReferenceType() ?
2261 CastCategory(From) : VK_RValue;
Douglas Gregor63982352010-07-13 18:40:04 +00002262 ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
John McCall2de56d12010-08-25 11:45:40 +00002263 CK_NoOp, VK);
Douglas Gregora9bff302010-02-28 18:30:25 +00002264
2265 if (SCS.DeprecatedStringLiteralToCharPtr)
2266 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2267 << ToType.getNonReferenceType();
2268
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002269 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002270 }
2271
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002272 default:
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002273 assert(false && "Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002274 break;
2275 }
2276
2277 return false;
2278}
2279
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002280ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002281 SourceLocation KWLoc,
2282 ParsedType Ty,
2283 SourceLocation RParen) {
2284 TypeSourceInfo *TSInfo;
2285 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002286
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002287 if (!TSInfo)
2288 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002289 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002290}
2291
Sebastian Redlf8aca862010-09-14 23:40:14 +00002292static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT, QualType T,
2293 SourceLocation KeyLoc) {
Douglas Gregora0506182011-01-27 20:35:44 +00002294 // FIXME: For many of these traits, we need a complete type before we can
2295 // check these properties.
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002296 assert(!T->isDependentType() &&
2297 "Cannot evaluate traits for dependent types.");
2298 ASTContext &C = Self.Context;
2299 switch(UTT) {
2300 default: assert(false && "Unknown type trait or not implemented");
2301 case UTT_IsPOD: return T->isPODType();
2302 case UTT_IsLiteral: return T->isLiteralType();
2303 case UTT_IsClass: // Fallthrough
2304 case UTT_IsUnion:
2305 if (const RecordType *Record = T->getAs<RecordType>()) {
2306 bool Union = Record->getDecl()->isUnion();
2307 return UTT == UTT_IsUnion ? Union : !Union;
2308 }
2309 return false;
2310 case UTT_IsEnum: return T->isEnumeralType();
2311 case UTT_IsPolymorphic:
2312 if (const RecordType *Record = T->getAs<RecordType>()) {
2313 // Type traits are only parsed in C++, so we've got CXXRecords.
2314 return cast<CXXRecordDecl>(Record->getDecl())->isPolymorphic();
2315 }
2316 return false;
2317 case UTT_IsAbstract:
2318 if (const RecordType *RT = T->getAs<RecordType>())
2319 return cast<CXXRecordDecl>(RT->getDecl())->isAbstract();
2320 return false;
2321 case UTT_IsEmpty:
2322 if (const RecordType *Record = T->getAs<RecordType>()) {
2323 return !Record->getDecl()->isUnion()
2324 && cast<CXXRecordDecl>(Record->getDecl())->isEmpty();
2325 }
2326 return false;
2327 case UTT_HasTrivialConstructor:
2328 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2329 // If __is_pod (type) is true then the trait is true, else if type is
2330 // a cv class or union type (or array thereof) with a trivial default
2331 // constructor ([class.ctor]) then the trait is true, else it is false.
2332 if (T->isPODType())
2333 return true;
2334 if (const RecordType *RT =
2335 C.getBaseElementType(T)->getAs<RecordType>())
2336 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialConstructor();
2337 return false;
2338 case UTT_HasTrivialCopy:
2339 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2340 // If __is_pod (type) is true or type is a reference type then
2341 // the trait is true, else if type is a cv class or union type
2342 // with a trivial copy constructor ([class.copy]) then the trait
2343 // is true, else it is false.
2344 if (T->isPODType() || T->isReferenceType())
2345 return true;
2346 if (const RecordType *RT = T->getAs<RecordType>())
2347 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2348 return false;
2349 case UTT_HasTrivialAssign:
2350 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2351 // If type is const qualified or is a reference type then the
2352 // trait is false. Otherwise if __is_pod (type) is true then the
2353 // trait is true, else if type is a cv class or union type with
2354 // a trivial copy assignment ([class.copy]) then the trait is
2355 // true, else it is false.
2356 // Note: the const and reference restrictions are interesting,
2357 // given that const and reference members don't prevent a class
2358 // from having a trivial copy assignment operator (but do cause
2359 // errors if the copy assignment operator is actually used, q.v.
2360 // [class.copy]p12).
2361
2362 if (C.getBaseElementType(T).isConstQualified())
2363 return false;
2364 if (T->isPODType())
2365 return true;
2366 if (const RecordType *RT = T->getAs<RecordType>())
2367 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2368 return false;
2369 case UTT_HasTrivialDestructor:
2370 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2371 // If __is_pod (type) is true or type is a reference type
2372 // then the trait is true, else if type is a cv class or union
2373 // type (or array thereof) with a trivial destructor
2374 // ([class.dtor]) then the trait is true, else it is
2375 // false.
2376 if (T->isPODType() || T->isReferenceType())
2377 return true;
2378 if (const RecordType *RT =
2379 C.getBaseElementType(T)->getAs<RecordType>())
2380 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2381 return false;
2382 // TODO: Propagate nothrowness for implicitly declared special members.
2383 case UTT_HasNothrowAssign:
2384 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2385 // If type is const qualified or is a reference type then the
2386 // trait is false. Otherwise if __has_trivial_assign (type)
2387 // is true then the trait is true, else if type is a cv class
2388 // or union type with copy assignment operators that are known
2389 // not to throw an exception then the trait is true, else it is
2390 // false.
2391 if (C.getBaseElementType(T).isConstQualified())
2392 return false;
2393 if (T->isReferenceType())
2394 return false;
2395 if (T->isPODType())
2396 return true;
2397 if (const RecordType *RT = T->getAs<RecordType>()) {
2398 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2399 if (RD->hasTrivialCopyAssignment())
2400 return true;
2401
2402 bool FoundAssign = false;
2403 bool AllNoThrow = true;
2404 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redlf8aca862010-09-14 23:40:14 +00002405 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2406 Sema::LookupOrdinaryName);
2407 if (Self.LookupQualifiedName(Res, RD)) {
2408 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2409 Op != OpEnd; ++Op) {
2410 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2411 if (Operator->isCopyAssignmentOperator()) {
2412 FoundAssign = true;
2413 const FunctionProtoType *CPT
2414 = Operator->getType()->getAs<FunctionProtoType>();
2415 if (!CPT->hasEmptyExceptionSpec()) {
2416 AllNoThrow = false;
2417 break;
2418 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002419 }
2420 }
2421 }
2422
2423 return FoundAssign && AllNoThrow;
2424 }
2425 return false;
2426 case UTT_HasNothrowCopy:
2427 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2428 // If __has_trivial_copy (type) is true then the trait is true, else
2429 // if type is a cv class or union type with copy constructors that are
2430 // known not to throw an exception then the trait is true, else it is
2431 // false.
2432 if (T->isPODType() || T->isReferenceType())
2433 return true;
2434 if (const RecordType *RT = T->getAs<RecordType>()) {
2435 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2436 if (RD->hasTrivialCopyConstructor())
2437 return true;
2438
2439 bool FoundConstructor = false;
2440 bool AllNoThrow = true;
2441 unsigned FoundTQs;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002442 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl5f4e8992010-09-13 21:10:20 +00002443 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002444 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002445 // A template constructor is never a copy constructor.
2446 // FIXME: However, it may actually be selected at the actual overload
2447 // resolution point.
2448 if (isa<FunctionTemplateDecl>(*Con))
2449 continue;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002450 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2451 if (Constructor->isCopyConstructor(FoundTQs)) {
2452 FoundConstructor = true;
2453 const FunctionProtoType *CPT
2454 = Constructor->getType()->getAs<FunctionProtoType>();
Sebastian Redl751025d2010-09-13 22:02:47 +00002455 // TODO: check whether evaluating default arguments can throw.
2456 // For now, we'll be conservative and assume that they can throw.
2457 if (!CPT->hasEmptyExceptionSpec() || CPT->getNumArgs() > 1) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002458 AllNoThrow = false;
2459 break;
2460 }
2461 }
2462 }
2463
2464 return FoundConstructor && AllNoThrow;
2465 }
2466 return false;
2467 case UTT_HasNothrowConstructor:
2468 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2469 // If __has_trivial_constructor (type) is true then the trait is
2470 // true, else if type is a cv class or union type (or array
2471 // thereof) with a default constructor that is known not to
2472 // throw an exception then the trait is true, else it is false.
2473 if (T->isPODType())
2474 return true;
2475 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
2476 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2477 if (RD->hasTrivialConstructor())
2478 return true;
2479
Sebastian Redl751025d2010-09-13 22:02:47 +00002480 DeclContext::lookup_const_iterator Con, ConEnd;
2481 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2482 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002483 // FIXME: In C++0x, a constructor template can be a default constructor.
2484 if (isa<FunctionTemplateDecl>(*Con))
2485 continue;
Sebastian Redl751025d2010-09-13 22:02:47 +00002486 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2487 if (Constructor->isDefaultConstructor()) {
2488 const FunctionProtoType *CPT
2489 = Constructor->getType()->getAs<FunctionProtoType>();
2490 // TODO: check whether evaluating default arguments can throw.
2491 // For now, we'll be conservative and assume that they can throw.
2492 return CPT->hasEmptyExceptionSpec() && CPT->getNumArgs() == 0;
2493 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002494 }
2495 }
2496 return false;
2497 case UTT_HasVirtualDestructor:
2498 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2499 // If type is a class type with a virtual destructor ([class.dtor])
2500 // then the trait is true, else it is false.
2501 if (const RecordType *Record = T->getAs<RecordType>()) {
2502 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redlf8aca862010-09-14 23:40:14 +00002503 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002504 return Destructor->isVirtual();
2505 }
2506 return false;
2507 }
2508}
2509
2510ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002511 SourceLocation KWLoc,
2512 TypeSourceInfo *TSInfo,
2513 SourceLocation RParen) {
2514 QualType T = TSInfo->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002515
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002516 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
2517 // all traits except __is_class, __is_enum and __is_union require a the type
Sebastian Redl607a1782010-09-08 00:48:43 +00002518 // to be complete, an array of unknown bound, or void.
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002519 if (UTT != UTT_IsClass && UTT != UTT_IsEnum && UTT != UTT_IsUnion) {
Sebastian Redl607a1782010-09-08 00:48:43 +00002520 QualType E = T;
2521 if (T->isIncompleteArrayType())
2522 E = Context.getAsArrayType(T)->getElementType();
2523 if (!T->isVoidType() &&
2524 RequireCompleteType(KWLoc, E,
Anders Carlssond497ba72009-08-26 22:59:12 +00002525 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002526 return ExprError();
2527 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00002528
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002529 bool Value = false;
2530 if (!T->isDependentType())
Sebastian Redlf8aca862010-09-14 23:40:14 +00002531 Value = EvaluateUnaryTypeTrait(*this, UTT, T, KWLoc);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002532
2533 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002534 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00002535}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002536
Francois Pichet6ad6f282010-12-07 00:08:36 +00002537ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
2538 SourceLocation KWLoc,
2539 ParsedType LhsTy,
2540 ParsedType RhsTy,
2541 SourceLocation RParen) {
2542 TypeSourceInfo *LhsTSInfo;
2543 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
2544 if (!LhsTSInfo)
2545 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
2546
2547 TypeSourceInfo *RhsTSInfo;
2548 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
2549 if (!RhsTSInfo)
2550 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
2551
2552 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
2553}
2554
2555static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
2556 QualType LhsT, QualType RhsT,
2557 SourceLocation KeyLoc) {
2558 assert((!LhsT->isDependentType() || RhsT->isDependentType()) &&
2559 "Cannot evaluate traits for dependent types.");
2560
2561 switch(BTT) {
John McCalld89d30f2011-01-28 22:02:36 +00002562 case BTT_IsBaseOf: {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002563 // C++0x [meta.rel]p2
John McCalld89d30f2011-01-28 22:02:36 +00002564 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet6ad6f282010-12-07 00:08:36 +00002565 // Base and Derived are not unions and name the same class type without
2566 // regard to cv-qualifiers.
Francois Pichet6ad6f282010-12-07 00:08:36 +00002567
John McCalld89d30f2011-01-28 22:02:36 +00002568 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
2569 if (!lhsRecord) return false;
2570
2571 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
2572 if (!rhsRecord) return false;
2573
2574 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
2575 == (lhsRecord == rhsRecord));
2576
2577 if (lhsRecord == rhsRecord)
2578 return !lhsRecord->getDecl()->isUnion();
2579
2580 // C++0x [meta.rel]p2:
2581 // If Base and Derived are class types and are different types
2582 // (ignoring possible cv-qualifiers) then Derived shall be a
2583 // complete type.
2584 if (Self.RequireCompleteType(KeyLoc, RhsT,
2585 diag::err_incomplete_type_used_in_type_trait_expr))
2586 return false;
2587
2588 return cast<CXXRecordDecl>(rhsRecord->getDecl())
2589 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
2590 }
2591
Francois Pichetf1872372010-12-08 22:35:30 +00002592 case BTT_TypeCompatible:
2593 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
2594 RhsT.getUnqualifiedType());
Douglas Gregor9f361132011-01-27 20:28:01 +00002595
2596 case BTT_IsConvertibleTo: {
2597 // C++0x [meta.rel]p4:
2598 // Given the following function prototype:
2599 //
2600 // template <class T>
2601 // typename add_rvalue_reference<T>::type create();
2602 //
2603 // the predicate condition for a template specialization
2604 // is_convertible<From, To> shall be satisfied if and only if
2605 // the return expression in the following code would be
2606 // well-formed, including any implicit conversions to the return
2607 // type of the function:
2608 //
2609 // To test() {
2610 // return create<From>();
2611 // }
2612 //
2613 // Access checking is performed as if in a context unrelated to To and
2614 // From. Only the validity of the immediate context of the expression
2615 // of the return-statement (including conversions to the return type)
2616 // is considered.
2617 //
2618 // We model the initialization as a copy-initialization of a temporary
2619 // of the appropriate type, which for this expression is identical to the
2620 // return statement (since NRVO doesn't apply).
2621 if (LhsT->isObjectType() || LhsT->isFunctionType())
2622 LhsT = Self.Context.getRValueReferenceType(LhsT);
2623
2624 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorb608b982011-01-28 02:26:04 +00002625 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor9f361132011-01-27 20:28:01 +00002626 Expr::getValueKindForType(LhsT));
2627 Expr *FromPtr = &From;
2628 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
2629 SourceLocation()));
2630
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00002631 // Perform the initialization within a SFINAE trap at translation unit
2632 // scope.
2633 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
2634 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Douglas Gregor9f361132011-01-27 20:28:01 +00002635 InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
2636 if (Init.getKind() == InitializationSequence::FailedSequence)
2637 return false;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00002638
Douglas Gregor9f361132011-01-27 20:28:01 +00002639 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
2640 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
2641 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00002642 }
2643 llvm_unreachable("Unknown type trait or not implemented");
2644}
2645
2646ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
2647 SourceLocation KWLoc,
2648 TypeSourceInfo *LhsTSInfo,
2649 TypeSourceInfo *RhsTSInfo,
2650 SourceLocation RParen) {
2651 QualType LhsT = LhsTSInfo->getType();
2652 QualType RhsT = RhsTSInfo->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002653
John McCalld89d30f2011-01-28 22:02:36 +00002654 if (BTT == BTT_TypeCompatible) {
Francois Pichetf1872372010-12-08 22:35:30 +00002655 if (getLangOptions().CPlusPlus) {
2656 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
2657 << SourceRange(KWLoc, RParen);
2658 return ExprError();
2659 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00002660 }
2661
2662 bool Value = false;
2663 if (!LhsT->isDependentType() && !RhsT->isDependentType())
2664 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
2665
Francois Pichetf1872372010-12-08 22:35:30 +00002666 // Select trait result type.
2667 QualType ResultType;
2668 switch (BTT) {
Francois Pichetf1872372010-12-08 22:35:30 +00002669 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
2670 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
Douglas Gregor9f361132011-01-27 20:28:01 +00002671 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00002672 }
2673
Francois Pichet6ad6f282010-12-07 00:08:36 +00002674 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
2675 RhsTSInfo, Value, RParen,
Francois Pichetf1872372010-12-08 22:35:30 +00002676 ResultType));
Francois Pichet6ad6f282010-12-07 00:08:36 +00002677}
2678
John McCallf89e55a2010-11-18 06:31:45 +00002679QualType Sema::CheckPointerToMemberOperands(Expr *&lex, Expr *&rex,
2680 ExprValueKind &VK,
2681 SourceLocation Loc,
2682 bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002683 const char *OpSpelling = isIndirect ? "->*" : ".*";
2684 // C++ 5.5p2
2685 // The binary operator .* [p3: ->*] binds its second operand, which shall
2686 // be of type "pointer to member of T" (where T is a completely-defined
2687 // class type) [...]
2688 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002689 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00002690 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002691 Diag(Loc, diag::err_bad_memptr_rhs)
2692 << OpSpelling << RType << rex->getSourceRange();
2693 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00002694 }
Douglas Gregore7450f52009-03-24 19:52:54 +00002695
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002696 QualType Class(MemPtr->getClass(), 0);
2697
Douglas Gregor7d520ba2010-10-13 20:41:14 +00002698 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
2699 // member pointer points must be completely-defined. However, there is no
2700 // reason for this semantic distinction, and the rule is not enforced by
2701 // other compilers. Therefore, we do not check this property, as it is
2702 // likely to be considered a defect.
Sebastian Redl59fc2692010-04-10 10:14:54 +00002703
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002704 // C++ 5.5p2
2705 // [...] to its first operand, which shall be of class T or of a class of
2706 // which T is an unambiguous and accessible base class. [p3: a pointer to
2707 // such a class]
2708 QualType LType = lex->getType();
2709 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002710 if (const PointerType *Ptr = LType->getAs<PointerType>())
John McCallf89e55a2010-11-18 06:31:45 +00002711 LType = Ptr->getPointeeType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002712 else {
2713 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00002714 << OpSpelling << 1 << LType
Douglas Gregor849b2432010-03-31 17:46:05 +00002715 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002716 return QualType();
2717 }
2718 }
2719
Douglas Gregora4923eb2009-11-16 21:35:15 +00002720 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00002721 // If we want to check the hierarchy, we need a complete type.
2722 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
2723 << OpSpelling << (int)isIndirect)) {
2724 return QualType();
2725 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002726 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002727 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00002728 // FIXME: Would it be useful to print full ambiguity paths, or is that
2729 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002730 if (!IsDerivedFrom(LType, Class, Paths) ||
2731 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
2732 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00002733 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002734 return QualType();
2735 }
Eli Friedman3005efe2010-01-16 00:00:48 +00002736 // Cast LHS to type of use.
2737 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
John McCall5baba9d2010-08-25 10:28:54 +00002738 ExprValueKind VK =
2739 isIndirect ? VK_RValue : CastCategory(lex);
Sebastian Redl906082e2010-07-20 04:20:21 +00002740
John McCallf871d0c2010-08-07 06:22:56 +00002741 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002742 BuildBasePathArray(Paths, BasePath);
John McCall5baba9d2010-08-25 10:28:54 +00002743 ImpCastExprToType(lex, UseType, CK_DerivedToBase, VK, &BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002744 }
2745
Douglas Gregored8abf12010-07-08 06:14:04 +00002746 if (isa<CXXScalarValueInitExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00002747 // Diagnose use of pointer-to-member type which when used as
2748 // the functional cast in a pointer-to-member expression.
2749 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
2750 return QualType();
2751 }
John McCallf89e55a2010-11-18 06:31:45 +00002752
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002753 // C++ 5.5p2
2754 // The result is an object or a function of the type specified by the
2755 // second operand.
2756 // The cv qualifiers are the union of those in the pointer and the left side,
2757 // in accordance with 5.5p5 and 5.2.5.
2758 // FIXME: This returns a dereferenced member function pointer as a normal
2759 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00002760 // calling them. There's also a GCC extension to get a function pointer to the
2761 // thing, which is another complication, because this type - unlike the type
2762 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002763 // argument.
2764 // We probably need a "MemberFunctionClosureType" or something like that.
2765 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00002766 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
John McCallf89e55a2010-11-18 06:31:45 +00002767
Douglas Gregor6b4df912011-01-26 16:40:18 +00002768 // C++0x [expr.mptr.oper]p6:
2769 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002770 // ill-formed if the second operand is a pointer to member function with
2771 // ref-qualifier &. In a ->* expression or in a .* expression whose object
2772 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor6b4df912011-01-26 16:40:18 +00002773 // is a pointer to member function with ref-qualifier &&.
2774 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
2775 switch (Proto->getRefQualifier()) {
2776 case RQ_None:
2777 // Do nothing
2778 break;
2779
2780 case RQ_LValue:
2781 if (!isIndirect && !lex->Classify(Context).isLValue())
2782 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
2783 << RType << 1 << lex->getSourceRange();
2784 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002785
Douglas Gregor6b4df912011-01-26 16:40:18 +00002786 case RQ_RValue:
2787 if (isIndirect || !lex->Classify(Context).isRValue())
2788 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
2789 << RType << 0 << lex->getSourceRange();
2790 break;
2791 }
2792 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002793
John McCallf89e55a2010-11-18 06:31:45 +00002794 // C++ [expr.mptr.oper]p6:
2795 // The result of a .* expression whose second operand is a pointer
2796 // to a data member is of the same value category as its
2797 // first operand. The result of a .* expression whose second
2798 // operand is a pointer to a member function is a prvalue. The
2799 // result of an ->* expression is an lvalue if its second operand
2800 // is a pointer to data member and a prvalue otherwise.
2801 if (Result->isFunctionType())
2802 VK = VK_RValue;
2803 else if (isIndirect)
2804 VK = VK_LValue;
2805 else
2806 VK = lex->getValueKind();
2807
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002808 return Result;
2809}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002810
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002811/// \brief Try to convert a type to another according to C++0x 5.16p3.
2812///
2813/// This is part of the parameter validation for the ? operator. If either
2814/// value operand is a class type, the two operands are attempted to be
2815/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002816/// It returns true if the program is ill-formed and has already been diagnosed
2817/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002818static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
2819 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00002820 bool &HaveConversion,
2821 QualType &ToType) {
2822 HaveConversion = false;
2823 ToType = To->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002824
2825 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00002826 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002827 // C++0x 5.16p3
2828 // The process for determining whether an operand expression E1 of type T1
2829 // can be converted to match an operand expression E2 of type T2 is defined
2830 // as follows:
2831 // -- If E2 is an lvalue:
John McCall7eb0a9e2010-11-24 05:12:34 +00002832 bool ToIsLvalue = To->isLValue();
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002833 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002834 // E1 can be converted to match E2 if E1 can be implicitly converted to
2835 // type "lvalue reference to T2", subject to the constraint that in the
2836 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002837 QualType T = Self.Context.getLValueReferenceType(ToType);
2838 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002839
Douglas Gregorb70cf442010-03-26 20:14:36 +00002840 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2841 if (InitSeq.isDirectReferenceBinding()) {
2842 ToType = T;
2843 HaveConversion = true;
2844 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002845 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002846
Douglas Gregorb70cf442010-03-26 20:14:36 +00002847 if (InitSeq.isAmbiguous())
2848 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002849 }
John McCallb1bdc622010-02-25 01:37:24 +00002850
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002851 // -- If E2 is an rvalue, or if the conversion above cannot be done:
2852 // -- if E1 and E2 have class type, and the underlying class types are
2853 // the same or one is a base class of the other:
2854 QualType FTy = From->getType();
2855 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002856 const RecordType *FRec = FTy->getAs<RecordType>();
2857 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002858 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00002859 Self.IsDerivedFrom(FTy, TTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002860 if (FRec && TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00002861 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002862 // E1 can be converted to match E2 if the class of T2 is the
2863 // same type as, or a base class of, the class of T1, and
2864 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00002865 if (FRec == TRec || FDerivedFromT) {
2866 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002867 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2868 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2869 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2870 HaveConversion = true;
2871 return false;
2872 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002873
Douglas Gregorb70cf442010-03-26 20:14:36 +00002874 if (InitSeq.isAmbiguous())
2875 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002876 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002877 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002878
Douglas Gregorb70cf442010-03-26 20:14:36 +00002879 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002880 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002881
Douglas Gregorb70cf442010-03-26 20:14:36 +00002882 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2883 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002884 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002885 // an rvalue).
2886 //
2887 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2888 // to the array-to-pointer or function-to-pointer conversions.
2889 if (!TTy->getAs<TagType>())
2890 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002891
Douglas Gregorb70cf442010-03-26 20:14:36 +00002892 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2893 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002894 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002895 ToType = TTy;
2896 if (InitSeq.isAmbiguous())
2897 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2898
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002899 return false;
2900}
2901
2902/// \brief Try to find a common type for two according to C++0x 5.16p5.
2903///
2904/// This is part of the parameter validation for the ? operator. If either
2905/// value operand is a class type, overload resolution is used to find a
2906/// conversion to a common type.
2907static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
Chandler Carruth82214a82011-02-18 23:54:50 +00002908 SourceLocation QuestionLoc) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002909 Expr *Args[2] = { LHS, RHS };
Chandler Carruth82214a82011-02-18 23:54:50 +00002910 OverloadCandidateSet CandidateSet(QuestionLoc);
2911 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
2912 CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002913
2914 OverloadCandidateSet::iterator Best;
Chandler Carruth82214a82011-02-18 23:54:50 +00002915 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002916 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002917 // We found a match. Perform the conversions on the arguments and move on.
2918 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00002919 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002920 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00002921 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002922 break;
2923 return false;
2924
Douglas Gregor20093b42009-12-09 23:02:17 +00002925 case OR_No_Viable_Function:
Chandler Carruth82214a82011-02-18 23:54:50 +00002926
2927 // Emit a better diagnostic if one of the expressions is a null pointer
2928 // constant and the other is a pointer type. In this case, the user most
2929 // likely forgot to take the address of the other expression.
2930 if (Self.DiagnoseConditionalForNull(LHS, RHS, QuestionLoc))
2931 return true;
2932
2933 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002934 << LHS->getType() << RHS->getType()
2935 << LHS->getSourceRange() << RHS->getSourceRange();
2936 return true;
2937
Douglas Gregor20093b42009-12-09 23:02:17 +00002938 case OR_Ambiguous:
Chandler Carruth82214a82011-02-18 23:54:50 +00002939 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002940 << LHS->getType() << RHS->getType()
2941 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00002942 // FIXME: Print the possible common types by printing the return types of
2943 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002944 break;
2945
Douglas Gregor20093b42009-12-09 23:02:17 +00002946 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002947 assert(false && "Conditional operator has only built-in overloads");
2948 break;
2949 }
2950 return true;
2951}
2952
Sebastian Redl76458502009-04-17 16:30:52 +00002953/// \brief Perform an "extended" implicit conversion as returned by
2954/// TryClassUnification.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002955static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2956 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2957 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2958 SourceLocation());
2959 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
John McCallf312b1e2010-08-26 23:41:50 +00002960 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&E, 1));
Douglas Gregorb70cf442010-03-26 20:14:36 +00002961 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00002962 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002963
Douglas Gregorb70cf442010-03-26 20:14:36 +00002964 E = Result.takeAs<Expr>();
Sebastian Redl76458502009-04-17 16:30:52 +00002965 return false;
2966}
2967
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002968/// \brief Check the operands of ?: under C++ semantics.
2969///
2970/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2971/// extension. In this case, LHS == Cond. (But they're not aliases.)
2972QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
John McCall56ca35d2011-02-17 10:25:35 +00002973 ExprValueKind &VK, ExprObjectKind &OK,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002974 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002975 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2976 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002977
2978 // C++0x 5.16p1
2979 // The first expression is contextually converted to bool.
2980 if (!Cond->isTypeDependent()) {
2981 if (CheckCXXBooleanCondition(Cond))
2982 return QualType();
2983 }
2984
John McCallf89e55a2010-11-18 06:31:45 +00002985 // Assume r-value.
2986 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00002987 OK = OK_Ordinary;
John McCallf89e55a2010-11-18 06:31:45 +00002988
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002989 // Either of the arguments dependent?
2990 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2991 return Context.DependentTy;
2992
2993 // C++0x 5.16p2
2994 // If either the second or the third operand has type (cv) void, ...
2995 QualType LTy = LHS->getType();
2996 QualType RTy = RHS->getType();
2997 bool LVoid = LTy->isVoidType();
2998 bool RVoid = RTy->isVoidType();
2999 if (LVoid || RVoid) {
3000 // ... then the [l2r] conversions are performed on the second and third
3001 // operands ...
Douglas Gregora873dfc2010-02-03 00:27:59 +00003002 DefaultFunctionArrayLvalueConversion(LHS);
3003 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003004 LTy = LHS->getType();
3005 RTy = RHS->getType();
3006
3007 // ... and one of the following shall hold:
3008 // -- The second or the third operand (but not both) is a throw-
3009 // expression; the result is of the type of the other and is an rvalue.
3010 bool LThrow = isa<CXXThrowExpr>(LHS);
3011 bool RThrow = isa<CXXThrowExpr>(RHS);
3012 if (LThrow && !RThrow)
3013 return RTy;
3014 if (RThrow && !LThrow)
3015 return LTy;
3016
3017 // -- Both the second and third operands have type void; the result is of
3018 // type void and is an rvalue.
3019 if (LVoid && RVoid)
3020 return Context.VoidTy;
3021
3022 // Neither holds, error.
3023 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
3024 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
3025 << LHS->getSourceRange() << RHS->getSourceRange();
3026 return QualType();
3027 }
3028
3029 // Neither is void.
3030
3031 // C++0x 5.16p3
3032 // Otherwise, if the second and third operand have different types, and
3033 // either has (cv) class type, and attempt is made to convert each of those
3034 // operands to the other.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003035 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003036 (LTy->isRecordType() || RTy->isRecordType())) {
3037 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
3038 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003039 QualType L2RType, R2LType;
3040 bool HaveL2R, HaveR2L;
3041 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003042 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00003043 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003044 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003045
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003046 // If both can be converted, [...] the program is ill-formed.
3047 if (HaveL2R && HaveR2L) {
3048 Diag(QuestionLoc, diag::err_conditional_ambiguous)
3049 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
3050 return QualType();
3051 }
3052
3053 // If exactly one conversion is possible, that conversion is applied to
3054 // the chosen operand and the converted operands are used in place of the
3055 // original operands for the remainder of this section.
3056 if (HaveL2R) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003057 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003058 return QualType();
3059 LTy = LHS->getType();
3060 } else if (HaveR2L) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003061 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003062 return QualType();
3063 RTy = RHS->getType();
3064 }
3065 }
3066
3067 // C++0x 5.16p4
John McCallf89e55a2010-11-18 06:31:45 +00003068 // If the second and third operands are glvalues of the same value
3069 // category and have the same type, the result is of that type and
3070 // value category and it is a bit-field if the second or the third
3071 // operand is a bit-field, or if both are bit-fields.
John McCall09431682010-11-18 19:01:18 +00003072 // We only extend this to bitfields, not to the crazy other kinds of
3073 // l-values.
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003074 bool Same = Context.hasSameType(LTy, RTy);
John McCallf89e55a2010-11-18 06:31:45 +00003075 if (Same &&
John McCall56ca35d2011-02-17 10:25:35 +00003076 LHS->isGLValue() &&
John McCallf89e55a2010-11-18 06:31:45 +00003077 LHS->getValueKind() == RHS->getValueKind() &&
John McCall56ca35d2011-02-17 10:25:35 +00003078 LHS->isOrdinaryOrBitFieldObject() &&
3079 RHS->isOrdinaryOrBitFieldObject()) {
John McCallf89e55a2010-11-18 06:31:45 +00003080 VK = LHS->getValueKind();
John McCall09431682010-11-18 19:01:18 +00003081 if (LHS->getObjectKind() == OK_BitField ||
3082 RHS->getObjectKind() == OK_BitField)
3083 OK = OK_BitField;
John McCallf89e55a2010-11-18 06:31:45 +00003084 return LTy;
Fariborz Jahanian3911a1a2010-09-25 01:08:05 +00003085 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003086
3087 // C++0x 5.16p5
3088 // Otherwise, the result is an rvalue. If the second and third operands
3089 // do not have the same type, and either has (cv) class type, ...
3090 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
3091 // ... overload resolution is used to determine the conversions (if any)
3092 // to be applied to the operands. If the overload resolution fails, the
3093 // program is ill-formed.
3094 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
3095 return QualType();
3096 }
3097
3098 // C++0x 5.16p6
3099 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
3100 // conversions are performed on the second and third operands.
Douglas Gregora873dfc2010-02-03 00:27:59 +00003101 DefaultFunctionArrayLvalueConversion(LHS);
3102 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003103 LTy = LHS->getType();
3104 RTy = RHS->getType();
3105
3106 // After those conversions, one of the following shall hold:
3107 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00003108 // is of that type. If the operands have class type, the result
3109 // is a prvalue temporary of the result type, which is
3110 // copy-initialized from either the second operand or the third
3111 // operand depending on the value of the first operand.
3112 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
3113 if (LTy->isRecordType()) {
3114 // The operands have class type. Make a temporary copy.
3115 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003116 ExprResult LHSCopy = PerformCopyInitialization(Entity,
3117 SourceLocation(),
John McCallf6a16482010-12-04 03:47:34 +00003118 Owned(LHS));
Douglas Gregorb65a4582010-05-19 23:40:50 +00003119 if (LHSCopy.isInvalid())
3120 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003121
3122 ExprResult RHSCopy = PerformCopyInitialization(Entity,
3123 SourceLocation(),
John McCallf6a16482010-12-04 03:47:34 +00003124 Owned(RHS));
Douglas Gregorb65a4582010-05-19 23:40:50 +00003125 if (RHSCopy.isInvalid())
3126 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003127
Douglas Gregorb65a4582010-05-19 23:40:50 +00003128 LHS = LHSCopy.takeAs<Expr>();
3129 RHS = RHSCopy.takeAs<Expr>();
3130 }
3131
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003132 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00003133 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003134
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003135 // Extension: conditional operator involving vector types.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003136 if (LTy->isVectorType() || RTy->isVectorType())
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003137 return CheckVectorOperands(QuestionLoc, LHS, RHS);
3138
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003139 // -- The second and third operands have arithmetic or enumeration type;
3140 // the usual arithmetic conversions are performed to bring them to a
3141 // common type, and the result is of that type.
3142 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
3143 UsualArithmeticConversions(LHS, RHS);
3144 return LHS->getType();
3145 }
3146
3147 // -- The second and third operands have pointer type, or one has pointer
3148 // type and the other is a null pointer constant; pointer conversions
3149 // and qualification conversions are performed to bring them to their
3150 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00003151 // -- The second and third operands have pointer to member type, or one has
3152 // pointer to member type and the other is a null pointer constant;
3153 // pointer to member conversions and qualification conversions are
3154 // performed to bring them to a common type, whose cv-qualification
3155 // shall match the cv-qualification of either the second or the third
3156 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003157 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003158 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003159 isSFINAEContext()? 0 : &NonStandardCompositeType);
3160 if (!Composite.isNull()) {
3161 if (NonStandardCompositeType)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003162 Diag(QuestionLoc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003163 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
3164 << LTy << RTy << Composite
3165 << LHS->getSourceRange() << RHS->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003166
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003167 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003168 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003169
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003170 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00003171 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
3172 if (!Composite.isNull())
3173 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003174
Chandler Carruth7ef93242011-02-19 00:13:59 +00003175 // Check if we are using a null with a non-pointer type.
3176 if (DiagnoseConditionalForNull(LHS, RHS, QuestionLoc))
3177 return QualType();
3178
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003179 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3180 << LHS->getType() << RHS->getType()
3181 << LHS->getSourceRange() << RHS->getSourceRange();
3182 return QualType();
3183}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003184
3185/// \brief Find a merged pointer type and convert the two expressions to it.
3186///
Douglas Gregor20b3e992009-08-24 17:42:35 +00003187/// This finds the composite pointer type (or member pointer type) for @p E1
3188/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
3189/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003190/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003191///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003192/// \param Loc The location of the operator requiring these two expressions to
3193/// be converted to the composite pointer type.
3194///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003195/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
3196/// a non-standard (but still sane) composite type to which both expressions
3197/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
3198/// will be set true.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003199QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003200 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003201 bool *NonStandardCompositeType) {
3202 if (NonStandardCompositeType)
3203 *NonStandardCompositeType = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003204
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003205 assert(getLangOptions().CPlusPlus && "This function assumes C++");
3206 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003207
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00003208 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
3209 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00003210 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003211
3212 // C++0x 5.9p2
3213 // Pointer conversions and qualification conversions are performed on
3214 // pointer operands to bring them to their composite pointer type. If
3215 // one operand is a null pointer constant, the composite pointer type is
3216 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00003217 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003218 if (T2->isMemberPointerType())
John McCall2de56d12010-08-25 11:45:40 +00003219 ImpCastExprToType(E1, T2, CK_NullToMemberPointer);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003220 else
John McCall404cd162010-11-13 01:35:44 +00003221 ImpCastExprToType(E1, T2, CK_NullToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003222 return T2;
3223 }
Douglas Gregorce940492009-09-25 04:25:58 +00003224 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003225 if (T1->isMemberPointerType())
John McCall2de56d12010-08-25 11:45:40 +00003226 ImpCastExprToType(E2, T1, CK_NullToMemberPointer);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003227 else
John McCall404cd162010-11-13 01:35:44 +00003228 ImpCastExprToType(E2, T1, CK_NullToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003229 return T1;
3230 }
Mike Stump1eb44332009-09-09 15:08:12 +00003231
Douglas Gregor20b3e992009-08-24 17:42:35 +00003232 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003233 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
3234 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003235 return QualType();
3236
3237 // Otherwise, of one of the operands has type "pointer to cv1 void," then
3238 // the other has type "pointer to cv2 T" and the composite pointer type is
3239 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
3240 // Otherwise, the composite pointer type is a pointer type similar to the
3241 // type of one of the operands, with a cv-qualification signature that is
3242 // the union of the cv-qualification signatures of the operand types.
3243 // In practice, the first part here is redundant; it's subsumed by the second.
3244 // What we do here is, we build the two possible composite types, and try the
3245 // conversions in both directions. If only one works, or if the two composite
3246 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00003247 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00003248 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
3249 QualifierVector QualifierUnion;
3250 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
3251 ContainingClassVector;
3252 ContainingClassVector MemberOfClass;
3253 QualType Composite1 = Context.getCanonicalType(T1),
3254 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003255 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00003256 do {
3257 const PointerType *Ptr1, *Ptr2;
3258 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3259 (Ptr2 = Composite2->getAs<PointerType>())) {
3260 Composite1 = Ptr1->getPointeeType();
3261 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003262
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003263 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003264 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003265 if (NonStandardCompositeType &&
3266 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3267 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003268
Douglas Gregor20b3e992009-08-24 17:42:35 +00003269 QualifierUnion.push_back(
3270 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3271 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3272 continue;
3273 }
Mike Stump1eb44332009-09-09 15:08:12 +00003274
Douglas Gregor20b3e992009-08-24 17:42:35 +00003275 const MemberPointerType *MemPtr1, *MemPtr2;
3276 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3277 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3278 Composite1 = MemPtr1->getPointeeType();
3279 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003280
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003281 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003282 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003283 if (NonStandardCompositeType &&
3284 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3285 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003286
Douglas Gregor20b3e992009-08-24 17:42:35 +00003287 QualifierUnion.push_back(
3288 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3289 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
3290 MemPtr2->getClass()));
3291 continue;
3292 }
Mike Stump1eb44332009-09-09 15:08:12 +00003293
Douglas Gregor20b3e992009-08-24 17:42:35 +00003294 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00003295
Douglas Gregor20b3e992009-08-24 17:42:35 +00003296 // Cannot unwrap any more types.
3297 break;
3298 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00003299
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003300 if (NeedConstBefore && NonStandardCompositeType) {
3301 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003302 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003303 // requirements of C++ [conv.qual]p4 bullet 3.
3304 for (unsigned I = 0; I != NeedConstBefore; ++I) {
3305 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
3306 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
3307 *NonStandardCompositeType = true;
3308 }
3309 }
3310 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003311
Douglas Gregor20b3e992009-08-24 17:42:35 +00003312 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003313 ContainingClassVector::reverse_iterator MOC
3314 = MemberOfClass.rbegin();
3315 for (QualifierVector::reverse_iterator
3316 I = QualifierUnion.rbegin(),
3317 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00003318 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00003319 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00003320 if (MOC->first && MOC->second) {
3321 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00003322 Composite1 = Context.getMemberPointerType(
3323 Context.getQualifiedType(Composite1, Quals),
3324 MOC->first);
3325 Composite2 = Context.getMemberPointerType(
3326 Context.getQualifiedType(Composite2, Quals),
3327 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00003328 } else {
3329 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00003330 Composite1
3331 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
3332 Composite2
3333 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00003334 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003335 }
3336
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003337 // Try to convert to the first composite pointer type.
3338 InitializedEntity Entity1
3339 = InitializedEntity::InitializeTemporary(Composite1);
3340 InitializationKind Kind
3341 = InitializationKind::CreateCopy(Loc, SourceLocation());
3342 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
3343 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00003344
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003345 if (E1ToC1 && E2ToC1) {
3346 // Conversion to Composite1 is viable.
3347 if (!Context.hasSameType(Composite1, Composite2)) {
3348 // Composite2 is a different type from Composite1. Check whether
3349 // Composite2 is also viable.
3350 InitializedEntity Entity2
3351 = InitializedEntity::InitializeTemporary(Composite2);
3352 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3353 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3354 if (E1ToC2 && E2ToC2) {
3355 // Both Composite1 and Composite2 are viable and are different;
3356 // this is an ambiguity.
3357 return QualType();
3358 }
3359 }
3360
3361 // Convert E1 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00003362 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00003363 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003364 if (E1Result.isInvalid())
3365 return QualType();
3366 E1 = E1Result.takeAs<Expr>();
3367
3368 // Convert E2 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00003369 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00003370 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003371 if (E2Result.isInvalid())
3372 return QualType();
3373 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003374
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003375 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003376 }
3377
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003378 // Check whether Composite2 is viable.
3379 InitializedEntity Entity2
3380 = InitializedEntity::InitializeTemporary(Composite2);
3381 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3382 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3383 if (!E1ToC2 || !E2ToC2)
3384 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003385
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003386 // Convert E1 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00003387 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00003388 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003389 if (E1Result.isInvalid())
3390 return QualType();
3391 E1 = E1Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003392
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003393 // Convert E2 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00003394 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00003395 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003396 if (E2Result.isInvalid())
3397 return QualType();
3398 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003399
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003400 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003401}
Anders Carlsson165a0a02009-05-17 18:41:29 +00003402
John McCall60d7b3a2010-08-24 06:29:42 +00003403ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor19cc1c72010-11-01 21:10:29 +00003404 if (!E)
3405 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003406
Anders Carlsson089c2602009-08-15 23:41:35 +00003407 if (!Context.getLangOptions().CPlusPlus)
3408 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003409
Douglas Gregor51326552009-12-24 18:51:59 +00003410 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
3411
Ted Kremenek6217b802009-07-29 21:53:49 +00003412 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00003413 if (!RT)
3414 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003415
Douglas Gregor5e6fcd42011-02-08 02:14:35 +00003416 // If the result is a glvalue, we shouldn't bind it.
3417 if (E->Classify(Context).isGLValue())
3418 return Owned(E);
John McCall86ff3082010-02-04 22:26:26 +00003419
3420 // That should be enough to guarantee that this type is complete.
3421 // If it has a trivial destructor, we can avoid the extra copy.
Jeffrey Yasskinb7ee2e52011-01-27 19:17:54 +00003422 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall507384f2010-08-12 02:40:37 +00003423 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall86ff3082010-02-04 22:26:26 +00003424 return Owned(E);
3425
Douglas Gregordb89f282010-07-01 22:47:18 +00003426 CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD));
Anders Carlsson860306e2009-05-30 21:21:49 +00003427 ExprTemporaries.push_back(Temp);
Douglas Gregordb89f282010-07-01 22:47:18 +00003428 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003429 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00003430 CheckDestructorAccess(E->getExprLoc(), Destructor,
3431 PDiag(diag::err_access_dtor_temp)
3432 << E->getType());
3433 }
Anders Carlssondef11992009-05-30 20:36:53 +00003434 // FIXME: Add the temporary to the temporaries vector.
3435 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
3436}
3437
John McCall4765fa02010-12-06 08:20:24 +00003438Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003439 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00003440
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00003441 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3442 assert(ExprTemporaries.size() >= FirstTemporary);
3443 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003444 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003445
John McCall4765fa02010-12-06 08:20:24 +00003446 Expr *E = ExprWithCleanups::Create(Context, SubExpr,
3447 &ExprTemporaries[FirstTemporary],
3448 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00003449 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
3450 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00003451
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003452 return E;
3453}
3454
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003455ExprResult
John McCall4765fa02010-12-06 08:20:24 +00003456Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregor90f93822009-12-22 22:17:25 +00003457 if (SubExpr.isInvalid())
3458 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003459
John McCall4765fa02010-12-06 08:20:24 +00003460 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregor90f93822009-12-22 22:17:25 +00003461}
3462
John McCall4765fa02010-12-06 08:20:24 +00003463Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003464 assert(SubStmt && "sub statement can't be null!");
3465
3466 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3467 assert(ExprTemporaries.size() >= FirstTemporary);
3468 if (ExprTemporaries.size() == FirstTemporary)
3469 return SubStmt;
3470
3471 // FIXME: In order to attach the temporaries, wrap the statement into
3472 // a StmtExpr; currently this is only used for asm statements.
3473 // This is hacky, either create a new CXXStmtWithTemporaries statement or
3474 // a new AsmStmtWithTemporaries.
3475 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
3476 SourceLocation(),
3477 SourceLocation());
3478 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
3479 SourceLocation());
John McCall4765fa02010-12-06 08:20:24 +00003480 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003481}
3482
John McCall60d7b3a2010-08-24 06:29:42 +00003483ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003484Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallb3d87482010-08-24 05:47:05 +00003485 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00003486 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003487 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003488 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003489 if (Result.isInvalid()) return ExprError();
3490 Base = Result.get();
Mike Stump1eb44332009-09-09 15:08:12 +00003491
John McCall9ae2f072010-08-23 23:25:46 +00003492 QualType BaseType = Base->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00003493 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003494 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00003495 // If we have a pointer to a dependent type and are using the -> operator,
3496 // the object type is the type that the pointer points to. We might still
3497 // have enough information about that type to do something useful.
3498 if (OpKind == tok::arrow)
3499 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3500 BaseType = Ptr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003501
John McCallb3d87482010-08-24 05:47:05 +00003502 ObjectType = ParsedType::make(BaseType);
Douglas Gregord4dca082010-02-24 18:44:31 +00003503 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00003504 return Owned(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003505 }
Mike Stump1eb44332009-09-09 15:08:12 +00003506
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003507 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00003508 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003509 // returned, with the original second operand.
3510 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00003511 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00003512 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00003513 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00003514 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003515
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003516 while (BaseType->isRecordType()) {
John McCall9ae2f072010-08-23 23:25:46 +00003517 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
3518 if (Result.isInvalid())
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003519 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00003520 Base = Result.get();
3521 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonde699e52009-10-13 22:55:59 +00003522 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCall9ae2f072010-08-23 23:25:46 +00003523 BaseType = Base->getType();
John McCallc4e83212009-09-30 01:01:30 +00003524 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00003525 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00003526 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00003527 for (unsigned i = 0; i < Locations.size(); i++)
3528 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00003529 return ExprError();
3530 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003531 }
Mike Stump1eb44332009-09-09 15:08:12 +00003532
Douglas Gregor31658df2009-11-20 19:58:21 +00003533 if (BaseType->isPointerType())
3534 BaseType = BaseType->getPointeeType();
3535 }
Mike Stump1eb44332009-09-09 15:08:12 +00003536
3537 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003538 // vector types or Objective-C interfaces. Just return early and let
3539 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00003540 if (!BaseType->isRecordType()) {
3541 // C++ [basic.lookup.classref]p2:
3542 // [...] If the type of the object expression is of pointer to scalar
3543 // type, the unqualified-id is looked up in the context of the complete
3544 // postfix-expression.
Douglas Gregord4dca082010-02-24 18:44:31 +00003545 //
3546 // This also indicates that we should be parsing a
3547 // pseudo-destructor-name.
John McCallb3d87482010-08-24 05:47:05 +00003548 ObjectType = ParsedType();
Douglas Gregord4dca082010-02-24 18:44:31 +00003549 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00003550 return Owned(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00003551 }
Mike Stump1eb44332009-09-09 15:08:12 +00003552
Douglas Gregor03c57052009-11-17 05:17:33 +00003553 // The object type must be complete (or dependent).
3554 if (!BaseType->isDependentType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003555 RequireCompleteType(OpLoc, BaseType,
Douglas Gregor03c57052009-11-17 05:17:33 +00003556 PDiag(diag::err_incomplete_member_access)))
3557 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003558
Douglas Gregorc68afe22009-09-03 21:38:09 +00003559 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00003560 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00003561 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00003562 // type C (or of pointer to a class type C), the unqualified-id is looked
3563 // up in the scope of class C. [...]
John McCallb3d87482010-08-24 05:47:05 +00003564 ObjectType = ParsedType::make(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00003565 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003566}
3567
John McCall60d7b3a2010-08-24 06:29:42 +00003568ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003569 Expr *MemExpr) {
Douglas Gregor77549082010-02-24 21:29:12 +00003570 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCall9ae2f072010-08-23 23:25:46 +00003571 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
3572 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregor849b2432010-03-31 17:46:05 +00003573 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003574
Douglas Gregor77549082010-02-24 21:29:12 +00003575 return ActOnCallExpr(/*Scope*/ 0,
John McCall9ae2f072010-08-23 23:25:46 +00003576 MemExpr,
Douglas Gregor77549082010-02-24 21:29:12 +00003577 /*LPLoc*/ ExpectedLParenLoc,
John McCallf312b1e2010-08-26 23:41:50 +00003578 MultiExprArg(),
Douglas Gregor77549082010-02-24 21:29:12 +00003579 /*RPLoc*/ ExpectedLParenLoc);
3580}
Douglas Gregord4dca082010-02-24 18:44:31 +00003581
John McCall60d7b3a2010-08-24 06:29:42 +00003582ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003583 SourceLocation OpLoc,
3584 tok::TokenKind OpKind,
3585 const CXXScopeSpec &SS,
Douglas Gregor26d4ac92010-02-24 23:40:28 +00003586 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003587 SourceLocation CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00003588 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003589 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003590 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003591 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003592
Douglas Gregorb57fb492010-02-24 22:38:50 +00003593 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003594 // The left-hand side of the dot operator shall be of scalar type. The
Douglas Gregorb57fb492010-02-24 22:38:50 +00003595 // left-hand side of the arrow operator shall be of pointer to scalar type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003596 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00003597 QualType ObjectType = Base->getType();
Douglas Gregorb57fb492010-02-24 22:38:50 +00003598 if (OpKind == tok::arrow) {
3599 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3600 ObjectType = Ptr->getPointeeType();
John McCall9ae2f072010-08-23 23:25:46 +00003601 } else if (!Base->isTypeDependent()) {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003602 // The user wrote "p->" when she probably meant "p."; fix it.
3603 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3604 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00003605 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb57fb492010-02-24 22:38:50 +00003606 if (isSFINAEContext())
3607 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003608
Douglas Gregorb57fb492010-02-24 22:38:50 +00003609 OpKind = tok::period;
3610 }
3611 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003612
Douglas Gregorb57fb492010-02-24 22:38:50 +00003613 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
3614 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
John McCall9ae2f072010-08-23 23:25:46 +00003615 << ObjectType << Base->getSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00003616 return ExprError();
3617 }
3618
3619 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003620 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb57fb492010-02-24 22:38:50 +00003621 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003622 if (DestructedTypeInfo) {
3623 QualType DestructedType = DestructedTypeInfo->getType();
3624 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003625 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003626 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
3627 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
3628 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00003629 << ObjectType << DestructedType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003630 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003631
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003632 // Recover by setting the destructed type to the object type.
3633 DestructedType = ObjectType;
3634 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
3635 DestructedTypeStart);
3636 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3637 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00003638 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003639
Douglas Gregorb57fb492010-02-24 22:38:50 +00003640 // C++ [expr.pseudo]p2:
3641 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
3642 // form
3643 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003644 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb57fb492010-02-24 22:38:50 +00003645 //
3646 // shall designate the same scalar type.
3647 if (ScopeTypeInfo) {
3648 QualType ScopeType = ScopeTypeInfo->getType();
3649 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00003650 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003651
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003652 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00003653 diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00003654 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003655 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003656
Douglas Gregorb57fb492010-02-24 22:38:50 +00003657 ScopeType = QualType();
3658 ScopeTypeInfo = 0;
3659 }
3660 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003661
John McCall9ae2f072010-08-23 23:25:46 +00003662 Expr *Result
3663 = new (Context) CXXPseudoDestructorExpr(Context, Base,
3664 OpKind == tok::arrow, OpLoc,
3665 SS.getScopeRep(), SS.getRange(),
3666 ScopeTypeInfo,
3667 CCLoc,
3668 TildeLoc,
3669 Destructed);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003670
Douglas Gregorb57fb492010-02-24 22:38:50 +00003671 if (HasTrailingLParen)
John McCall9ae2f072010-08-23 23:25:46 +00003672 return Owned(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003673
John McCall9ae2f072010-08-23 23:25:46 +00003674 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor77549082010-02-24 21:29:12 +00003675}
3676
John McCall60d7b3a2010-08-24 06:29:42 +00003677ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
Douglas Gregor77549082010-02-24 21:29:12 +00003678 SourceLocation OpLoc,
3679 tok::TokenKind OpKind,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003680 CXXScopeSpec &SS,
Douglas Gregor77549082010-02-24 21:29:12 +00003681 UnqualifiedId &FirstTypeName,
3682 SourceLocation CCLoc,
3683 SourceLocation TildeLoc,
3684 UnqualifiedId &SecondTypeName,
3685 bool HasTrailingLParen) {
3686 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3687 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3688 "Invalid first type name in pseudo-destructor");
3689 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3690 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3691 "Invalid second type name in pseudo-destructor");
3692
Douglas Gregor77549082010-02-24 21:29:12 +00003693 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003694 // The left-hand side of the dot operator shall be of scalar type. The
Douglas Gregor77549082010-02-24 21:29:12 +00003695 // left-hand side of the arrow operator shall be of pointer to scalar type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003696 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00003697 QualType ObjectType = Base->getType();
Douglas Gregor77549082010-02-24 21:29:12 +00003698 if (OpKind == tok::arrow) {
3699 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3700 ObjectType = Ptr->getPointeeType();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003701 } else if (!ObjectType->isDependentType()) {
Douglas Gregor77549082010-02-24 21:29:12 +00003702 // The user wrote "p->" when she probably meant "p."; fix it.
3703 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003704 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00003705 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor77549082010-02-24 21:29:12 +00003706 if (isSFINAEContext())
3707 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003708
Douglas Gregor77549082010-02-24 21:29:12 +00003709 OpKind = tok::period;
3710 }
3711 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003712
3713 // Compute the object type that we should use for name lookup purposes. Only
3714 // record types and dependent types matter.
John McCallb3d87482010-08-24 05:47:05 +00003715 ParsedType ObjectTypePtrForLookup;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003716 if (!SS.isSet()) {
John McCallb3d87482010-08-24 05:47:05 +00003717 if (const Type *T = ObjectType->getAs<RecordType>())
3718 ObjectTypePtrForLookup = ParsedType::make(QualType(T, 0));
3719 else if (ObjectType->isDependentType())
3720 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003721 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003722
3723 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb57fb492010-02-24 22:38:50 +00003724 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00003725 QualType DestructedType;
3726 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003727 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00003728 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003729 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00003730 SecondTypeName.StartLocation,
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +00003731 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003732 if (!T &&
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003733 ((SS.isSet() && !computeDeclContext(SS, false)) ||
3734 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003735 // The name of the type being destroyed is a dependent name, and we
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003736 // couldn't find anything useful in scope. Just store the identifier and
3737 // it's location, and we'll perform (qualified) name lookup again at
3738 // template instantiation time.
3739 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
3740 SecondTypeName.StartLocation);
3741 } else if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003742 Diag(SecondTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00003743 diag::err_pseudo_dtor_destructor_non_type)
3744 << SecondTypeName.Identifier << ObjectType;
3745 if (isSFINAEContext())
3746 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003747
Douglas Gregor77549082010-02-24 21:29:12 +00003748 // Recover by assuming we had the right type all along.
3749 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003750 } else
Douglas Gregor77549082010-02-24 21:29:12 +00003751 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003752 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003753 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00003754 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003755 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3756 TemplateId->getTemplateArgs(),
3757 TemplateId->NumArgs);
John McCall2b5289b2010-08-23 07:28:44 +00003758 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003759 TemplateId->TemplateNameLoc,
3760 TemplateId->LAngleLoc,
3761 TemplateArgsPtr,
3762 TemplateId->RAngleLoc);
3763 if (T.isInvalid() || !T.get()) {
3764 // Recover by assuming we had the right type all along.
3765 DestructedType = ObjectType;
3766 } else
3767 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003768 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003769
3770 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb57fb492010-02-24 22:38:50 +00003771 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003772 if (!DestructedType.isNull()) {
3773 if (!DestructedTypeInfo)
3774 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003775 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003776 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3777 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003778
Douglas Gregorb57fb492010-02-24 22:38:50 +00003779 // Convert the name of the scope type (the type prior to '::') into a type.
3780 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00003781 QualType ScopeType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003782 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor77549082010-02-24 21:29:12 +00003783 FirstTypeName.Identifier) {
3784 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003785 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00003786 FirstTypeName.StartLocation,
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +00003787 S, &SS, false, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00003788 if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003789 Diag(FirstTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00003790 diag::err_pseudo_dtor_destructor_non_type)
3791 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003792
Douglas Gregorb57fb492010-02-24 22:38:50 +00003793 if (isSFINAEContext())
3794 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003795
Douglas Gregorb57fb492010-02-24 22:38:50 +00003796 // Just drop this type. It's unnecessary anyway.
3797 ScopeType = QualType();
3798 } else
3799 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003800 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003801 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00003802 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003803 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3804 TemplateId->getTemplateArgs(),
3805 TemplateId->NumArgs);
John McCall2b5289b2010-08-23 07:28:44 +00003806 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003807 TemplateId->TemplateNameLoc,
3808 TemplateId->LAngleLoc,
3809 TemplateArgsPtr,
3810 TemplateId->RAngleLoc);
3811 if (T.isInvalid() || !T.get()) {
3812 // Recover by dropping this type.
3813 ScopeType = QualType();
3814 } else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003815 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003816 }
3817 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003818
Douglas Gregorb4a418f2010-02-24 23:02:30 +00003819 if (!ScopeType.isNull() && !ScopeTypeInfo)
3820 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
3821 FirstTypeName.StartLocation);
3822
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003823
John McCall9ae2f072010-08-23 23:25:46 +00003824 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00003825 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003826 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00003827}
3828
Douglas Gregorf2ae5262011-01-20 00:18:04 +00003829ExprResult Sema::BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
3830 CXXMethodDecl *Method) {
John McCall6bb80172010-03-30 21:47:33 +00003831 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
3832 FoundDecl, Method))
Douglas Gregorf2ae5262011-01-20 00:18:04 +00003833 return true;
Eli Friedman772fffa2009-12-09 04:53:56 +00003834
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003835 MemberExpr *ME =
Abramo Bagnara25777432010-08-11 22:01:17 +00003836 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
John McCallf89e55a2010-11-18 06:31:45 +00003837 SourceLocation(), Method->getType(),
3838 VK_RValue, OK_Ordinary);
3839 QualType ResultType = Method->getResultType();
3840 ExprValueKind VK = Expr::getValueKindForType(ResultType);
3841 ResultType = ResultType.getNonLValueExprType(Context);
3842
Douglas Gregor7edfb692009-11-23 12:27:39 +00003843 MarkDeclarationReferenced(Exp->getLocStart(), Method);
3844 CXXMemberCallExpr *CE =
John McCallf89e55a2010-11-18 06:31:45 +00003845 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
Douglas Gregor7edfb692009-11-23 12:27:39 +00003846 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003847 return CE;
3848}
3849
Sebastian Redl2e156222010-09-10 20:55:43 +00003850ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
3851 SourceLocation RParen) {
Sebastian Redl2e156222010-09-10 20:55:43 +00003852 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
3853 Operand->CanThrow(Context),
3854 KeyLoc, RParen));
3855}
3856
3857ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
3858 Expr *Operand, SourceLocation RParen) {
3859 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl02bc21a2010-09-10 20:55:37 +00003860}
3861
John McCallf6a16482010-12-04 03:47:34 +00003862/// Perform the conversions required for an expression used in a
3863/// context that ignores the result.
3864void Sema::IgnoredValueConversions(Expr *&E) {
John McCalla878cda2010-12-02 02:07:15 +00003865 // C99 6.3.2.1:
3866 // [Except in specific positions,] an lvalue that does not have
3867 // array type is converted to the value stored in the
3868 // designated object (and is no longer an lvalue).
John McCallf6a16482010-12-04 03:47:34 +00003869 if (E->isRValue()) return;
John McCalla878cda2010-12-02 02:07:15 +00003870
John McCallf6a16482010-12-04 03:47:34 +00003871 // We always want to do this on ObjC property references.
3872 if (E->getObjectKind() == OK_ObjCProperty) {
3873 ConvertPropertyForRValue(E);
3874 if (E->isRValue()) return;
3875 }
3876
3877 // Otherwise, this rule does not apply in C++, at least not for the moment.
3878 if (getLangOptions().CPlusPlus) return;
3879
3880 // GCC seems to also exclude expressions of incomplete enum type.
3881 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
3882 if (!T->getDecl()->isComplete()) {
3883 // FIXME: stupid workaround for a codegen bug!
3884 ImpCastExprToType(E, Context.VoidTy, CK_ToVoid);
3885 return;
3886 }
3887 }
3888
3889 DefaultFunctionArrayLvalueConversion(E);
John McCall85515d62010-12-04 12:29:11 +00003890 if (!E->getType()->isVoidType())
3891 RequireCompleteType(E->getExprLoc(), E->getType(),
3892 diag::err_incomplete_type);
John McCallf6a16482010-12-04 03:47:34 +00003893}
3894
3895ExprResult Sema::ActOnFinishFullExpr(Expr *FullExpr) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003896 if (!FullExpr)
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003897 return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00003898
Douglas Gregord0937222010-12-13 22:49:22 +00003899 if (DiagnoseUnexpandedParameterPack(FullExpr))
3900 return ExprError();
3901
John McCallf6a16482010-12-04 03:47:34 +00003902 IgnoredValueConversions(FullExpr);
John McCallb4eb64d2010-10-08 02:01:28 +00003903 CheckImplicitConversions(FullExpr);
John McCall4765fa02010-12-06 08:20:24 +00003904 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson165a0a02009-05-17 18:41:29 +00003905}
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003906
3907StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
3908 if (!FullStmt) return StmtError();
3909
John McCall4765fa02010-12-06 08:20:24 +00003910 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003911}