blob: 5e46090c0588f7274d1b6113ed325c808078378f [file] [log] [blame]
Chris Lattner29375652006-12-04 18:06:35 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner29375652006-12-04 18:06:35 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000014#include "clang/Sema/Sema.h"
15#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
Steve Naroffaac94152007-08-25 14:02:58 +000017#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000019#include "clang/AST/ExprCXX.h"
Fariborz Jahanian1d446082010-06-16 18:56:04 +000020#include "clang/AST/ExprObjC.h"
Douglas Gregorb1dd23f2010-02-24 22:38:50 +000021#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000022#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlfaf68082008-12-03 20:26:15 +000023#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000024#include "clang/Lex/Preprocessor.h"
25#include "clang/Parse/DeclSpec.h"
Douglas Gregore610ada2010-02-24 18:44:31 +000026#include "clang/Parse/Template.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000027#include "llvm/ADT/STLExtras.h"
Chris Lattner29375652006-12-04 18:06:35 +000028using namespace clang;
29
Douglas Gregorfe17d252010-02-16 19:09:40 +000030Action::TypeTy *Sema::getDestructorName(SourceLocation TildeLoc,
31 IdentifierInfo &II,
32 SourceLocation NameLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +000033 Scope *S, CXXScopeSpec &SS,
Douglas Gregorfe17d252010-02-16 19:09:40 +000034 TypeTy *ObjectTypePtr,
35 bool EnteringContext) {
36 // Determine where to perform name lookup.
37
38 // FIXME: This area of the standard is very messy, and the current
39 // wording is rather unclear about which scopes we search for the
40 // destructor name; see core issues 399 and 555. Issue 399 in
41 // particular shows where the current description of destructor name
42 // lookup is completely out of line with existing practice, e.g.,
43 // this appears to be ill-formed:
44 //
45 // namespace N {
46 // template <typename T> struct S {
47 // ~S();
48 // };
49 // }
50 //
51 // void f(N::S<int>* s) {
52 // s->N::S<int>::~S();
53 // }
54 //
Douglas Gregor46841e12010-02-23 00:15:22 +000055 // See also PR6358 and PR6359.
Sebastian Redla771d222010-07-07 23:17:38 +000056 // For this reason, we're currently only doing the C++03 version of this
57 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregorfe17d252010-02-16 19:09:40 +000058 QualType SearchType;
59 DeclContext *LookupCtx = 0;
60 bool isDependent = false;
61 bool LookInScope = false;
62
63 // If we have an object type, it's because we are in a
64 // pseudo-destructor-expression or a member access expression, and
65 // we know what type we're looking for.
66 if (ObjectTypePtr)
67 SearchType = GetTypeFromParser(ObjectTypePtr);
68
69 if (SS.isSet()) {
Douglas Gregor46841e12010-02-23 00:15:22 +000070 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
71
72 bool AlreadySearched = false;
73 bool LookAtPrefix = true;
Sebastian Redla771d222010-07-07 23:17:38 +000074 // C++ [basic.lookup.qual]p6:
75 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
76 // the type-names are looked up as types in the scope designated by the
77 // nested-name-specifier. In a qualified-id of the form:
78 //
79 // ::[opt] nested-name-specifier ̃ class-name
80 //
81 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth8f254812010-02-21 10:19:54 +000082 // a qualified-id of the form:
Douglas Gregorfe17d252010-02-16 19:09:40 +000083 //
Sebastian Redla771d222010-07-07 23:17:38 +000084 // ::opt nested-name-specifier class-name :: ̃ class-name
Douglas Gregorfe17d252010-02-16 19:09:40 +000085 //
Sebastian Redla771d222010-07-07 23:17:38 +000086 // the class-names are looked up as types in the scope designated by
87 // the nested-name-specifier.
Douglas Gregorfe17d252010-02-16 19:09:40 +000088 //
Sebastian Redla771d222010-07-07 23:17:38 +000089 // Here, we check the first case (completely) and determine whether the
90 // code below is permitted to look at the prefix of the
91 // nested-name-specifier.
92 DeclContext *DC = computeDeclContext(SS, EnteringContext);
93 if (DC && DC->isFileContext()) {
94 AlreadySearched = true;
95 LookupCtx = DC;
96 isDependent = false;
97 } else if (DC && isa<CXXRecordDecl>(DC))
98 LookAtPrefix = false;
99
100 // The second case from the C++03 rules quoted further above.
Douglas Gregor46841e12010-02-23 00:15:22 +0000101 NestedNameSpecifier *Prefix = 0;
102 if (AlreadySearched) {
103 // Nothing left to do.
104 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
105 CXXScopeSpec PrefixSS;
106 PrefixSS.setScopeRep(Prefix);
107 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
108 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor46841e12010-02-23 00:15:22 +0000109 } else if (ObjectTypePtr) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000110 LookupCtx = computeDeclContext(SearchType);
111 isDependent = SearchType->isDependentType();
112 } else {
113 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor46841e12010-02-23 00:15:22 +0000114 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000115 }
Douglas Gregor46841e12010-02-23 00:15:22 +0000116
Douglas Gregorcd3f49f2010-02-25 04:46:04 +0000117 LookInScope = false;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000118 } else if (ObjectTypePtr) {
119 // C++ [basic.lookup.classref]p3:
120 // If the unqualified-id is ~type-name, the type-name is looked up
121 // in the context of the entire postfix-expression. If the type T
122 // of the object expression is of a class type C, the type-name is
123 // also looked up in the scope of class C. At least one of the
124 // lookups shall find a name that refers to (possibly
125 // cv-qualified) T.
126 LookupCtx = computeDeclContext(SearchType);
127 isDependent = SearchType->isDependentType();
128 assert((isDependent || !SearchType->isIncompleteType()) &&
129 "Caller should have completed object type");
130
131 LookInScope = true;
132 } else {
133 // Perform lookup into the current scope (only).
134 LookInScope = true;
135 }
136
137 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
138 for (unsigned Step = 0; Step != 2; ++Step) {
139 // Look for the name first in the computed lookup context (if we
140 // have one) and, if that fails to find a match, in the sope (if
141 // we're allowed to look there).
142 Found.clear();
143 if (Step == 0 && LookupCtx)
144 LookupQualifiedName(Found, LookupCtx);
Douglas Gregor678f90d2010-02-25 01:56:36 +0000145 else if (Step == 1 && LookInScope && S)
Douglas Gregorfe17d252010-02-16 19:09:40 +0000146 LookupName(Found, S);
147 else
148 continue;
149
150 // FIXME: Should we be suppressing ambiguities here?
151 if (Found.isAmbiguous())
152 return 0;
153
154 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
155 QualType T = Context.getTypeDeclType(Type);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000156
157 if (SearchType.isNull() || SearchType->isDependentType() ||
158 Context.hasSameUnqualifiedType(T, SearchType)) {
159 // We found our type!
160
161 return T.getAsOpaquePtr();
162 }
163 }
164
165 // If the name that we found is a class template name, and it is
166 // the same name as the template name in the last part of the
167 // nested-name-specifier (if present) or the object type, then
168 // this is the destructor for that class.
169 // FIXME: This is a workaround until we get real drafting for core
170 // issue 399, for which there isn't even an obvious direction.
171 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
172 QualType MemberOfType;
173 if (SS.isSet()) {
174 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
175 // Figure out the type of the context, if it has one.
John McCalle78aac42010-03-10 03:28:59 +0000176 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
177 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000178 }
179 }
180 if (MemberOfType.isNull())
181 MemberOfType = SearchType;
182
183 if (MemberOfType.isNull())
184 continue;
185
186 // We're referring into a class template specialization. If the
187 // class template we found is the same as the template being
188 // specialized, we found what we are looking for.
189 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
190 if (ClassTemplateSpecializationDecl *Spec
191 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
192 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
193 Template->getCanonicalDecl())
194 return MemberOfType.getAsOpaquePtr();
195 }
196
197 continue;
198 }
199
200 // We're referring to an unresolved class template
201 // specialization. Determine whether we class template we found
202 // is the same as the template being specialized or, if we don't
203 // know which template is being specialized, that it at least
204 // has the same name.
205 if (const TemplateSpecializationType *SpecType
206 = MemberOfType->getAs<TemplateSpecializationType>()) {
207 TemplateName SpecName = SpecType->getTemplateName();
208
209 // The class template we found is the same template being
210 // specialized.
211 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
212 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
213 return MemberOfType.getAsOpaquePtr();
214
215 continue;
216 }
217
218 // The class template we found has the same name as the
219 // (dependent) template name being specialized.
220 if (DependentTemplateName *DepTemplate
221 = SpecName.getAsDependentTemplateName()) {
222 if (DepTemplate->isIdentifier() &&
223 DepTemplate->getIdentifier() == Template->getIdentifier())
224 return MemberOfType.getAsOpaquePtr();
225
226 continue;
227 }
228 }
229 }
230 }
231
232 if (isDependent) {
233 // We didn't find our type, but that's okay: it's dependent
234 // anyway.
235 NestedNameSpecifier *NNS = 0;
236 SourceRange Range;
237 if (SS.isSet()) {
238 NNS = (NestedNameSpecifier *)SS.getScopeRep();
239 Range = SourceRange(SS.getRange().getBegin(), NameLoc);
240 } else {
241 NNS = NestedNameSpecifier::Create(Context, &II);
242 Range = SourceRange(NameLoc);
243 }
244
Abramo Bagnarad7548482010-05-19 21:37:53 +0000245 return CheckTypenameType(ETK_None, NNS, II, SourceLocation(),
246 Range, NameLoc).getAsOpaquePtr();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000247 }
248
249 if (ObjectTypePtr)
250 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
251 << &II;
252 else
253 Diag(NameLoc, diag::err_destructor_class_name);
254
255 return 0;
256}
257
Douglas Gregor9da64192010-04-26 22:37:10 +0000258/// \brief Build a C++ typeid expression with a type operand.
259Sema::OwningExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
260 SourceLocation TypeidLoc,
261 TypeSourceInfo *Operand,
262 SourceLocation RParenLoc) {
263 // C++ [expr.typeid]p4:
264 // The top-level cv-qualifiers of the lvalue expression or the type-id
265 // that is the operand of typeid are always ignored.
266 // If the type of the type-id is a class type or a reference to a class
267 // type, the class shall be completely-defined.
Douglas Gregor876cec22010-06-02 06:16:02 +0000268 Qualifiers Quals;
269 QualType T
270 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
271 Quals);
Douglas Gregor9da64192010-04-26 22:37:10 +0000272 if (T->getAs<RecordType>() &&
273 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
274 return ExprError();
Daniel Dunbar0547ad32010-05-11 21:32:35 +0000275
Douglas Gregor9da64192010-04-26 22:37:10 +0000276 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
277 Operand,
278 SourceRange(TypeidLoc, RParenLoc)));
279}
280
281/// \brief Build a C++ typeid expression with an expression operand.
282Sema::OwningExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
283 SourceLocation TypeidLoc,
284 ExprArg Operand,
285 SourceLocation RParenLoc) {
286 bool isUnevaluatedOperand = true;
287 Expr *E = static_cast<Expr *>(Operand.get());
288 if (E && !E->isTypeDependent()) {
289 QualType T = E->getType();
290 if (const RecordType *RecordT = T->getAs<RecordType>()) {
291 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
292 // C++ [expr.typeid]p3:
293 // [...] If the type of the expression is a class type, the class
294 // shall be completely-defined.
295 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
296 return ExprError();
297
298 // C++ [expr.typeid]p3:
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000299 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor9da64192010-04-26 22:37:10 +0000300 // polymorphic class type [...] [the] expression is an unevaluated
301 // operand. [...]
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000302 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000303 isUnevaluatedOperand = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000304
305 // We require a vtable to query the type at run time.
306 MarkVTableUsed(TypeidLoc, RecordD);
307 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000308 }
309
310 // C++ [expr.typeid]p4:
311 // [...] If the type of the type-id is a reference to a possibly
312 // cv-qualified type, the result of the typeid expression refers to a
313 // std::type_info object representing the cv-unqualified referenced
314 // type.
Douglas Gregor876cec22010-06-02 06:16:02 +0000315 Qualifiers Quals;
316 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
317 if (!Context.hasSameType(T, UnqualT)) {
318 T = UnqualT;
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000319 ImpCastExprToType(E, UnqualT, CastExpr::CK_NoOp, CastCategory(E));
Douglas Gregor9da64192010-04-26 22:37:10 +0000320 Operand.release();
321 Operand = Owned(E);
322 }
323 }
324
325 // If this is an unevaluated operand, clear out the set of
326 // declaration references we have been computing and eliminate any
327 // temporaries introduced in its computation.
328 if (isUnevaluatedOperand)
329 ExprEvalContexts.back().Context = Unevaluated;
330
331 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
332 Operand.takeAs<Expr>(),
333 SourceRange(TypeidLoc, RParenLoc)));
334}
335
336/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000337Action::OwningExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000338Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
339 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000340 // Find the std::type_info type.
Douglas Gregor87f54062009-09-15 22:30:29 +0000341 if (!StdNamespace)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000342 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000343
Chris Lattnerec7f7732008-11-20 05:51:55 +0000344 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCall27b18f82009-11-17 02:14:36 +0000345 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +0000346 LookupQualifiedName(R, getStdNamespace());
John McCall67c00872009-12-02 08:25:40 +0000347 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
Chris Lattnerec7f7732008-11-20 05:51:55 +0000348 if (!TypeInfoRecordDecl)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000349 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Douglas Gregor9da64192010-04-26 22:37:10 +0000350
Sebastian Redlc4704762008-11-11 11:37:55 +0000351 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
Douglas Gregor9da64192010-04-26 22:37:10 +0000352
353 if (isType) {
354 // The operand is a type; handle it as such.
355 TypeSourceInfo *TInfo = 0;
356 QualType T = GetTypeFromParser(TyOrExpr, &TInfo);
357 if (T.isNull())
358 return ExprError();
359
360 if (!TInfo)
361 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000362
Douglas Gregor9da64192010-04-26 22:37:10 +0000363 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000364 }
Mike Stump11289f42009-09-09 15:08:12 +0000365
Douglas Gregor9da64192010-04-26 22:37:10 +0000366 // The operand is an expression.
367 return BuildCXXTypeId(TypeInfoType, OpLoc, Owned((Expr*)TyOrExpr), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000368}
369
Steve Naroff66356bd2007-09-16 14:56:35 +0000370/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000371Action::OwningExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000372Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000373 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000374 "Unknown C++ Boolean value!");
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000375 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
376 Context.BoolTy, OpLoc));
Bill Wendling4073ed52007-02-13 01:51:42 +0000377}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000378
Sebastian Redl576fd422009-05-10 18:38:11 +0000379/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
380Action::OwningExprResult
381Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
382 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
383}
384
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000385/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000386Action::OwningExprResult
387Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000388 Expr *Ex = E.takeAs<Expr>();
389 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
390 return ExprError();
391 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
392}
393
394/// CheckCXXThrowOperand - Validate the operand of a throw.
395bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
396 // C++ [except.throw]p3:
Douglas Gregor247894b2009-12-23 22:04:40 +0000397 // A throw-expression initializes a temporary object, called the exception
398 // object, the type of which is determined by removing any top-level
399 // cv-qualifiers from the static type of the operand of throw and adjusting
400 // the type from "array of T" or "function returning T" to "pointer to T"
401 // or "pointer to function returning T", [...]
402 if (E->getType().hasQualifiers())
403 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp,
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000404 CastCategory(E));
Douglas Gregor247894b2009-12-23 22:04:40 +0000405
Sebastian Redl4de47b42009-04-27 20:27:31 +0000406 DefaultFunctionArrayConversion(E);
407
408 // If the type of the exception would be an incomplete type or a pointer
409 // to an incomplete type other than (cv) void the program is ill-formed.
410 QualType Ty = E->getType();
John McCall2e6567a2010-04-22 01:10:34 +0000411 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000412 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000413 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000414 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000415 }
416 if (!isPointer || !Ty->isVoidType()) {
417 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlsson029fc692009-08-26 22:59:12 +0000418 PDiag(isPointer ? diag::err_throw_incomplete_ptr
419 : diag::err_throw_incomplete)
420 << E->getSourceRange()))
Sebastian Redl4de47b42009-04-27 20:27:31 +0000421 return true;
Rafael Espindola70e040d2010-03-02 21:28:26 +0000422
Douglas Gregore8154332010-04-15 18:05:39 +0000423 if (RequireNonAbstractType(ThrowLoc, E->getType(),
424 PDiag(diag::err_throw_abstract_type)
425 << E->getSourceRange()))
426 return true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000427 }
428
John McCall2e6567a2010-04-22 01:10:34 +0000429 // Initialize the exception result. This implicitly weeds out
430 // abstract types or types with inaccessible copy constructors.
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000431 // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p34.
John McCall2e6567a2010-04-22 01:10:34 +0000432 InitializedEntity Entity =
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000433 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
434 /*NRVO=*/false);
John McCall2e6567a2010-04-22 01:10:34 +0000435 OwningExprResult Res = PerformCopyInitialization(Entity,
436 SourceLocation(),
437 Owned(E));
438 if (Res.isInvalid())
439 return true;
440 E = Res.takeAs<Expr>();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000441
Eli Friedman91a3d272010-06-03 20:39:03 +0000442 // If the exception has class type, we need additional handling.
443 const RecordType *RecordTy = Ty->getAs<RecordType>();
444 if (!RecordTy)
445 return false;
446 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
447
Douglas Gregor88d292c2010-05-13 16:44:06 +0000448 // If we are throwing a polymorphic class type or pointer thereof,
449 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000450 MarkVTableUsed(ThrowLoc, RD);
451
452 // If the class has a non-trivial destructor, we must be able to call it.
453 if (RD->hasTrivialDestructor())
454 return false;
455
Douglas Gregorbac74902010-07-01 14:13:13 +0000456 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +0000457 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman91a3d272010-06-03 20:39:03 +0000458 if (!Destructor)
459 return false;
460
461 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
462 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregor747eb782010-07-08 06:14:04 +0000463 PDiag(diag::err_access_dtor_exception) << Ty);
Sebastian Redl4de47b42009-04-27 20:27:31 +0000464 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000465}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000466
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000467Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000468 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
469 /// is a non-lvalue expression whose value is the address of the object for
470 /// which the function is called.
471
John McCall87fe5d52010-05-20 01:18:31 +0000472 DeclContext *DC = getFunctionLevelDeclContext();
473 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000474 if (MD->isInstance())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000475 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregorb15af892010-01-07 23:12:05 +0000476 MD->getThisType(Context),
477 /*isImplicit=*/false));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000478
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000479 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000480}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000481
482/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
483/// Can be interpreted either as function-style casting ("int(x)")
484/// or class type construction ("ClassType(x,y,z)")
485/// or creation of a value-initialized type ("int()").
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000486Action::OwningExprResult
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000487Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
488 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000489 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000490 SourceLocation *CommaLocs,
491 SourceLocation RParenLoc) {
Douglas Gregor7df89f52010-02-05 19:11:37 +0000492 if (!TypeRep)
493 return ExprError();
494
John McCall97513962010-01-15 18:39:57 +0000495 TypeSourceInfo *TInfo;
496 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
497 if (!TInfo)
498 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000499 unsigned NumExprs = exprs.size();
500 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000501 SourceLocation TyBeginLoc = TypeRange.getBegin();
502 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
503
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000504 if (Ty->isDependentType() ||
Douglas Gregor0950e412009-03-13 21:01:28 +0000505 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000506 exprs.release();
Mike Stump11289f42009-09-09 15:08:12 +0000507
508 return Owned(CXXUnresolvedConstructExpr::Create(Context,
509 TypeRange.getBegin(), Ty,
Douglas Gregorce934142009-05-20 18:46:25 +0000510 LParenLoc,
511 Exprs, NumExprs,
512 RParenLoc));
Douglas Gregor0950e412009-03-13 21:01:28 +0000513 }
514
Anders Carlsson55243162009-08-27 03:53:50 +0000515 if (Ty->isArrayType())
516 return ExprError(Diag(TyBeginLoc,
517 diag::err_value_init_for_array_type) << FullRange);
518 if (!Ty->isVoidType() &&
519 RequireCompleteType(TyBeginLoc, Ty,
520 PDiag(diag::err_invalid_incomplete_type_use)
521 << FullRange))
522 return ExprError();
Fariborz Jahanian9a14b842009-10-23 21:01:39 +0000523
Anders Carlsson55243162009-08-27 03:53:50 +0000524 if (RequireNonAbstractType(TyBeginLoc, Ty,
525 diag::err_allocation_of_abstract_type))
526 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000527
528
Douglas Gregordd04d332009-01-16 18:33:17 +0000529 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000530 // If the expression list is a single expression, the type conversion
531 // expression is equivalent (in definedness, and if defined in meaning) to the
532 // corresponding cast expression.
533 //
534 if (NumExprs == 1) {
Anders Carlssonf10e4142009-08-07 22:21:05 +0000535 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
John McCallcf142162010-08-07 06:22:56 +0000536 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +0000537 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, BasePath,
538 /*FunctionalStyle=*/true))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000539 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +0000540
541 exprs.release();
Anders Carlssone9766d52009-09-09 21:33:21 +0000542
John McCallcf142162010-08-07 06:22:56 +0000543 return Owned(CXXFunctionalCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +0000544 Ty.getNonLValueExprType(Context),
John McCallcf142162010-08-07 06:22:56 +0000545 TInfo, TyBeginLoc, Kind,
546 Exprs[0], &BasePath,
547 RParenLoc));
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000548 }
549
Douglas Gregor747eb782010-07-08 06:14:04 +0000550 if (Ty->isRecordType()) {
551 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
552 InitializationKind Kind
553 = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
554 LParenLoc, RParenLoc)
555 : InitializationKind::CreateValue(TypeRange.getBegin(),
556 LParenLoc, RParenLoc);
557 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
558 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
559 move(exprs));
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000560
Douglas Gregor747eb782010-07-08 06:14:04 +0000561 // FIXME: Improve AST representation?
562 return move(Result);
Douglas Gregordd04d332009-01-16 18:33:17 +0000563 }
564
565 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000566 // If the expression list specifies more than a single value, the type shall
567 // be a class with a suitably declared constructor.
568 //
569 if (NumExprs > 1)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000570 return ExprError(Diag(CommaLocs[0],
571 diag::err_builtin_func_cast_more_than_one_arg)
572 << FullRange);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000573
574 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregordd04d332009-01-16 18:33:17 +0000575 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000576 // The expression T(), where T is a simple-type-specifier for a non-array
577 // complete object type or the (possibly cv-qualified) void type, creates an
578 // rvalue of the specified type, which is value-initialized.
579 //
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000580 exprs.release();
Douglas Gregor747eb782010-07-08 06:14:04 +0000581 return Owned(new (Context) CXXScalarValueInitExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000582}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000583
584
Sebastian Redlbd150f42008-11-21 19:14:01 +0000585/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
586/// @code new (memory) int[size][4] @endcode
587/// or
588/// @code ::new Foo(23, "hello") @endcode
589/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000590Action::OwningExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +0000591Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000592 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Douglas Gregorf2753b32010-07-13 15:54:32 +0000593 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl351bb782008-12-02 14:43:59 +0000594 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000595 MultiExprArg ConstructorArgs,
Mike Stump11289f42009-09-09 15:08:12 +0000596 SourceLocation ConstructorRParen) {
Sebastian Redl351bb782008-12-02 14:43:59 +0000597 Expr *ArraySize = 0;
Sebastian Redl351bb782008-12-02 14:43:59 +0000598 // If the specified type is an array, unwrap it and save the expression.
599 if (D.getNumTypeObjects() > 0 &&
600 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
601 DeclaratorChunk &Chunk = D.getTypeObject(0);
602 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000603 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
604 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000605 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000606 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
607 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000608
Sebastian Redl351bb782008-12-02 14:43:59 +0000609 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000610 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +0000611 }
612
Douglas Gregor73341c42009-09-11 00:18:58 +0000613 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000614 if (ArraySize) {
615 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +0000616 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
617 break;
618
619 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
620 if (Expr *NumElts = (Expr *)Array.NumElts) {
621 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
622 !NumElts->isIntegerConstantExpr(Context)) {
623 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
624 << NumElts->getSourceRange();
625 return ExprError();
626 }
627 }
628 }
629 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000630
John McCallbcd03502009-12-07 02:54:59 +0000631 //FIXME: Store TypeSourceInfo in CXXNew expression.
John McCall8cb7bdf2010-06-04 23:28:52 +0000632 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
633 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000634 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000635 return ExprError();
Ted Kremenekabb1f912010-06-25 22:48:49 +0000636
637 SourceRange R = TInfo->getTypeLoc().getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +0000638 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000639 PlacementLParen,
Mike Stump11289f42009-09-09 15:08:12 +0000640 move(PlacementArgs),
Douglas Gregord0fefba2009-05-21 00:00:09 +0000641 PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +0000642 TypeIdParens,
Mike Stump11289f42009-09-09 15:08:12 +0000643 AllocType,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000644 D.getSourceRange().getBegin(),
Ted Kremenekabb1f912010-06-25 22:48:49 +0000645 R,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000646 Owned(ArraySize),
647 ConstructorLParen,
648 move(ConstructorArgs),
649 ConstructorRParen);
650}
651
Mike Stump11289f42009-09-09 15:08:12 +0000652Sema::OwningExprResult
Douglas Gregord0fefba2009-05-21 00:00:09 +0000653Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
654 SourceLocation PlacementLParen,
655 MultiExprArg PlacementArgs,
656 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +0000657 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000658 QualType AllocType,
659 SourceLocation TypeLoc,
660 SourceRange TypeRange,
661 ExprArg ArraySizeE,
662 SourceLocation ConstructorLParen,
663 MultiExprArg ConstructorArgs,
664 SourceLocation ConstructorRParen) {
665 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000666 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +0000667
Douglas Gregorcda95f42010-05-16 16:01:03 +0000668 // Per C++0x [expr.new]p5, the type being constructed may be a
669 // typedef of an array type.
670 if (!ArraySizeE.get()) {
671 if (const ConstantArrayType *Array
672 = Context.getAsConstantArrayType(AllocType)) {
673 ArraySizeE = Owned(new (Context) IntegerLiteral(Array->getSize(),
674 Context.getSizeType(),
675 TypeRange.getEnd()));
676 AllocType = Array->getElementType();
677 }
678 }
Sebastian Redlbd150f42008-11-21 19:14:01 +0000679
Douglas Gregorcda95f42010-05-16 16:01:03 +0000680 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl351bb782008-12-02 14:43:59 +0000681
Sebastian Redlbd150f42008-11-21 19:14:01 +0000682 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
683 // or enumeration type with a non-negative value."
Douglas Gregord0fefba2009-05-21 00:00:09 +0000684 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000685 if (ArraySize && !ArraySize->isTypeDependent()) {
Douglas Gregor4799d032010-06-30 00:20:43 +0000686
Sebastian Redl351bb782008-12-02 14:43:59 +0000687 QualType SizeType = ArraySize->getType();
Douglas Gregorf4ea7252010-06-29 23:17:37 +0000688
Douglas Gregor4799d032010-06-30 00:20:43 +0000689 OwningExprResult ConvertedSize
690 = ConvertToIntegralOrEnumerationType(StartLoc, move(ArraySizeE),
691 PDiag(diag::err_array_size_not_integral),
692 PDiag(diag::err_array_size_incomplete_type)
693 << ArraySize->getSourceRange(),
694 PDiag(diag::err_array_size_explicit_conversion),
695 PDiag(diag::note_array_size_conversion),
696 PDiag(diag::err_array_size_ambiguous_conversion),
697 PDiag(diag::note_array_size_conversion),
698 PDiag(getLangOptions().CPlusPlus0x? 0
699 : diag::ext_array_size_conversion));
700 if (ConvertedSize.isInvalid())
701 return ExprError();
702
703 ArraySize = ConvertedSize.takeAs<Expr>();
704 ArraySizeE = Owned(ArraySize);
705 SizeType = ArraySize->getType();
Douglas Gregorb90df602010-06-16 00:17:44 +0000706 if (!SizeType->isIntegralOrEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +0000707 return ExprError();
708
Sebastian Redl351bb782008-12-02 14:43:59 +0000709 // Let's see if this is a constant < 0. If so, we reject it out of hand.
710 // We don't care about special rules, so we tell the machinery it's not
711 // evaluated - it gives us a result in more cases.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000712 if (!ArraySize->isValueDependent()) {
713 llvm::APSInt Value;
714 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
715 if (Value < llvm::APSInt(
Anders Carlsson8ab20bb2009-09-23 00:37:25 +0000716 llvm::APInt::getNullValue(Value.getBitWidth()),
717 Value.isUnsigned()))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000718 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregorcaa1bf42010-08-18 00:39:00 +0000719 diag::err_typecheck_negative_array_size)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000720 << ArraySize->getSourceRange());
Douglas Gregorcaa1bf42010-08-18 00:39:00 +0000721
722 if (!AllocType->isDependentType()) {
723 unsigned ActiveSizeBits
724 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
725 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
726 Diag(ArraySize->getSourceRange().getBegin(),
727 diag::err_array_too_large)
728 << Value.toString(10)
729 << ArraySize->getSourceRange();
730 return ExprError();
731 }
732 }
Douglas Gregorf2753b32010-07-13 15:54:32 +0000733 } else if (TypeIdParens.isValid()) {
734 // Can't have dynamic array size when the type-id is in parentheses.
735 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
736 << ArraySize->getSourceRange()
737 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
738 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
739
740 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000741 }
Sebastian Redl351bb782008-12-02 14:43:59 +0000742 }
Anders Carlsson8ab20bb2009-09-23 00:37:25 +0000743
Eli Friedman06ed2a52009-10-20 08:27:19 +0000744 ImpCastExprToType(ArraySize, Context.getSizeType(),
745 CastExpr::CK_IntegralCast);
Sebastian Redl351bb782008-12-02 14:43:59 +0000746 }
Sebastian Redlbd150f42008-11-21 19:14:01 +0000747
Sebastian Redlbd150f42008-11-21 19:14:01 +0000748 FunctionDecl *OperatorNew = 0;
749 FunctionDecl *OperatorDelete = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000750 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
751 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000752
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000753 if (!AllocType->isDependentType() &&
754 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
755 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000756 SourceRange(PlacementLParen, PlacementRParen),
757 UseGlobal, AllocType, ArraySize, PlaceArgs,
758 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000759 return ExprError();
Fariborz Jahanian835026e2009-11-24 18:29:37 +0000760 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000761 if (OperatorNew) {
762 // Add default arguments, if any.
763 const FunctionProtoType *Proto =
764 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +0000765 VariadicCallType CallType =
766 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Anders Carlssonc144bc22010-05-03 02:07:56 +0000767
768 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
769 Proto, 1, PlaceArgs, NumPlaceArgs,
770 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +0000771 return ExprError();
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000772
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000773 NumPlaceArgs = AllPlaceArgs.size();
774 if (NumPlaceArgs > 0)
775 PlaceArgs = &AllPlaceArgs[0];
776 }
777
Sebastian Redlbd150f42008-11-21 19:14:01 +0000778 bool Init = ConstructorLParen.isValid();
779 // --- Choosing a constructor ---
Sebastian Redlbd150f42008-11-21 19:14:01 +0000780 CXXConstructorDecl *Constructor = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000781 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
782 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmanfd8d4e12009-11-08 22:15:39 +0000783 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
784
Anders Carlssonc6bb0e12010-05-03 15:45:23 +0000785 // Array 'new' can't have any initializers.
Anders Carlssone6ae81b2010-05-16 16:24:20 +0000786 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlssonc6bb0e12010-05-03 15:45:23 +0000787 SourceRange InitRange(ConsArgs[0]->getLocStart(),
788 ConsArgs[NumConsArgs - 1]->getLocEnd());
789
790 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
791 return ExprError();
792 }
793
Douglas Gregor85dabae2009-12-16 01:38:02 +0000794 if (!AllocType->isDependentType() &&
795 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
796 // C++0x [expr.new]p15:
797 // A new-expression that creates an object of type T initializes that
798 // object as follows:
799 InitializationKind Kind
800 // - If the new-initializer is omitted, the object is default-
801 // initialized (8.5); if no initialization is performed,
802 // the object has indeterminate value
803 = !Init? InitializationKind::CreateDefault(TypeLoc)
804 // - Otherwise, the new-initializer is interpreted according to the
805 // initialization rules of 8.5 for direct-initialization.
806 : InitializationKind::CreateDirect(TypeLoc,
807 ConstructorLParen,
808 ConstructorRParen);
809
Douglas Gregor85dabae2009-12-16 01:38:02 +0000810 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +0000811 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000812 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000813 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
814 move(ConstructorArgs));
815 if (FullInit.isInvalid())
816 return ExprError();
817
818 // FullInit is our initializer; walk through it to determine if it's a
819 // constructor call, which CXXNewExpr handles directly.
820 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
821 if (CXXBindTemporaryExpr *Binder
822 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
823 FullInitExpr = Binder->getSubExpr();
824 if (CXXConstructExpr *Construct
825 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
826 Constructor = Construct->getConstructor();
827 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
828 AEnd = Construct->arg_end();
829 A != AEnd; ++A)
830 ConvertedConstructorArgs.push_back(A->Retain());
831 } else {
832 // Take the converted initializer.
833 ConvertedConstructorArgs.push_back(FullInit.release());
834 }
835 } else {
836 // No initialization required.
837 }
838
839 // Take the converted arguments and use them for the new expression.
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000840 NumConsArgs = ConvertedConstructorArgs.size();
841 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redlbd150f42008-11-21 19:14:01 +0000842 }
Douglas Gregor85dabae2009-12-16 01:38:02 +0000843
Douglas Gregor6642ca22010-02-26 05:06:18 +0000844 // Mark the new and delete operators as referenced.
845 if (OperatorNew)
846 MarkDeclarationReferenced(StartLoc, OperatorNew);
847 if (OperatorDelete)
848 MarkDeclarationReferenced(StartLoc, OperatorDelete);
849
Sebastian Redlbd150f42008-11-21 19:14:01 +0000850 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor4bbd1ac2009-10-17 21:40:42 +0000851
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000852 PlacementArgs.release();
853 ConstructorArgs.release();
Douglas Gregord0fefba2009-05-21 00:00:09 +0000854 ArraySizeE.release();
Ted Kremenekabb1f912010-06-25 22:48:49 +0000855
856 // FIXME: The TypeSourceInfo should also be included in CXXNewExpr.
Ted Kremenek9d6eb402010-02-11 22:51:03 +0000857 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregorf2753b32010-07-13 15:54:32 +0000858 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenek9d6eb402010-02-11 22:51:03 +0000859 ArraySize, Constructor, Init,
860 ConsArgs, NumConsArgs, OperatorDelete,
861 ResultType, StartLoc,
862 Init ? ConstructorRParen :
Ted Kremenekabb1f912010-06-25 22:48:49 +0000863 TypeRange.getEnd()));
Sebastian Redlbd150f42008-11-21 19:14:01 +0000864}
865
866/// CheckAllocatedType - Checks that a type is suitable as the allocated type
867/// in a new-expression.
868/// dimension off and stores the size expression in ArraySize.
Douglas Gregord0fefba2009-05-21 00:00:09 +0000869bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000870 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +0000871 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
872 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +0000873 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +0000874 return Diag(Loc, diag::err_bad_new_type)
875 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +0000876 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +0000877 return Diag(Loc, diag::err_bad_new_type)
878 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +0000879 else if (!AllocType->isDependentType() &&
Douglas Gregord0fefba2009-05-21 00:00:09 +0000880 RequireCompleteType(Loc, AllocType,
Anders Carlssond624e162009-08-26 23:45:07 +0000881 PDiag(diag::err_new_incomplete_type)
882 << R))
Sebastian Redlbd150f42008-11-21 19:14:01 +0000883 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +0000884 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +0000885 diag::err_allocation_of_abstract_type))
886 return true;
Sebastian Redlbd150f42008-11-21 19:14:01 +0000887
Sebastian Redlbd150f42008-11-21 19:14:01 +0000888 return false;
889}
890
Douglas Gregor6642ca22010-02-26 05:06:18 +0000891/// \brief Determine whether the given function is a non-placement
892/// deallocation function.
893static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
894 if (FD->isInvalidDecl())
895 return false;
896
897 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
898 return Method->isUsualDeallocationFunction();
899
900 return ((FD->getOverloadedOperator() == OO_Delete ||
901 FD->getOverloadedOperator() == OO_Array_Delete) &&
902 FD->getNumParams() == 1);
903}
904
Sebastian Redlfaf68082008-12-03 20:26:15 +0000905/// FindAllocationFunctions - Finds the overloads of operator new and delete
906/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000907bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
908 bool UseGlobal, QualType AllocType,
909 bool IsArray, Expr **PlaceArgs,
910 unsigned NumPlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +0000911 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +0000912 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-12-03 20:26:15 +0000913 // --- Choosing an allocation function ---
914 // C++ 5.3.4p8 - 14 & 18
915 // 1) If UseGlobal is true, only look in the global scope. Else, also look
916 // in the scope of the allocated class.
917 // 2) If an array size is given, look for operator new[], else look for
918 // operator new.
919 // 3) The first argument is always size_t. Append the arguments from the
920 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +0000921
922 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
923 // We don't care about the actual value of this argument.
924 // FIXME: Should the Sema create the expression and embed it in the syntax
925 // tree? Or should the consumer just recalculate the value?
Anders Carlssona471db02009-08-16 20:29:29 +0000926 IntegerLiteral Size(llvm::APInt::getNullValue(
927 Context.Target.getPointerWidth(0)),
928 Context.getSizeType(),
929 SourceLocation());
930 AllocArgs[0] = &Size;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000931 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
932
Douglas Gregor6642ca22010-02-26 05:06:18 +0000933 // C++ [expr.new]p8:
934 // If the allocated type is a non-array type, the allocation
935 // function’s name is operator new and the deallocation function’s
936 // name is operator delete. If the allocated type is an array
937 // type, the allocation function’s name is operator new[] and the
938 // deallocation function’s name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +0000939 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
940 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +0000941 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
942 IsArray ? OO_Array_Delete : OO_Delete);
943
Sebastian Redlfaf68082008-12-03 20:26:15 +0000944 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump11289f42009-09-09 15:08:12 +0000945 CXXRecordDecl *Record
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000946 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000947 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +0000948 AllocArgs.size(), Record, /*AllowMissing=*/true,
949 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +0000950 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000951 }
952 if (!OperatorNew) {
953 // Didn't find a member overload. Look for a global one.
954 DeclareGlobalNewDelete();
Sebastian Redl33a31012008-12-04 22:20:51 +0000955 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000956 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +0000957 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
958 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +0000959 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000960 }
961
John McCall0f55a032010-04-20 02:18:25 +0000962 // We don't need an operator delete if we're running under
963 // -fno-exceptions.
964 if (!getLangOptions().Exceptions) {
965 OperatorDelete = 0;
966 return false;
967 }
968
Anders Carlsson6f9dabf2009-05-31 20:26:12 +0000969 // FindAllocationOverload can change the passed in arguments, so we need to
970 // copy them back.
971 if (NumPlaceArgs > 0)
972 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump11289f42009-09-09 15:08:12 +0000973
Douglas Gregor6642ca22010-02-26 05:06:18 +0000974 // C++ [expr.new]p19:
975 //
976 // If the new-expression begins with a unary :: operator, the
977 // deallocation function’s name is looked up in the global
978 // scope. Otherwise, if the allocated type is a class type T or an
979 // array thereof, the deallocation function’s name is looked up in
980 // the scope of T. If this lookup fails to find the name, or if
981 // the allocated type is not a class type or array thereof, the
982 // deallocation function’s name is looked up in the global scope.
983 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
984 if (AllocType->isRecordType() && !UseGlobal) {
985 CXXRecordDecl *RD
986 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
987 LookupQualifiedName(FoundDelete, RD);
988 }
John McCallfb6f5262010-03-18 08:19:33 +0000989 if (FoundDelete.isAmbiguous())
990 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +0000991
992 if (FoundDelete.empty()) {
993 DeclareGlobalNewDelete();
994 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
995 }
996
997 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +0000998
999 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1000
John McCallfb6f5262010-03-18 08:19:33 +00001001 if (NumPlaceArgs > 0) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00001002 // C++ [expr.new]p20:
1003 // A declaration of a placement deallocation function matches the
1004 // declaration of a placement allocation function if it has the
1005 // same number of parameters and, after parameter transformations
1006 // (8.3.5), all parameter types except the first are
1007 // identical. [...]
1008 //
1009 // To perform this comparison, we compute the function type that
1010 // the deallocation function should have, and use that type both
1011 // for template argument deduction and for comparison purposes.
1012 QualType ExpectedFunctionType;
1013 {
1014 const FunctionProtoType *Proto
1015 = OperatorNew->getType()->getAs<FunctionProtoType>();
1016 llvm::SmallVector<QualType, 4> ArgTypes;
1017 ArgTypes.push_back(Context.VoidPtrTy);
1018 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1019 ArgTypes.push_back(Proto->getArgType(I));
1020
1021 ExpectedFunctionType
1022 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
1023 ArgTypes.size(),
1024 Proto->isVariadic(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001025 0, false, false, 0, 0,
1026 FunctionType::ExtInfo());
Douglas Gregor6642ca22010-02-26 05:06:18 +00001027 }
1028
1029 for (LookupResult::iterator D = FoundDelete.begin(),
1030 DEnd = FoundDelete.end();
1031 D != DEnd; ++D) {
1032 FunctionDecl *Fn = 0;
1033 if (FunctionTemplateDecl *FnTmpl
1034 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1035 // Perform template argument deduction to try to match the
1036 // expected function type.
1037 TemplateDeductionInfo Info(Context, StartLoc);
1038 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1039 continue;
1040 } else
1041 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1042
1043 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00001044 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001045 }
1046 } else {
1047 // C++ [expr.new]p20:
1048 // [...] Any non-placement deallocation function matches a
1049 // non-placement allocation function. [...]
1050 for (LookupResult::iterator D = FoundDelete.begin(),
1051 DEnd = FoundDelete.end();
1052 D != DEnd; ++D) {
1053 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1054 if (isNonPlacementDeallocationFunction(Fn))
John McCalla0296f72010-03-19 07:35:19 +00001055 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001056 }
1057 }
1058
1059 // C++ [expr.new]p20:
1060 // [...] If the lookup finds a single matching deallocation
1061 // function, that function will be called; otherwise, no
1062 // deallocation function will be called.
1063 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00001064 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00001065
1066 // C++0x [expr.new]p20:
1067 // If the lookup finds the two-parameter form of a usual
1068 // deallocation function (3.7.4.2) and that function, considered
1069 // as a placement deallocation function, would have been
1070 // selected as a match for the allocation function, the program
1071 // is ill-formed.
1072 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1073 isNonPlacementDeallocationFunction(OperatorDelete)) {
1074 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1075 << SourceRange(PlaceArgs[0]->getLocStart(),
1076 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1077 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1078 << DeleteName;
John McCallfb6f5262010-03-18 08:19:33 +00001079 } else {
1080 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCalla0296f72010-03-19 07:35:19 +00001081 Matches[0].first);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001082 }
1083 }
1084
Sebastian Redlfaf68082008-12-03 20:26:15 +00001085 return false;
1086}
1087
Sebastian Redl33a31012008-12-04 22:20:51 +00001088/// FindAllocationOverload - Find an fitting overload for the allocation
1089/// function in the specified scope.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001090bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1091 DeclarationName Name, Expr** Args,
1092 unsigned NumArgs, DeclContext *Ctx,
Mike Stump11289f42009-09-09 15:08:12 +00001093 bool AllowMissing, FunctionDecl *&Operator) {
John McCall27b18f82009-11-17 02:14:36 +00001094 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1095 LookupQualifiedName(R, Ctx);
John McCall9f3059a2009-10-09 21:13:30 +00001096 if (R.empty()) {
Sebastian Redl33a31012008-12-04 22:20:51 +00001097 if (AllowMissing)
1098 return false;
Sebastian Redl33a31012008-12-04 22:20:51 +00001099 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00001100 << Name << Range;
Sebastian Redl33a31012008-12-04 22:20:51 +00001101 }
1102
John McCallfb6f5262010-03-18 08:19:33 +00001103 if (R.isAmbiguous())
1104 return true;
1105
1106 R.suppressDiagnostics();
John McCall9f3059a2009-10-09 21:13:30 +00001107
John McCallbc077cf2010-02-08 23:07:23 +00001108 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor80a6cc52009-09-30 00:03:47 +00001109 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1110 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor55297ac2008-12-23 00:26:44 +00001111 // Even member operator new/delete are implicitly treated as
1112 // static, so don't use AddMemberCandidate.
John McCalla0296f72010-03-19 07:35:19 +00001113 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth93538422010-02-03 11:02:14 +00001114
John McCalla0296f72010-03-19 07:35:19 +00001115 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1116 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth93538422010-02-03 11:02:14 +00001117 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1118 Candidates,
1119 /*SuppressUserConversions=*/false);
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001120 continue;
Chandler Carruth93538422010-02-03 11:02:14 +00001121 }
1122
John McCalla0296f72010-03-19 07:35:19 +00001123 FunctionDecl *Fn = cast<FunctionDecl>(D);
1124 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth93538422010-02-03 11:02:14 +00001125 /*SuppressUserConversions=*/false);
Sebastian Redl33a31012008-12-04 22:20:51 +00001126 }
1127
1128 // Do the resolution.
1129 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001130 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl33a31012008-12-04 22:20:51 +00001131 case OR_Success: {
1132 // Got one!
1133 FunctionDecl *FnDecl = Best->Function;
1134 // The first argument is size_t, and the first parameter must be size_t,
1135 // too. This is checked on declaration and can be assumed. (It can't be
1136 // asserted on, though, since invalid decls are left in there.)
John McCallfb6f5262010-03-18 08:19:33 +00001137 // Watch out for variadic allocator function.
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001138 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1139 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Douglas Gregor34147272010-03-26 20:35:59 +00001140 OwningExprResult Result
1141 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
1142 FnDecl->getParamDecl(i)),
1143 SourceLocation(),
1144 Owned(Args[i]->Retain()));
1145 if (Result.isInvalid())
Sebastian Redl33a31012008-12-04 22:20:51 +00001146 return true;
Douglas Gregor34147272010-03-26 20:35:59 +00001147
1148 Args[i] = Result.takeAs<Expr>();
Sebastian Redl33a31012008-12-04 22:20:51 +00001149 }
1150 Operator = FnDecl;
John McCalla0296f72010-03-19 07:35:19 +00001151 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl33a31012008-12-04 22:20:51 +00001152 return false;
1153 }
1154
1155 case OR_No_Viable_Function:
Sebastian Redl33a31012008-12-04 22:20:51 +00001156 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00001157 << Name << Range;
John McCallad907772010-01-12 07:18:19 +00001158 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl33a31012008-12-04 22:20:51 +00001159 return true;
1160
1161 case OR_Ambiguous:
Sebastian Redl33a31012008-12-04 22:20:51 +00001162 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001163 << Name << Range;
John McCallad907772010-01-12 07:18:19 +00001164 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl33a31012008-12-04 22:20:51 +00001165 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001166
1167 case OR_Deleted:
1168 Diag(StartLoc, diag::err_ovl_deleted_call)
1169 << Best->Function->isDeleted()
1170 << Name << Range;
John McCallad907772010-01-12 07:18:19 +00001171 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001172 return true;
Sebastian Redl33a31012008-12-04 22:20:51 +00001173 }
1174 assert(false && "Unreachable, bad result from BestViableFunction");
1175 return true;
1176}
1177
1178
Sebastian Redlfaf68082008-12-03 20:26:15 +00001179/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1180/// delete. These are:
1181/// @code
1182/// void* operator new(std::size_t) throw(std::bad_alloc);
1183/// void* operator new[](std::size_t) throw(std::bad_alloc);
1184/// void operator delete(void *) throw();
1185/// void operator delete[](void *) throw();
1186/// @endcode
1187/// Note that the placement and nothrow forms of new are *not* implicitly
1188/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00001189void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001190 if (GlobalNewDeleteDeclared)
1191 return;
Douglas Gregor87f54062009-09-15 22:30:29 +00001192
1193 // C++ [basic.std.dynamic]p2:
1194 // [...] The following allocation and deallocation functions (18.4) are
1195 // implicitly declared in global scope in each translation unit of a
1196 // program
1197 //
1198 // void* operator new(std::size_t) throw(std::bad_alloc);
1199 // void* operator new[](std::size_t) throw(std::bad_alloc);
1200 // void operator delete(void*) throw();
1201 // void operator delete[](void*) throw();
1202 //
1203 // These implicit declarations introduce only the function names operator
1204 // new, operator new[], operator delete, operator delete[].
1205 //
1206 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1207 // "std" or "bad_alloc" as necessary to form the exception specification.
1208 // However, we do not make these implicit declarations visible to name
1209 // lookup.
Douglas Gregor87f54062009-09-15 22:30:29 +00001210 if (!StdBadAlloc) {
1211 // The "std::bad_alloc" class has not yet been declared, so build it
1212 // implicitly.
Abramo Bagnara6150c882010-05-11 21:36:43 +00001213 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00001214 getOrCreateStdNamespace(),
Douglas Gregor87f54062009-09-15 22:30:29 +00001215 SourceLocation(),
1216 &PP.getIdentifierTable().get("bad_alloc"),
1217 SourceLocation(), 0);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00001218 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00001219 }
1220
Sebastian Redlfaf68082008-12-03 20:26:15 +00001221 GlobalNewDeleteDeclared = true;
1222
1223 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1224 QualType SizeT = Context.getSizeType();
Nuno Lopes13c88c72009-12-16 16:59:22 +00001225 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001226
Sebastian Redlfaf68082008-12-03 20:26:15 +00001227 DeclareGlobalAllocationFunction(
1228 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001229 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001230 DeclareGlobalAllocationFunction(
1231 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001232 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001233 DeclareGlobalAllocationFunction(
1234 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1235 Context.VoidTy, VoidPtr);
1236 DeclareGlobalAllocationFunction(
1237 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1238 Context.VoidTy, VoidPtr);
1239}
1240
1241/// DeclareGlobalAllocationFunction - Declares a single implicit global
1242/// allocation function if it doesn't already exist.
1243void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopes13c88c72009-12-16 16:59:22 +00001244 QualType Return, QualType Argument,
1245 bool AddMallocAttr) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001246 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1247
1248 // Check if this function is already declared.
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001249 {
Douglas Gregor17eb26b2008-12-23 22:05:29 +00001250 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001251 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001252 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth93538422010-02-03 11:02:14 +00001253 // Only look at non-template functions, as it is the predefined,
1254 // non-templated allocation function we are trying to declare here.
1255 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1256 QualType InitialParamType =
Douglas Gregor684d7bd2009-12-22 23:42:49 +00001257 Context.getCanonicalType(
Chandler Carruth93538422010-02-03 11:02:14 +00001258 Func->getParamDecl(0)->getType().getUnqualifiedType());
1259 // FIXME: Do we need to check for default arguments here?
1260 if (Func->getNumParams() == 1 && InitialParamType == Argument)
1261 return;
1262 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00001263 }
1264 }
1265
Douglas Gregor87f54062009-09-15 22:30:29 +00001266 QualType BadAllocType;
1267 bool HasBadAllocExceptionSpec
1268 = (Name.getCXXOverloadedOperator() == OO_New ||
1269 Name.getCXXOverloadedOperator() == OO_Array_New);
1270 if (HasBadAllocExceptionSpec) {
1271 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00001272 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor87f54062009-09-15 22:30:29 +00001273 }
1274
1275 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1276 true, false,
1277 HasBadAllocExceptionSpec? 1 : 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001278 &BadAllocType,
1279 FunctionType::ExtInfo());
Sebastian Redlfaf68082008-12-03 20:26:15 +00001280 FunctionDecl *Alloc =
1281 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001282 FnType, /*TInfo=*/0, FunctionDecl::None,
1283 FunctionDecl::None, false, true);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001284 Alloc->setImplicit();
Nuno Lopes13c88c72009-12-16 16:59:22 +00001285
1286 if (AddMallocAttr)
1287 Alloc->addAttr(::new (Context) MallocAttr());
1288
Sebastian Redlfaf68082008-12-03 20:26:15 +00001289 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCallbcd03502009-12-07 02:54:59 +00001290 0, Argument, /*TInfo=*/0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001291 VarDecl::None,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00001292 VarDecl::None, 0);
Douglas Gregord5058122010-02-11 01:19:42 +00001293 Alloc->setParams(&Param, 1);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001294
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001295 // FIXME: Also add this declaration to the IdentifierResolver, but
1296 // make sure it is at the end of the chain to coincide with the
1297 // global scope.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001298 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001299}
1300
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001301bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1302 DeclarationName Name,
Anders Carlssonf98849e2009-12-02 17:15:43 +00001303 FunctionDecl* &Operator) {
John McCall27b18f82009-11-17 02:14:36 +00001304 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001305 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00001306 LookupQualifiedName(Found, RD);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001307
John McCall27b18f82009-11-17 02:14:36 +00001308 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001309 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001310
Chandler Carruthb6f99172010-06-28 00:30:51 +00001311 Found.suppressDiagnostics();
1312
John McCall66a87592010-08-04 00:31:26 +00001313 llvm::SmallVector<DeclAccessPair,4> Matches;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001314 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1315 F != FEnd; ++F) {
Chandler Carruth9b418232010-08-08 07:04:00 +00001316 NamedDecl *ND = (*F)->getUnderlyingDecl();
1317
1318 // Ignore template operator delete members from the check for a usual
1319 // deallocation function.
1320 if (isa<FunctionTemplateDecl>(ND))
1321 continue;
1322
1323 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall66a87592010-08-04 00:31:26 +00001324 Matches.push_back(F.getPair());
1325 }
1326
1327 // There's exactly one suitable operator; pick it.
1328 if (Matches.size() == 1) {
1329 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
1330 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1331 Matches[0]);
1332 return false;
1333
1334 // We found multiple suitable operators; complain about the ambiguity.
1335 } else if (!Matches.empty()) {
1336 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1337 << Name << RD;
1338
1339 for (llvm::SmallVectorImpl<DeclAccessPair>::iterator
1340 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1341 Diag((*F)->getUnderlyingDecl()->getLocation(),
1342 diag::note_member_declared_here) << Name;
1343 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001344 }
1345
1346 // We did find operator delete/operator delete[] declarations, but
1347 // none of them were suitable.
1348 if (!Found.empty()) {
1349 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1350 << Name << RD;
1351
1352 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
John McCall66a87592010-08-04 00:31:26 +00001353 F != FEnd; ++F)
1354 Diag((*F)->getUnderlyingDecl()->getLocation(),
1355 diag::note_member_declared_here) << Name;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001356
1357 return true;
1358 }
1359
1360 // Look for a global declaration.
1361 DeclareGlobalNewDelete();
1362 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1363
1364 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1365 Expr* DeallocArgs[1];
1366 DeallocArgs[0] = &Null;
1367 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1368 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1369 Operator))
1370 return true;
1371
1372 assert(Operator && "Did not find a deallocation function!");
1373 return false;
1374}
1375
Sebastian Redlbd150f42008-11-21 19:14:01 +00001376/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1377/// @code ::delete ptr; @endcode
1378/// or
1379/// @code delete [] ptr; @endcode
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001380Action::OwningExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001381Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump11289f42009-09-09 15:08:12 +00001382 bool ArrayForm, ExprArg Operand) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001383 // C++ [expr.delete]p1:
1384 // The operand shall have a pointer type, or a class type having a single
1385 // conversion function to a pointer type. The result has type void.
1386 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00001387 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1388
Anders Carlssona471db02009-08-16 20:29:29 +00001389 FunctionDecl *OperatorDelete = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001390
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001391 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001392 if (!Ex->isTypeDependent()) {
1393 QualType Type = Ex->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00001394
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001395 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregorf65f4902010-07-29 14:44:35 +00001396 if (RequireCompleteType(StartLoc, Type,
1397 PDiag(diag::err_delete_incomplete_class_type)))
1398 return ExprError();
1399
John McCallda4458e2010-03-31 01:36:47 +00001400 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1401
Fariborz Jahanianb54ccb22009-09-11 21:44:33 +00001402 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCallda4458e2010-03-31 01:36:47 +00001403 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001404 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001405 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00001406 NamedDecl *D = I.getDecl();
1407 if (isa<UsingShadowDecl>(D))
1408 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1409
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001410 // Skip over templated conversion functions; they aren't considered.
John McCallda4458e2010-03-31 01:36:47 +00001411 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001412 continue;
1413
John McCallda4458e2010-03-31 01:36:47 +00001414 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001415
1416 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1417 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00001418 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001419 ObjectPtrConversions.push_back(Conv);
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001420 }
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001421 if (ObjectPtrConversions.size() == 1) {
1422 // We have a single conversion to a pointer-to-object type. Perform
1423 // that conversion.
John McCallda4458e2010-03-31 01:36:47 +00001424 // TODO: don't redo the conversion calculation.
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001425 Operand.release();
John McCallda4458e2010-03-31 01:36:47 +00001426 if (!PerformImplicitConversion(Ex,
1427 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001428 AA_Converting)) {
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001429 Operand = Owned(Ex);
1430 Type = Ex->getType();
1431 }
1432 }
1433 else if (ObjectPtrConversions.size() > 1) {
1434 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1435 << Type << Ex->getSourceRange();
John McCallda4458e2010-03-31 01:36:47 +00001436 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1437 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001438 return ExprError();
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001439 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001440 }
1441
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001442 if (!Type->isPointerType())
1443 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1444 << Type << Ex->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001445
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001446 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregorbb3348e2010-05-24 17:01:56 +00001447 if (Pointee->isVoidType() && !isSFINAEContext()) {
1448 // The C++ standard bans deleting a pointer to a non-object type, which
1449 // effectively bans deletion of "void*". However, most compilers support
1450 // this, so we treat it as a warning unless we're in a SFINAE context.
1451 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1452 << Type << Ex->getSourceRange();
1453 } else if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001454 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1455 << Type << Ex->getSourceRange());
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001456 else if (!Pointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00001457 RequireCompleteType(StartLoc, Pointee,
Anders Carlssond624e162009-08-26 23:45:07 +00001458 PDiag(diag::warn_delete_incomplete)
1459 << Ex->getSourceRange()))
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001460 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001461
Douglas Gregor98496dc2009-09-29 21:38:53 +00001462 // C++ [expr.delete]p2:
1463 // [Note: a pointer to a const type can be the operand of a
1464 // delete-expression; it is not necessary to cast away the constness
1465 // (5.2.11) of the pointer expression before it is used as the operand
1466 // of the delete-expression. ]
1467 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
1468 CastExpr::CK_NoOp);
1469
1470 // Update the operand.
1471 Operand.take();
1472 Operand = ExprArg(*this, Ex);
1473
Anders Carlssona471db02009-08-16 20:29:29 +00001474 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1475 ArrayForm ? OO_Array_Delete : OO_Delete);
1476
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001477 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
1478 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1479
1480 if (!UseGlobal &&
1481 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00001482 return ExprError();
Anders Carlsson654e5c72009-11-14 03:17:38 +00001483
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001484 if (!RD->hasTrivialDestructor())
Douglas Gregore71edda2010-07-01 22:47:18 +00001485 if (const CXXDestructorDecl *Dtor = LookupDestructor(RD))
Mike Stump11289f42009-09-09 15:08:12 +00001486 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001487 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssona471db02009-08-16 20:29:29 +00001488 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001489
Anders Carlssona471db02009-08-16 20:29:29 +00001490 if (!OperatorDelete) {
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001491 // Look for a global declaration.
Anders Carlssona471db02009-08-16 20:29:29 +00001492 DeclareGlobalNewDelete();
1493 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001494 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001495 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssona471db02009-08-16 20:29:29 +00001496 OperatorDelete))
1497 return ExprError();
1498 }
Mike Stump11289f42009-09-09 15:08:12 +00001499
John McCall0f55a032010-04-20 02:18:25 +00001500 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1501
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001502 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redlbd150f42008-11-21 19:14:01 +00001503 }
1504
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001505 Operand.release();
1506 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssona471db02009-08-16 20:29:29 +00001507 OperatorDelete, Ex, StartLoc));
Sebastian Redlbd150f42008-11-21 19:14:01 +00001508}
1509
Douglas Gregor633caca2009-11-23 23:44:04 +00001510/// \brief Check the use of the given variable as a C++ condition in an if,
1511/// while, do-while, or switch statement.
Douglas Gregore60e41a2010-05-06 17:25:47 +00001512Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
1513 SourceLocation StmtLoc,
1514 bool ConvertToBoolean) {
Douglas Gregor633caca2009-11-23 23:44:04 +00001515 QualType T = ConditionVar->getType();
1516
1517 // C++ [stmt.select]p2:
1518 // The declarator shall not specify a function or an array.
1519 if (T->isFunctionType())
1520 return ExprError(Diag(ConditionVar->getLocation(),
1521 diag::err_invalid_use_of_function_type)
1522 << ConditionVar->getSourceRange());
1523 else if (T->isArrayType())
1524 return ExprError(Diag(ConditionVar->getLocation(),
1525 diag::err_invalid_use_of_array_type)
1526 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00001527
Douglas Gregore60e41a2010-05-06 17:25:47 +00001528 Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1529 ConditionVar->getLocation(),
1530 ConditionVar->getType().getNonReferenceType());
Douglas Gregorb412e172010-07-25 18:17:45 +00001531 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc))
Douglas Gregore60e41a2010-05-06 17:25:47 +00001532 return ExprError();
Douglas Gregore60e41a2010-05-06 17:25:47 +00001533
1534 return Owned(Condition);
Douglas Gregor633caca2009-11-23 23:44:04 +00001535}
1536
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001537/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1538bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1539 // C++ 6.4p4:
1540 // The value of a condition that is an initialized declaration in a statement
1541 // other than a switch statement is the value of the declared variable
1542 // implicitly converted to type bool. If that conversion is ill-formed, the
1543 // program is ill-formed.
1544 // The value of a condition that is an expression is the value of the
1545 // expression, implicitly converted to bool.
1546 //
Douglas Gregor5fb53972009-01-14 15:45:31 +00001547 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001548}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001549
1550/// Helper function to determine whether this is the (deprecated) C++
1551/// conversion from a string literal to a pointer to non-const char or
1552/// non-const wchar_t (for narrow and wide string literals,
1553/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00001554bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001555Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1556 // Look inside the implicit cast, if it exists.
1557 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1558 From = Cast->getSubExpr();
1559
1560 // A string literal (2.13.4) that is not a wide string literal can
1561 // be converted to an rvalue of type "pointer to char"; a wide
1562 // string literal can be converted to an rvalue of type "pointer
1563 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00001564 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001565 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001566 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00001567 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001568 // This conversion is considered only when there is an
1569 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall8ccfcb52009-09-24 19:53:00 +00001570 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001571 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1572 (!StrLit->isWide() &&
1573 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1574 ToPointeeType->getKind() == BuiltinType::Char_S))))
1575 return true;
1576 }
1577
1578 return false;
1579}
Douglas Gregor39c16d42008-10-24 04:54:22 +00001580
Douglas Gregora4253922010-04-16 22:17:36 +00001581static Sema::OwningExprResult BuildCXXCastArgument(Sema &S,
1582 SourceLocation CastLoc,
1583 QualType Ty,
1584 CastExpr::CastKind Kind,
1585 CXXMethodDecl *Method,
1586 Sema::ExprArg Arg) {
1587 Expr *From = Arg.takeAs<Expr>();
1588
1589 switch (Kind) {
1590 default: assert(0 && "Unhandled cast kind!");
1591 case CastExpr::CK_ConstructorConversion: {
1592 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
1593
1594 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
1595 Sema::MultiExprArg(S, (void **)&From, 1),
1596 CastLoc, ConstructorArgs))
1597 return S.ExprError();
1598
1599 Sema::OwningExprResult Result =
1600 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
1601 move_arg(ConstructorArgs));
1602 if (Result.isInvalid())
1603 return S.ExprError();
1604
1605 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1606 }
1607
1608 case CastExpr::CK_UserDefinedConversion: {
1609 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1610
1611 // Create an implicit call expr that calls it.
1612 // FIXME: pass the FoundDecl for the user-defined conversion here
1613 CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method);
1614 return S.MaybeBindToTemporary(CE);
1615 }
1616 }
1617}
1618
Douglas Gregor5fb53972009-01-14 15:45:31 +00001619/// PerformImplicitConversion - Perform an implicit conversion of the
1620/// expression From to the type ToType using the pre-computed implicit
1621/// conversion sequence ICS. Returns true if there was an error, false
1622/// otherwise. The expression From is replaced with the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001623/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001624/// used in the error message.
1625bool
1626Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1627 const ImplicitConversionSequence &ICS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001628 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall0d1da222010-01-12 00:44:57 +00001629 switch (ICS.getKind()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001630 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001631 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redl7c353682009-11-14 21:15:49 +00001632 IgnoreBaseAccess))
Douglas Gregor39c16d42008-10-24 04:54:22 +00001633 return true;
1634 break;
1635
Anders Carlsson110b07b2009-09-15 06:28:28 +00001636 case ImplicitConversionSequence::UserDefinedConversion: {
1637
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00001638 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1639 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlsson110b07b2009-09-15 06:28:28 +00001640 QualType BeforeToType;
1641 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00001642 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlsson110b07b2009-09-15 06:28:28 +00001643
1644 // If the user-defined conversion is specified by a conversion function,
1645 // the initial standard conversion sequence converts the source type to
1646 // the implicit object parameter of the conversion function.
1647 BeforeToType = Context.getTagDeclType(Conv->getParent());
1648 } else if (const CXXConstructorDecl *Ctor =
1649 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlssone9766d52009-09-09 21:33:21 +00001650 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001651 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00001652 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian55824512009-11-06 00:23:08 +00001653 // If the user-defined conversion is specified by a constructor, the
1654 // initial standard conversion sequence converts the source type to the
1655 // type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00001656 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1657 }
Anders Carlsson110b07b2009-09-15 06:28:28 +00001658 }
Anders Carlssone9766d52009-09-09 21:33:21 +00001659 else
1660 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian55824512009-11-06 00:23:08 +00001661 // Whatch out for elipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00001662 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian55824512009-11-06 00:23:08 +00001663 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001664 ICS.UserDefined.Before, AA_Converting,
Sebastian Redl7c353682009-11-14 21:15:49 +00001665 IgnoreBaseAccess))
Fariborz Jahanian55824512009-11-06 00:23:08 +00001666 return true;
1667 }
Anders Carlsson110b07b2009-09-15 06:28:28 +00001668
Anders Carlssone9766d52009-09-09 21:33:21 +00001669 OwningExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00001670 = BuildCXXCastArgument(*this,
1671 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00001672 ToType.getNonReferenceType(),
1673 CastKind, cast<CXXMethodDecl>(FD),
1674 Owned(From));
1675
1676 if (CastArg.isInvalid())
1677 return true;
Eli Friedmane96f1d32009-11-27 04:41:50 +00001678
1679 From = CastArg.takeAs<Expr>();
1680
Eli Friedmane96f1d32009-11-27 04:41:50 +00001681 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001682 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00001683 }
John McCall0d1da222010-01-12 00:44:57 +00001684
1685 case ImplicitConversionSequence::AmbiguousConversion:
1686 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1687 PDiag(diag::err_typecheck_ambiguous_condition)
1688 << From->getSourceRange());
1689 return true;
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00001690
Douglas Gregor39c16d42008-10-24 04:54:22 +00001691 case ImplicitConversionSequence::EllipsisConversion:
1692 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001693 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001694
1695 case ImplicitConversionSequence::BadConversion:
1696 return true;
1697 }
1698
1699 // Everything went well.
1700 return false;
1701}
1702
1703/// PerformImplicitConversion - Perform an implicit conversion of the
1704/// expression From to the type ToType by following the standard
1705/// conversion sequence SCS. Returns true if there was an error, false
1706/// otherwise. The expression From is replaced with the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00001707/// expression. Flavor is the context in which we're performing this
1708/// conversion, for use in error messages.
Mike Stump11289f42009-09-09 15:08:12 +00001709bool
Douglas Gregor39c16d42008-10-24 04:54:22 +00001710Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001711 const StandardConversionSequence& SCS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001712 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001713 // Overall FIXME: we are recomputing too many types here and doing far too
1714 // much extra work. What this means is that we need to keep track of more
1715 // information that is computed when we try the implicit conversion initially,
1716 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00001717 QualType FromType = From->getType();
1718
Douglas Gregor2fe98832008-11-03 19:09:14 +00001719 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00001720 // FIXME: When can ToType be a reference type?
1721 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00001722 if (SCS.Second == ICK_Derived_To_Base) {
1723 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1724 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1725 MultiExprArg(*this, (void **)&From, 1),
1726 /*FIXME:ConstructLoc*/SourceLocation(),
1727 ConstructorArgs))
1728 return true;
1729 OwningExprResult FromResult =
1730 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1731 ToType, SCS.CopyConstructor,
1732 move_arg(ConstructorArgs));
1733 if (FromResult.isInvalid())
1734 return true;
1735 From = FromResult.takeAs<Expr>();
1736 return false;
1737 }
Mike Stump11289f42009-09-09 15:08:12 +00001738 OwningExprResult FromResult =
1739 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1740 ToType, SCS.CopyConstructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00001741 MultiExprArg(*this, (void**)&From, 1));
Mike Stump11289f42009-09-09 15:08:12 +00001742
Anders Carlsson6eb55572009-08-25 05:12:04 +00001743 if (FromResult.isInvalid())
1744 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001745
Anders Carlsson6eb55572009-08-25 05:12:04 +00001746 From = FromResult.takeAs<Expr>();
Douglas Gregor2fe98832008-11-03 19:09:14 +00001747 return false;
1748 }
1749
Douglas Gregor980fb162010-04-29 18:24:40 +00001750 // Resolve overloaded function references.
1751 if (Context.hasSameType(FromType, Context.OverloadTy)) {
1752 DeclAccessPair Found;
1753 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1754 true, Found);
1755 if (!Fn)
1756 return true;
1757
1758 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1759 return true;
1760
1761 From = FixOverloadedFunctionReference(From, Found, Fn);
1762 FromType = From->getType();
1763 }
1764
Douglas Gregor39c16d42008-10-24 04:54:22 +00001765 // Perform the first implicit conversion.
1766 switch (SCS.First) {
1767 case ICK_Identity:
1768 case ICK_Lvalue_To_Rvalue:
1769 // Nothing to do.
1770 break;
1771
1772 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00001773 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson2c101b32009-08-08 21:04:35 +00001774 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001775 break;
1776
1777 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001778 FromType = Context.getPointerType(FromType);
Anders Carlsson6904f642009-09-01 20:37:18 +00001779 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001780 break;
1781
1782 default:
1783 assert(false && "Improper first standard conversion");
1784 break;
1785 }
1786
1787 // Perform the second implicit conversion
1788 switch (SCS.Second) {
1789 case ICK_Identity:
Sebastian Redl5d431642009-10-10 12:04:10 +00001790 // If both sides are functions (or pointers/references to them), there could
1791 // be incompatible exception declarations.
1792 if (CheckExceptionSpecCompatibility(From, ToType))
1793 return true;
1794 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00001795 break;
1796
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001797 case ICK_NoReturn_Adjustment:
1798 // If both sides are functions (or pointers/references to them), there could
1799 // be incompatible exception declarations.
1800 if (CheckExceptionSpecCompatibility(From, ToType))
1801 return true;
1802
1803 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1804 CastExpr::CK_NoOp);
1805 break;
1806
Douglas Gregor39c16d42008-10-24 04:54:22 +00001807 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001808 case ICK_Integral_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001809 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1810 break;
1811
1812 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001813 case ICK_Floating_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001814 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1815 break;
1816
1817 case ICK_Complex_Promotion:
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001818 case ICK_Complex_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001819 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1820 break;
1821
Douglas Gregor39c16d42008-10-24 04:54:22 +00001822 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00001823 if (ToType->isRealFloatingType())
Eli Friedman06ed2a52009-10-20 08:27:19 +00001824 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1825 else
1826 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1827 break;
1828
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001829 case ICK_Compatible_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001830 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001831 break;
1832
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001833 case ICK_Pointer_Conversion: {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001834 if (SCS.IncompatibleObjC) {
1835 // Diagnose incompatible Objective-C conversions
Mike Stump11289f42009-09-09 15:08:12 +00001836 Diag(From->getSourceRange().getBegin(),
Douglas Gregor47d3f272008-12-19 17:40:08 +00001837 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001838 << From->getType() << ToType << Action
Douglas Gregor47d3f272008-12-19 17:40:08 +00001839 << From->getSourceRange();
1840 }
1841
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001842
1843 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
John McCallcf142162010-08-07 06:22:56 +00001844 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00001845 if (CheckPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess))
Douglas Gregor39c16d42008-10-24 04:54:22 +00001846 return true;
John McCallcf142162010-08-07 06:22:56 +00001847 ImpCastExprToType(From, ToType, Kind, ImplicitCastExpr::RValue, &BasePath);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001848 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001849 }
1850
1851 case ICK_Pointer_Member: {
1852 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
John McCallcf142162010-08-07 06:22:56 +00001853 CXXCastPath BasePath;
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001854 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath,
1855 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001856 return true;
Sebastian Redl5d431642009-10-10 12:04:10 +00001857 if (CheckExceptionSpecCompatibility(From, ToType))
1858 return true;
John McCallcf142162010-08-07 06:22:56 +00001859 ImpCastExprToType(From, ToType, Kind, ImplicitCastExpr::RValue, &BasePath);
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001860 break;
1861 }
Anders Carlsson7fa434c2009-11-23 20:04:44 +00001862 case ICK_Boolean_Conversion: {
1863 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1864 if (FromType->isMemberPointerType())
1865 Kind = CastExpr::CK_MemberPointerToBoolean;
1866
1867 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001868 break;
Anders Carlsson7fa434c2009-11-23 20:04:44 +00001869 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001870
Douglas Gregor88d292c2010-05-13 16:44:06 +00001871 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00001872 CXXCastPath BasePath;
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001873 if (CheckDerivedToBaseConversion(From->getType(),
1874 ToType.getNonReferenceType(),
1875 From->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00001876 From->getSourceRange(),
1877 &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001878 IgnoreBaseAccess))
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001879 return true;
Douglas Gregor88d292c2010-05-13 16:44:06 +00001880
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001881 ImpCastExprToType(From, ToType.getNonReferenceType(),
John McCallcf142162010-08-07 06:22:56 +00001882 CastExpr::CK_DerivedToBase, CastCategory(From),
1883 &BasePath);
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001884 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00001885 }
1886
Douglas Gregor46188682010-05-18 22:42:18 +00001887 case ICK_Vector_Conversion:
1888 ImpCastExprToType(From, ToType, CastExpr::CK_BitCast);
1889 break;
1890
1891 case ICK_Vector_Splat:
1892 ImpCastExprToType(From, ToType, CastExpr::CK_VectorSplat);
1893 break;
1894
1895 case ICK_Complex_Real:
1896 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1897 break;
1898
1899 case ICK_Lvalue_To_Rvalue:
1900 case ICK_Array_To_Pointer:
1901 case ICK_Function_To_Pointer:
1902 case ICK_Qualification:
1903 case ICK_Num_Conversion_Kinds:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001904 assert(false && "Improper second standard conversion");
1905 break;
1906 }
1907
1908 switch (SCS.Third) {
1909 case ICK_Identity:
1910 // Nothing to do.
1911 break;
1912
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001913 case ICK_Qualification: {
1914 // The qualification keeps the category of the inner expression, unless the
1915 // target type isn't a reference.
1916 ImplicitCastExpr::ResultCategory Category = ToType->isReferenceType() ?
1917 CastCategory(From) : ImplicitCastExpr::RValue;
Douglas Gregora8a089b2010-07-13 18:40:04 +00001918 ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001919 CastExpr::CK_NoOp, Category);
Douglas Gregore489a7d2010-02-28 18:30:25 +00001920
1921 if (SCS.DeprecatedStringLiteralToCharPtr)
1922 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
1923 << ToType.getNonReferenceType();
1924
Douglas Gregor39c16d42008-10-24 04:54:22 +00001925 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001926 }
1927
Douglas Gregor39c16d42008-10-24 04:54:22 +00001928 default:
Douglas Gregor46188682010-05-18 22:42:18 +00001929 assert(false && "Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00001930 break;
1931 }
1932
1933 return false;
1934}
1935
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001936Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1937 SourceLocation KWLoc,
1938 SourceLocation LParen,
1939 TypeTy *Ty,
1940 SourceLocation RParen) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001941 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00001942
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001943 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1944 // all traits except __is_class, __is_enum and __is_union require a the type
1945 // to be complete.
1946 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump11289f42009-09-09 15:08:12 +00001947 if (RequireCompleteType(KWLoc, T,
Anders Carlsson029fc692009-08-26 22:59:12 +00001948 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001949 return ExprError();
1950 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001951
1952 // There is no point in eagerly computing the value. The traits are designed
1953 // to be used from type trait templates, so Ty will be a template parameter
1954 // 99% of the time.
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001955 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1956 RParen, Context.BoolTy));
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001957}
Sebastian Redl5822f082009-02-07 20:10:22 +00001958
1959QualType Sema::CheckPointerToMemberOperands(
Mike Stump11289f42009-09-09 15:08:12 +00001960 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl5822f082009-02-07 20:10:22 +00001961 const char *OpSpelling = isIndirect ? "->*" : ".*";
1962 // C++ 5.5p2
1963 // The binary operator .* [p3: ->*] binds its second operand, which shall
1964 // be of type "pointer to member of T" (where T is a completely-defined
1965 // class type) [...]
1966 QualType RType = rex->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001967 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00001968 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00001969 Diag(Loc, diag::err_bad_memptr_rhs)
1970 << OpSpelling << RType << rex->getSourceRange();
1971 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001972 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00001973
Sebastian Redl5822f082009-02-07 20:10:22 +00001974 QualType Class(MemPtr->getClass(), 0);
1975
Sebastian Redlc72350e2010-04-10 10:14:54 +00001976 if (RequireCompleteType(Loc, Class, diag::err_memptr_rhs_to_incomplete))
1977 return QualType();
1978
Sebastian Redl5822f082009-02-07 20:10:22 +00001979 // C++ 5.5p2
1980 // [...] to its first operand, which shall be of class T or of a class of
1981 // which T is an unambiguous and accessible base class. [p3: a pointer to
1982 // such a class]
1983 QualType LType = lex->getType();
1984 if (isIndirect) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001985 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl5822f082009-02-07 20:10:22 +00001986 LType = Ptr->getPointeeType().getNonReferenceType();
1987 else {
1988 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanian59f64202009-10-26 20:45:27 +00001989 << OpSpelling << 1 << LType
Douglas Gregora771f462010-03-31 17:46:05 +00001990 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00001991 return QualType();
1992 }
1993 }
1994
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001995 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00001996 // If we want to check the hierarchy, we need a complete type.
1997 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
1998 << OpSpelling << (int)isIndirect)) {
1999 return QualType();
2000 }
Anders Carlssona70cff62010-04-24 19:06:50 +00002001 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002002 /*DetectVirtual=*/false);
Mike Stump87c57ac2009-05-16 07:39:55 +00002003 // FIXME: Would it be useful to print full ambiguity paths, or is that
2004 // overkill?
Sebastian Redl5822f082009-02-07 20:10:22 +00002005 if (!IsDerivedFrom(LType, Class, Paths) ||
2006 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
2007 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman1fcf66b2010-01-16 00:00:48 +00002008 << (int)isIndirect << lex->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00002009 return QualType();
2010 }
Eli Friedman1fcf66b2010-01-16 00:00:48 +00002011 // Cast LHS to type of use.
2012 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002013 ImplicitCastExpr::ResultCategory Category =
2014 isIndirect ? ImplicitCastExpr::RValue : CastCategory(lex);
2015
John McCallcf142162010-08-07 06:22:56 +00002016 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00002017 BuildBasePathArray(Paths, BasePath);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002018 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, Category,
John McCallcf142162010-08-07 06:22:56 +00002019 &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00002020 }
2021
Douglas Gregor747eb782010-07-08 06:14:04 +00002022 if (isa<CXXScalarValueInitExpr>(rex->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00002023 // Diagnose use of pointer-to-member type which when used as
2024 // the functional cast in a pointer-to-member expression.
2025 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
2026 return QualType();
2027 }
Sebastian Redl5822f082009-02-07 20:10:22 +00002028 // C++ 5.5p2
2029 // The result is an object or a function of the type specified by the
2030 // second operand.
2031 // The cv qualifiers are the union of those in the pointer and the left side,
2032 // in accordance with 5.5p5 and 5.2.5.
2033 // FIXME: This returns a dereferenced member function pointer as a normal
2034 // function type. However, the only operation valid on such functions is
Mike Stump87c57ac2009-05-16 07:39:55 +00002035 // calling them. There's also a GCC extension to get a function pointer to the
2036 // thing, which is another complication, because this type - unlike the type
2037 // that is the result of this expression - takes the class as the first
Sebastian Redl5822f082009-02-07 20:10:22 +00002038 // argument.
2039 // We probably need a "MemberFunctionClosureType" or something like that.
2040 QualType Result = MemPtr->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00002041 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl5822f082009-02-07 20:10:22 +00002042 return Result;
2043}
Sebastian Redl1a99f442009-04-16 17:51:27 +00002044
Sebastian Redl1a99f442009-04-16 17:51:27 +00002045/// \brief Try to convert a type to another according to C++0x 5.16p3.
2046///
2047/// This is part of the parameter validation for the ? operator. If either
2048/// value operand is a class type, the two operands are attempted to be
2049/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002050/// It returns true if the program is ill-formed and has already been diagnosed
2051/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00002052static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
2053 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00002054 bool &HaveConversion,
2055 QualType &ToType) {
2056 HaveConversion = false;
2057 ToType = To->getType();
2058
2059 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
2060 SourceLocation());
Sebastian Redl1a99f442009-04-16 17:51:27 +00002061 // C++0x 5.16p3
2062 // The process for determining whether an operand expression E1 of type T1
2063 // can be converted to match an operand expression E2 of type T2 is defined
2064 // as follows:
2065 // -- If E2 is an lvalue:
Douglas Gregorf9edf802010-03-26 20:59:55 +00002066 bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid);
2067 if (ToIsLvalue) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002068 // E1 can be converted to match E2 if E1 can be implicitly converted to
2069 // type "lvalue reference to T2", subject to the constraint that in the
2070 // conversion the reference must bind directly to E1.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002071 QualType T = Self.Context.getLValueReferenceType(ToType);
2072 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2073
2074 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2075 if (InitSeq.isDirectReferenceBinding()) {
2076 ToType = T;
2077 HaveConversion = true;
2078 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00002079 }
Douglas Gregor838fcc32010-03-26 20:14:36 +00002080
2081 if (InitSeq.isAmbiguous())
2082 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002083 }
John McCall65eb8792010-02-25 01:37:24 +00002084
Sebastian Redl1a99f442009-04-16 17:51:27 +00002085 // -- If E2 is an rvalue, or if the conversion above cannot be done:
2086 // -- if E1 and E2 have class type, and the underlying class types are
2087 // the same or one is a base class of the other:
2088 QualType FTy = From->getType();
2089 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002090 const RecordType *FRec = FTy->getAs<RecordType>();
2091 const RecordType *TRec = TTy->getAs<RecordType>();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002092 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
2093 Self.IsDerivedFrom(FTy, TTy);
2094 if (FRec && TRec &&
2095 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002096 // E1 can be converted to match E2 if the class of T2 is the
2097 // same type as, or a base class of, the class of T1, and
2098 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00002099 if (FRec == TRec || FDerivedFromT) {
2100 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00002101 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2102 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2103 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2104 HaveConversion = true;
2105 return false;
2106 }
2107
2108 if (InitSeq.isAmbiguous())
2109 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2110 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00002111 }
Douglas Gregor838fcc32010-03-26 20:14:36 +00002112
2113 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00002114 }
Douglas Gregor838fcc32010-03-26 20:14:36 +00002115
2116 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2117 // implicitly converted to the type that expression E2 would have
Douglas Gregorf9edf802010-03-26 20:59:55 +00002118 // if E2 were converted to an rvalue (or the type it has, if E2 is
2119 // an rvalue).
2120 //
2121 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2122 // to the array-to-pointer or function-to-pointer conversions.
2123 if (!TTy->getAs<TagType>())
2124 TTy = TTy.getUnqualifiedType();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002125
2126 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2127 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2128 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
2129 ToType = TTy;
2130 if (InitSeq.isAmbiguous())
2131 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2132
Sebastian Redl1a99f442009-04-16 17:51:27 +00002133 return false;
2134}
2135
2136/// \brief Try to find a common type for two according to C++0x 5.16p5.
2137///
2138/// This is part of the parameter validation for the ? operator. If either
2139/// value operand is a class type, overload resolution is used to find a
2140/// conversion to a common type.
2141static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2142 SourceLocation Loc) {
2143 Expr *Args[2] = { LHS, RHS };
John McCallbc077cf2010-02-08 23:07:23 +00002144 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002145 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002146
2147 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00002148 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002149 case OR_Success:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002150 // We found a match. Perform the conversions on the arguments and move on.
2151 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002152 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00002153 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002154 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002155 break;
2156 return false;
2157
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002158 case OR_No_Viable_Function:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002159 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2160 << LHS->getType() << RHS->getType()
2161 << LHS->getSourceRange() << RHS->getSourceRange();
2162 return true;
2163
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002164 case OR_Ambiguous:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002165 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2166 << LHS->getType() << RHS->getType()
2167 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00002168 // FIXME: Print the possible common types by printing the return types of
2169 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00002170 break;
2171
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002172 case OR_Deleted:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002173 assert(false && "Conditional operator has only built-in overloads");
2174 break;
2175 }
2176 return true;
2177}
2178
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002179/// \brief Perform an "extended" implicit conversion as returned by
2180/// TryClassUnification.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002181static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2182 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2183 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2184 SourceLocation());
2185 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
2186 Sema::OwningExprResult Result = InitSeq.Perform(Self, Entity, Kind,
2187 Sema::MultiExprArg(Self, (void **)&E, 1));
2188 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002189 return true;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002190
2191 E = Result.takeAs<Expr>();
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002192 return false;
2193}
2194
Sebastian Redl1a99f442009-04-16 17:51:27 +00002195/// \brief Check the operands of ?: under C++ semantics.
2196///
2197/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2198/// extension. In this case, LHS == Cond. (But they're not aliases.)
2199QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2200 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00002201 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2202 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00002203
2204 // C++0x 5.16p1
2205 // The first expression is contextually converted to bool.
2206 if (!Cond->isTypeDependent()) {
2207 if (CheckCXXBooleanCondition(Cond))
2208 return QualType();
2209 }
2210
2211 // Either of the arguments dependent?
2212 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2213 return Context.DependentTy;
2214
2215 // C++0x 5.16p2
2216 // If either the second or the third operand has type (cv) void, ...
2217 QualType LTy = LHS->getType();
2218 QualType RTy = RHS->getType();
2219 bool LVoid = LTy->isVoidType();
2220 bool RVoid = RTy->isVoidType();
2221 if (LVoid || RVoid) {
2222 // ... then the [l2r] conversions are performed on the second and third
2223 // operands ...
Douglas Gregorb92a1562010-02-03 00:27:59 +00002224 DefaultFunctionArrayLvalueConversion(LHS);
2225 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002226 LTy = LHS->getType();
2227 RTy = RHS->getType();
2228
2229 // ... and one of the following shall hold:
2230 // -- The second or the third operand (but not both) is a throw-
2231 // expression; the result is of the type of the other and is an rvalue.
2232 bool LThrow = isa<CXXThrowExpr>(LHS);
2233 bool RThrow = isa<CXXThrowExpr>(RHS);
2234 if (LThrow && !RThrow)
2235 return RTy;
2236 if (RThrow && !LThrow)
2237 return LTy;
2238
2239 // -- Both the second and third operands have type void; the result is of
2240 // type void and is an rvalue.
2241 if (LVoid && RVoid)
2242 return Context.VoidTy;
2243
2244 // Neither holds, error.
2245 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2246 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2247 << LHS->getSourceRange() << RHS->getSourceRange();
2248 return QualType();
2249 }
2250
2251 // Neither is void.
2252
2253 // C++0x 5.16p3
2254 // Otherwise, if the second and third operand have different types, and
2255 // either has (cv) class type, and attempt is made to convert each of those
2256 // operands to the other.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002257 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00002258 (LTy->isRecordType() || RTy->isRecordType())) {
2259 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2260 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002261 QualType L2RType, R2LType;
2262 bool HaveL2R, HaveR2L;
2263 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002264 return QualType();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002265 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002266 return QualType();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002267
Sebastian Redl1a99f442009-04-16 17:51:27 +00002268 // If both can be converted, [...] the program is ill-formed.
2269 if (HaveL2R && HaveR2L) {
2270 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2271 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2272 return QualType();
2273 }
2274
2275 // If exactly one conversion is possible, that conversion is applied to
2276 // the chosen operand and the converted operands are used in place of the
2277 // original operands for the remainder of this section.
2278 if (HaveL2R) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00002279 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002280 return QualType();
2281 LTy = LHS->getType();
2282 } else if (HaveR2L) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00002283 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002284 return QualType();
2285 RTy = RHS->getType();
2286 }
2287 }
2288
2289 // C++0x 5.16p4
2290 // If the second and third operands are lvalues and have the same type,
2291 // the result is of that type [...]
Douglas Gregor697a3912010-04-01 22:47:07 +00002292 bool Same = Context.hasSameType(LTy, RTy);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002293 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
2294 RHS->isLvalue(Context) == Expr::LV_Valid)
2295 return LTy;
2296
2297 // C++0x 5.16p5
2298 // Otherwise, the result is an rvalue. If the second and third operands
2299 // do not have the same type, and either has (cv) class type, ...
2300 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2301 // ... overload resolution is used to determine the conversions (if any)
2302 // to be applied to the operands. If the overload resolution fails, the
2303 // program is ill-formed.
2304 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2305 return QualType();
2306 }
2307
2308 // C++0x 5.16p6
2309 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2310 // conversions are performed on the second and third operands.
Douglas Gregorb92a1562010-02-03 00:27:59 +00002311 DefaultFunctionArrayLvalueConversion(LHS);
2312 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002313 LTy = LHS->getType();
2314 RTy = RHS->getType();
2315
2316 // After those conversions, one of the following shall hold:
2317 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00002318 // is of that type. If the operands have class type, the result
2319 // is a prvalue temporary of the result type, which is
2320 // copy-initialized from either the second operand or the third
2321 // operand depending on the value of the first operand.
2322 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
2323 if (LTy->isRecordType()) {
2324 // The operands have class type. Make a temporary copy.
2325 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
2326 OwningExprResult LHSCopy = PerformCopyInitialization(Entity,
2327 SourceLocation(),
2328 Owned(LHS));
2329 if (LHSCopy.isInvalid())
2330 return QualType();
2331
2332 OwningExprResult RHSCopy = PerformCopyInitialization(Entity,
2333 SourceLocation(),
2334 Owned(RHS));
2335 if (RHSCopy.isInvalid())
2336 return QualType();
2337
2338 LHS = LHSCopy.takeAs<Expr>();
2339 RHS = RHSCopy.takeAs<Expr>();
2340 }
2341
Sebastian Redl1a99f442009-04-16 17:51:27 +00002342 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00002343 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00002344
Douglas Gregor46188682010-05-18 22:42:18 +00002345 // Extension: conditional operator involving vector types.
2346 if (LTy->isVectorType() || RTy->isVectorType())
2347 return CheckVectorOperands(QuestionLoc, LHS, RHS);
2348
Sebastian Redl1a99f442009-04-16 17:51:27 +00002349 // -- The second and third operands have arithmetic or enumeration type;
2350 // the usual arithmetic conversions are performed to bring them to a
2351 // common type, and the result is of that type.
2352 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2353 UsualArithmeticConversions(LHS, RHS);
2354 return LHS->getType();
2355 }
2356
2357 // -- The second and third operands have pointer type, or one has pointer
2358 // type and the other is a null pointer constant; pointer conversions
2359 // and qualification conversions are performed to bring them to their
2360 // composite pointer type. The result is of the composite pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00002361 // -- The second and third operands have pointer to member type, or one has
2362 // pointer to member type and the other is a null pointer constant;
2363 // pointer to member conversions and qualification conversions are
2364 // performed to bring them to a common type, whose cv-qualification
2365 // shall match the cv-qualification of either the second or the third
2366 // operand. The result is of the common type.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002367 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00002368 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002369 isSFINAEContext()? 0 : &NonStandardCompositeType);
2370 if (!Composite.isNull()) {
2371 if (NonStandardCompositeType)
2372 Diag(QuestionLoc,
2373 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2374 << LTy << RTy << Composite
2375 << LHS->getSourceRange() << RHS->getSourceRange();
2376
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002377 return Composite;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002378 }
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00002379
Douglas Gregor697a3912010-04-01 22:47:07 +00002380 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00002381 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2382 if (!Composite.isNull())
2383 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00002384
Sebastian Redl1a99f442009-04-16 17:51:27 +00002385 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2386 << LHS->getType() << RHS->getType()
2387 << LHS->getSourceRange() << RHS->getSourceRange();
2388 return QualType();
2389}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002390
2391/// \brief Find a merged pointer type and convert the two expressions to it.
2392///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002393/// This finds the composite pointer type (or member pointer type) for @p E1
2394/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2395/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002396/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002397///
Douglas Gregor19175ff2010-04-16 23:20:25 +00002398/// \param Loc The location of the operator requiring these two expressions to
2399/// be converted to the composite pointer type.
2400///
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002401/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2402/// a non-standard (but still sane) composite type to which both expressions
2403/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2404/// will be set true.
Douglas Gregor19175ff2010-04-16 23:20:25 +00002405QualType Sema::FindCompositePointerType(SourceLocation Loc,
2406 Expr *&E1, Expr *&E2,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002407 bool *NonStandardCompositeType) {
2408 if (NonStandardCompositeType)
2409 *NonStandardCompositeType = false;
2410
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002411 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2412 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002413
Fariborz Jahanian33e148f2009-12-08 20:04:24 +00002414 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2415 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002416 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002417
2418 // C++0x 5.9p2
2419 // Pointer conversions and qualification conversions are performed on
2420 // pointer operands to bring them to their composite pointer type. If
2421 // one operand is a null pointer constant, the composite pointer type is
2422 // the type of the other operand.
Douglas Gregor56751b52009-09-25 04:25:58 +00002423 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002424 if (T2->isMemberPointerType())
2425 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
2426 else
2427 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002428 return T2;
2429 }
Douglas Gregor56751b52009-09-25 04:25:58 +00002430 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002431 if (T1->isMemberPointerType())
2432 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
2433 else
2434 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002435 return T1;
2436 }
Mike Stump11289f42009-09-09 15:08:12 +00002437
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002438 // Now both have to be pointers or member pointers.
Sebastian Redl658262f2009-11-16 21:03:45 +00002439 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2440 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002441 return QualType();
2442
2443 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2444 // the other has type "pointer to cv2 T" and the composite pointer type is
2445 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2446 // Otherwise, the composite pointer type is a pointer type similar to the
2447 // type of one of the operands, with a cv-qualification signature that is
2448 // the union of the cv-qualification signatures of the operand types.
2449 // In practice, the first part here is redundant; it's subsumed by the second.
2450 // What we do here is, we build the two possible composite types, and try the
2451 // conversions in both directions. If only one works, or if the two composite
2452 // types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00002453 // FIXME: extended qualifiers?
Sebastian Redl658262f2009-11-16 21:03:45 +00002454 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2455 QualifierVector QualifierUnion;
2456 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2457 ContainingClassVector;
2458 ContainingClassVector MemberOfClass;
2459 QualType Composite1 = Context.getCanonicalType(T1),
2460 Composite2 = Context.getCanonicalType(T2);
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002461 unsigned NeedConstBefore = 0;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002462 do {
2463 const PointerType *Ptr1, *Ptr2;
2464 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2465 (Ptr2 = Composite2->getAs<PointerType>())) {
2466 Composite1 = Ptr1->getPointeeType();
2467 Composite2 = Ptr2->getPointeeType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002468
2469 // If we're allowed to create a non-standard composite type, keep track
2470 // of where we need to fill in additional 'const' qualifiers.
2471 if (NonStandardCompositeType &&
2472 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2473 NeedConstBefore = QualifierUnion.size();
2474
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002475 QualifierUnion.push_back(
2476 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2477 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2478 continue;
2479 }
Mike Stump11289f42009-09-09 15:08:12 +00002480
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002481 const MemberPointerType *MemPtr1, *MemPtr2;
2482 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2483 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2484 Composite1 = MemPtr1->getPointeeType();
2485 Composite2 = MemPtr2->getPointeeType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002486
2487 // If we're allowed to create a non-standard composite type, keep track
2488 // of where we need to fill in additional 'const' qualifiers.
2489 if (NonStandardCompositeType &&
2490 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2491 NeedConstBefore = QualifierUnion.size();
2492
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002493 QualifierUnion.push_back(
2494 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2495 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2496 MemPtr2->getClass()));
2497 continue;
2498 }
Mike Stump11289f42009-09-09 15:08:12 +00002499
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002500 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00002501
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002502 // Cannot unwrap any more types.
2503 break;
2504 } while (true);
Mike Stump11289f42009-09-09 15:08:12 +00002505
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002506 if (NeedConstBefore && NonStandardCompositeType) {
2507 // Extension: Add 'const' to qualifiers that come before the first qualifier
2508 // mismatch, so that our (non-standard!) composite type meets the
2509 // requirements of C++ [conv.qual]p4 bullet 3.
2510 for (unsigned I = 0; I != NeedConstBefore; ++I) {
2511 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
2512 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
2513 *NonStandardCompositeType = true;
2514 }
2515 }
2516 }
2517
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002518 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redl658262f2009-11-16 21:03:45 +00002519 ContainingClassVector::reverse_iterator MOC
2520 = MemberOfClass.rbegin();
2521 for (QualifierVector::reverse_iterator
2522 I = QualifierUnion.rbegin(),
2523 E = QualifierUnion.rend();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002524 I != E; (void)++I, ++MOC) {
John McCall8ccfcb52009-09-24 19:53:00 +00002525 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002526 if (MOC->first && MOC->second) {
2527 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00002528 Composite1 = Context.getMemberPointerType(
2529 Context.getQualifiedType(Composite1, Quals),
2530 MOC->first);
2531 Composite2 = Context.getMemberPointerType(
2532 Context.getQualifiedType(Composite2, Quals),
2533 MOC->second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002534 } else {
2535 // Rebuild pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00002536 Composite1
2537 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2538 Composite2
2539 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002540 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002541 }
2542
Douglas Gregor19175ff2010-04-16 23:20:25 +00002543 // Try to convert to the first composite pointer type.
2544 InitializedEntity Entity1
2545 = InitializedEntity::InitializeTemporary(Composite1);
2546 InitializationKind Kind
2547 = InitializationKind::CreateCopy(Loc, SourceLocation());
2548 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
2549 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump11289f42009-09-09 15:08:12 +00002550
Douglas Gregor19175ff2010-04-16 23:20:25 +00002551 if (E1ToC1 && E2ToC1) {
2552 // Conversion to Composite1 is viable.
2553 if (!Context.hasSameType(Composite1, Composite2)) {
2554 // Composite2 is a different type from Composite1. Check whether
2555 // Composite2 is also viable.
2556 InitializedEntity Entity2
2557 = InitializedEntity::InitializeTemporary(Composite2);
2558 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2559 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2560 if (E1ToC2 && E2ToC2) {
2561 // Both Composite1 and Composite2 are viable and are different;
2562 // this is an ambiguity.
2563 return QualType();
2564 }
2565 }
2566
2567 // Convert E1 to Composite1
2568 OwningExprResult E1Result
2569 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E1,1));
2570 if (E1Result.isInvalid())
2571 return QualType();
2572 E1 = E1Result.takeAs<Expr>();
2573
2574 // Convert E2 to Composite1
2575 OwningExprResult E2Result
2576 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E2,1));
2577 if (E2Result.isInvalid())
2578 return QualType();
2579 E2 = E2Result.takeAs<Expr>();
2580
2581 return Composite1;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002582 }
2583
Douglas Gregor19175ff2010-04-16 23:20:25 +00002584 // Check whether Composite2 is viable.
2585 InitializedEntity Entity2
2586 = InitializedEntity::InitializeTemporary(Composite2);
2587 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2588 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2589 if (!E1ToC2 || !E2ToC2)
2590 return QualType();
2591
2592 // Convert E1 to Composite2
2593 OwningExprResult E1Result
2594 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E1, 1));
2595 if (E1Result.isInvalid())
2596 return QualType();
2597 E1 = E1Result.takeAs<Expr>();
2598
2599 // Convert E2 to Composite2
2600 OwningExprResult E2Result
2601 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E2, 1));
2602 if (E2Result.isInvalid())
2603 return QualType();
2604 E2 = E2Result.takeAs<Expr>();
2605
2606 return Composite2;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002607}
Anders Carlsson85a307d2009-05-17 18:41:29 +00002608
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002609Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlssonf86a8d12009-08-15 23:41:35 +00002610 if (!Context.getLangOptions().CPlusPlus)
2611 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00002612
Douglas Gregor363b1512009-12-24 18:51:59 +00002613 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2614
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002615 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002616 if (!RT)
2617 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00002618
Anders Carlssonbb4cfdf2010-07-16 21:18:37 +00002619 // If this is the result of a call or an Objective-C message send expression,
2620 // our source might actually be a reference, in which case we shouldn't bind.
Anders Carlssonaedb46f2009-09-14 01:30:44 +00002621 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
Anders Carlssonbb4cfdf2010-07-16 21:18:37 +00002622 if (CE->getCallReturnType()->isReferenceType())
Anders Carlssonaedb46f2009-09-14 01:30:44 +00002623 return Owned(E);
Anders Carlssonbb4cfdf2010-07-16 21:18:37 +00002624 } else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
2625 if (const ObjCMethodDecl *MD = ME->getMethodDecl()) {
2626 if (MD->getResultType()->isReferenceType())
2627 return Owned(E);
2628 }
Anders Carlssonaedb46f2009-09-14 01:30:44 +00002629 }
John McCall67da35c2010-02-04 22:26:26 +00002630
2631 // That should be enough to guarantee that this type is complete.
2632 // If it has a trivial destructor, we can avoid the extra copy.
2633 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCallbdb989e2010-08-12 02:40:37 +00002634 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall67da35c2010-02-04 22:26:26 +00002635 return Owned(E);
2636
Douglas Gregore71edda2010-07-01 22:47:18 +00002637 CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD));
Anders Carlssonc78576e2009-05-30 21:21:49 +00002638 ExprTemporaries.push_back(Temp);
Douglas Gregore71edda2010-07-01 22:47:18 +00002639 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Fariborz Jahanian67828442009-08-03 19:13:25 +00002640 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00002641 CheckDestructorAccess(E->getExprLoc(), Destructor,
2642 PDiag(diag::err_access_dtor_temp)
2643 << E->getType());
2644 }
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002645 // FIXME: Add the temporary to the temporaries vector.
2646 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2647}
2648
Anders Carlsson6e997b22009-12-15 20:51:39 +00002649Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002650 assert(SubExpr && "sub expression can't be null!");
Mike Stump11289f42009-09-09 15:08:12 +00002651
John McCallcc7e5bf2010-05-06 08:58:33 +00002652 // Check any implicit conversions within the expression.
2653 CheckImplicitConversions(SubExpr);
2654
Douglas Gregor580cd4a2009-12-03 17:10:37 +00002655 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2656 assert(ExprTemporaries.size() >= FirstTemporary);
2657 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002658 return SubExpr;
Mike Stump11289f42009-09-09 15:08:12 +00002659
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002660 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor580cd4a2009-12-03 17:10:37 +00002661 &ExprTemporaries[FirstTemporary],
Anders Carlsson6e997b22009-12-15 20:51:39 +00002662 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor580cd4a2009-12-03 17:10:37 +00002663 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2664 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00002665
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002666 return E;
2667}
2668
Douglas Gregorb6ea6082009-12-22 22:17:25 +00002669Sema::OwningExprResult
2670Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2671 if (SubExpr.isInvalid())
2672 return ExprError();
2673
2674 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2675}
2676
Anders Carlssonafb2dad2009-12-16 02:09:40 +00002677FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2678 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2679 assert(ExprTemporaries.size() >= FirstTemporary);
2680
2681 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2682 CXXTemporary **Temporaries =
2683 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2684
2685 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2686
2687 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2688 ExprTemporaries.end());
2689
2690 return E;
2691}
2692
Mike Stump11289f42009-09-09 15:08:12 +00002693Sema::OwningExprResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002694Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
Douglas Gregore610ada2010-02-24 18:44:31 +00002695 tok::TokenKind OpKind, TypeTy *&ObjectType,
2696 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002697 // Since this might be a postfix expression, get rid of ParenListExprs.
2698 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump11289f42009-09-09 15:08:12 +00002699
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002700 Expr *BaseExpr = (Expr*)Base.get();
2701 assert(BaseExpr && "no record expansion");
Mike Stump11289f42009-09-09 15:08:12 +00002702
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002703 QualType BaseType = BaseExpr->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00002704 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002705 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00002706 // If we have a pointer to a dependent type and are using the -> operator,
2707 // the object type is the type that the pointer points to. We might still
2708 // have enough information about that type to do something useful.
2709 if (OpKind == tok::arrow)
2710 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2711 BaseType = Ptr->getPointeeType();
2712
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002713 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregore610ada2010-02-24 18:44:31 +00002714 MayBePseudoDestructor = true;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002715 return move(Base);
2716 }
Mike Stump11289f42009-09-09 15:08:12 +00002717
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002718 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00002719 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002720 // returned, with the original second operand.
2721 if (OpKind == tok::arrow) {
John McCallc1538c02009-09-30 01:01:30 +00002722 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00002723 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002724 llvm::SmallVector<SourceLocation, 8> Locations;
John McCallbd0465b2009-09-30 01:30:54 +00002725 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc1538c02009-09-30 01:01:30 +00002726
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002727 while (BaseType->isRecordType()) {
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00002728 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002729 BaseExpr = (Expr*)Base.get();
2730 if (BaseExpr == NULL)
2731 return ExprError();
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002732 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonfbd2d492009-10-13 22:55:59 +00002733 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc1538c02009-09-30 01:01:30 +00002734 BaseType = BaseExpr->getType();
2735 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCallbd0465b2009-09-30 01:30:54 +00002736 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00002737 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002738 for (unsigned i = 0; i < Locations.size(); i++)
2739 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00002740 return ExprError();
2741 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002742 }
Mike Stump11289f42009-09-09 15:08:12 +00002743
Douglas Gregore4f764f2009-11-20 19:58:21 +00002744 if (BaseType->isPointerType())
2745 BaseType = BaseType->getPointeeType();
2746 }
Mike Stump11289f42009-09-09 15:08:12 +00002747
2748 // We could end up with various non-record types here, such as extended
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002749 // vector types or Objective-C interfaces. Just return early and let
2750 // ActOnMemberReferenceExpr do the work.
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002751 if (!BaseType->isRecordType()) {
2752 // C++ [basic.lookup.classref]p2:
2753 // [...] If the type of the object expression is of pointer to scalar
2754 // type, the unqualified-id is looked up in the context of the complete
2755 // postfix-expression.
Douglas Gregore610ada2010-02-24 18:44:31 +00002756 //
2757 // This also indicates that we should be parsing a
2758 // pseudo-destructor-name.
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002759 ObjectType = 0;
Douglas Gregore610ada2010-02-24 18:44:31 +00002760 MayBePseudoDestructor = true;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002761 return move(Base);
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002762 }
Mike Stump11289f42009-09-09 15:08:12 +00002763
Douglas Gregor3fad6172009-11-17 05:17:33 +00002764 // The object type must be complete (or dependent).
2765 if (!BaseType->isDependentType() &&
2766 RequireCompleteType(OpLoc, BaseType,
2767 PDiag(diag::err_incomplete_member_access)))
2768 return ExprError();
2769
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002770 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002771 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00002772 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002773 // type C (or of pointer to a class type C), the unqualified-id is looked
2774 // up in the scope of class C. [...]
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002775 ObjectType = BaseType.getAsOpaquePtr();
Mike Stump11289f42009-09-09 15:08:12 +00002776 return move(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002777}
2778
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002779Sema::OwningExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
2780 ExprArg MemExpr) {
2781 Expr *E = (Expr *) MemExpr.get();
2782 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
2783 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2784 << isa<CXXPseudoDestructorExpr>(E)
Douglas Gregora771f462010-03-31 17:46:05 +00002785 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002786
2787 return ActOnCallExpr(/*Scope*/ 0,
2788 move(MemExpr),
2789 /*LPLoc*/ ExpectedLParenLoc,
2790 Sema::MultiExprArg(*this, 0, 0),
2791 /*CommaLocs*/ 0,
2792 /*RPLoc*/ ExpectedLParenLoc);
2793}
Douglas Gregore610ada2010-02-24 18:44:31 +00002794
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002795Sema::OwningExprResult Sema::BuildPseudoDestructorExpr(ExprArg Base,
2796 SourceLocation OpLoc,
2797 tok::TokenKind OpKind,
2798 const CXXScopeSpec &SS,
Douglas Gregor651fe5e2010-02-24 23:40:28 +00002799 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002800 SourceLocation CCLoc,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00002801 SourceLocation TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002802 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002803 bool HasTrailingLParen) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00002804 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002805
2806 // C++ [expr.pseudo]p2:
2807 // The left-hand side of the dot operator shall be of scalar type. The
2808 // left-hand side of the arrow operator shall be of pointer to scalar type.
2809 // This scalar type is the object type.
2810 Expr *BaseE = (Expr *)Base.get();
2811 QualType ObjectType = BaseE->getType();
2812 if (OpKind == tok::arrow) {
2813 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2814 ObjectType = Ptr->getPointeeType();
2815 } else if (!BaseE->isTypeDependent()) {
2816 // The user wrote "p->" when she probably meant "p."; fix it.
2817 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2818 << ObjectType << true
Douglas Gregora771f462010-03-31 17:46:05 +00002819 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002820 if (isSFINAEContext())
2821 return ExprError();
2822
2823 OpKind = tok::period;
2824 }
2825 }
2826
2827 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
2828 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2829 << ObjectType << BaseE->getSourceRange();
2830 return ExprError();
2831 }
2832
2833 // C++ [expr.pseudo]p2:
2834 // [...] The cv-unqualified versions of the object type and of the type
2835 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00002836 if (DestructedTypeInfo) {
2837 QualType DestructedType = DestructedTypeInfo->getType();
2838 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002839 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
Douglas Gregor678f90d2010-02-25 01:56:36 +00002840 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
2841 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
2842 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
2843 << ObjectType << DestructedType << BaseE->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002844 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor678f90d2010-02-25 01:56:36 +00002845
2846 // Recover by setting the destructed type to the object type.
2847 DestructedType = ObjectType;
2848 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
2849 DestructedTypeStart);
2850 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2851 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002852 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00002853
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002854 // C++ [expr.pseudo]p2:
2855 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
2856 // form
2857 //
2858 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
2859 //
2860 // shall designate the same scalar type.
2861 if (ScopeTypeInfo) {
2862 QualType ScopeType = ScopeTypeInfo->getType();
2863 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00002864 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002865
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002866 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002867 diag::err_pseudo_dtor_type_mismatch)
2868 << ObjectType << ScopeType << BaseE->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002869 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002870
2871 ScopeType = QualType();
2872 ScopeTypeInfo = 0;
2873 }
2874 }
2875
2876 OwningExprResult Result
2877 = Owned(new (Context) CXXPseudoDestructorExpr(Context,
2878 Base.takeAs<Expr>(),
2879 OpKind == tok::arrow,
2880 OpLoc,
2881 (NestedNameSpecifier *) SS.getScopeRep(),
2882 SS.getRange(),
2883 ScopeTypeInfo,
2884 CCLoc,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00002885 TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002886 Destructed));
2887
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002888 if (HasTrailingLParen)
2889 return move(Result);
2890
Douglas Gregor678f90d2010-02-25 01:56:36 +00002891 return DiagnoseDtorReference(Destructed.getLocation(), move(Result));
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002892}
2893
2894Sema::OwningExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, ExprArg Base,
2895 SourceLocation OpLoc,
2896 tok::TokenKind OpKind,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002897 CXXScopeSpec &SS,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002898 UnqualifiedId &FirstTypeName,
2899 SourceLocation CCLoc,
2900 SourceLocation TildeLoc,
2901 UnqualifiedId &SecondTypeName,
2902 bool HasTrailingLParen) {
2903 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2904 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2905 "Invalid first type name in pseudo-destructor");
2906 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2907 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2908 "Invalid second type name in pseudo-destructor");
2909
2910 Expr *BaseE = (Expr *)Base.get();
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002911
2912 // C++ [expr.pseudo]p2:
2913 // The left-hand side of the dot operator shall be of scalar type. The
2914 // left-hand side of the arrow operator shall be of pointer to scalar type.
2915 // This scalar type is the object type.
2916 QualType ObjectType = BaseE->getType();
2917 if (OpKind == tok::arrow) {
2918 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2919 ObjectType = Ptr->getPointeeType();
Douglas Gregor678f90d2010-02-25 01:56:36 +00002920 } else if (!ObjectType->isDependentType()) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002921 // The user wrote "p->" when she probably meant "p."; fix it.
2922 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregor678f90d2010-02-25 01:56:36 +00002923 << ObjectType << true
Douglas Gregora771f462010-03-31 17:46:05 +00002924 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002925 if (isSFINAEContext())
2926 return ExprError();
2927
2928 OpKind = tok::period;
2929 }
2930 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00002931
2932 // Compute the object type that we should use for name lookup purposes. Only
2933 // record types and dependent types matter.
2934 void *ObjectTypePtrForLookup = 0;
2935 if (!SS.isSet()) {
Gabor Greif2cd6c7b2010-06-17 11:29:31 +00002936 ObjectTypePtrForLookup = const_cast<RecordType*>(
2937 ObjectType->getAs<RecordType>());
Douglas Gregor678f90d2010-02-25 01:56:36 +00002938 if (!ObjectTypePtrForLookup && ObjectType->isDependentType())
2939 ObjectTypePtrForLookup = Context.DependentTy.getAsOpaquePtr();
2940 }
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002941
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002942 // Convert the name of the type being destructed (following the ~) into a
2943 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002944 QualType DestructedType;
2945 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregor678f90d2010-02-25 01:56:36 +00002946 PseudoDestructorTypeStorage Destructed;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002947 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2948 TypeTy *T = getTypeName(*SecondTypeName.Identifier,
2949 SecondTypeName.StartLocation,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002950 S, &SS, true, ObjectTypePtrForLookup);
2951 if (!T &&
2952 ((SS.isSet() && !computeDeclContext(SS, false)) ||
2953 (!SS.isSet() && ObjectType->isDependentType()))) {
2954 // The name of the type being destroyed is a dependent name, and we
2955 // couldn't find anything useful in scope. Just store the identifier and
2956 // it's location, and we'll perform (qualified) name lookup again at
2957 // template instantiation time.
2958 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
2959 SecondTypeName.StartLocation);
2960 } else if (!T) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002961 Diag(SecondTypeName.StartLocation,
2962 diag::err_pseudo_dtor_destructor_non_type)
2963 << SecondTypeName.Identifier << ObjectType;
2964 if (isSFINAEContext())
2965 return ExprError();
2966
2967 // Recover by assuming we had the right type all along.
2968 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002969 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002970 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002971 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002972 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002973 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002974 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2975 TemplateId->getTemplateArgs(),
2976 TemplateId->NumArgs);
2977 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2978 TemplateId->TemplateNameLoc,
2979 TemplateId->LAngleLoc,
2980 TemplateArgsPtr,
2981 TemplateId->RAngleLoc);
2982 if (T.isInvalid() || !T.get()) {
2983 // Recover by assuming we had the right type all along.
2984 DestructedType = ObjectType;
2985 } else
2986 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002987 }
2988
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002989 // If we've performed some kind of recovery, (re-)build the type source
2990 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00002991 if (!DestructedType.isNull()) {
2992 if (!DestructedTypeInfo)
2993 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002994 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00002995 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2996 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002997
2998 // Convert the name of the scope type (the type prior to '::') into a type.
2999 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003000 QualType ScopeType;
3001 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3002 FirstTypeName.Identifier) {
3003 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
3004 TypeTy *T = getTypeName(*FirstTypeName.Identifier,
3005 FirstTypeName.StartLocation,
Douglas Gregor678f90d2010-02-25 01:56:36 +00003006 S, &SS, false, ObjectTypePtrForLookup);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003007 if (!T) {
3008 Diag(FirstTypeName.StartLocation,
3009 diag::err_pseudo_dtor_destructor_non_type)
3010 << FirstTypeName.Identifier << ObjectType;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003011
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003012 if (isSFINAEContext())
3013 return ExprError();
3014
3015 // Just drop this type. It's unnecessary anyway.
3016 ScopeType = QualType();
3017 } else
3018 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003019 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003020 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003021 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003022 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3023 TemplateId->getTemplateArgs(),
3024 TemplateId->NumArgs);
3025 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
3026 TemplateId->TemplateNameLoc,
3027 TemplateId->LAngleLoc,
3028 TemplateArgsPtr,
3029 TemplateId->RAngleLoc);
3030 if (T.isInvalid() || !T.get()) {
3031 // Recover by dropping this type.
3032 ScopeType = QualType();
3033 } else
3034 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003035 }
3036 }
Douglas Gregor90ad9222010-02-24 23:02:30 +00003037
3038 if (!ScopeType.isNull() && !ScopeTypeInfo)
3039 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
3040 FirstTypeName.StartLocation);
3041
3042
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003043 return BuildPseudoDestructorExpr(move(Base), OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00003044 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00003045 Destructed, HasTrailingLParen);
Douglas Gregore610ada2010-02-24 18:44:31 +00003046}
3047
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00003048CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
John McCall16df1e52010-03-30 21:47:33 +00003049 NamedDecl *FoundDecl,
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00003050 CXXMethodDecl *Method) {
John McCall16df1e52010-03-30 21:47:33 +00003051 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
3052 FoundDecl, Method))
Eli Friedmanf7195532009-12-09 04:53:56 +00003053 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
3054
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00003055 MemberExpr *ME =
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003056 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00003057 SourceLocation(), Method->getType());
Douglas Gregor603d81b2010-07-13 08:18:22 +00003058 QualType ResultType = Method->getCallResultType();
Douglas Gregor27381f32009-11-23 12:27:39 +00003059 MarkDeclarationReferenced(Exp->getLocStart(), Method);
3060 CXXMemberCallExpr *CE =
3061 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
3062 Exp->getLocEnd());
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00003063 return CE;
3064}
3065
Anders Carlsson85a307d2009-05-17 18:41:29 +00003066Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
3067 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlssonb3d05d62009-06-05 15:38:08 +00003068 if (FullExpr)
Anders Carlsson6e997b22009-12-15 20:51:39 +00003069 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00003070 else
3071 return ExprError();
3072
Anders Carlsson85a307d2009-05-17 18:41:29 +00003073 return Owned(FullExpr);
3074}