blob: 3c64584bfcea20bb6b956f699c2321e7ecea833a [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000015#include "SemaInit.h"
John McCall7d384dd2009-11-18 07:57:50 +000016#include "Lookup.h"
Steve Naroff210679c2007-08-25 14:02:58 +000017#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000019#include "clang/AST/ExprCXX.h"
Fariborz Jahaniand4266622010-06-16 18:56:04 +000020#include "clang/AST/ExprObjC.h"
Douglas Gregorb57fb492010-02-24 22:38:50 +000021#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000022#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000023#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000024#include "clang/Lex/Preprocessor.h"
25#include "clang/Parse/DeclSpec.h"
Douglas Gregord4dca082010-02-24 18:44:31 +000026#include "clang/Parse/Template.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000027#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000028using namespace clang;
29
Douglas Gregor124b8782010-02-16 19:09:40 +000030Action::TypeTy *Sema::getDestructorName(SourceLocation TildeLoc,
31 IdentifierInfo &II,
32 SourceLocation NameLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +000033 Scope *S, CXXScopeSpec &SS,
Douglas Gregor124b8782010-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 Gregor93649fd2010-02-23 00:15:22 +000055 // See also PR6358 and PR6359.
Douglas Gregor124b8782010-02-16 19:09:40 +000056 QualType SearchType;
57 DeclContext *LookupCtx = 0;
58 bool isDependent = false;
59 bool LookInScope = false;
60
61 // If we have an object type, it's because we are in a
62 // pseudo-destructor-expression or a member access expression, and
63 // we know what type we're looking for.
64 if (ObjectTypePtr)
65 SearchType = GetTypeFromParser(ObjectTypePtr);
66
67 if (SS.isSet()) {
Douglas Gregor93649fd2010-02-23 00:15:22 +000068 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
69
70 bool AlreadySearched = false;
71 bool LookAtPrefix = true;
72 if (!getLangOptions().CPlusPlus0x) {
73 // C++ [basic.lookup.qual]p6:
74 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
75 // the type-names are looked up as types in the scope designated by the
76 // nested-name-specifier. In a qualified-id of the form:
77 //
78 // ::[opt] nested-name-specifier ̃ class-name
79 //
80 // where the nested-name-specifier designates a namespace scope, and in
81 // a qualified-id of the form:
82 //
83 // ::opt nested-name-specifier class-name :: ̃ class-name
84 //
85 // the class-names are looked up as types in the scope designated by
86 // the nested-name-specifier.
87 //
88 // Here, we check the first case (completely) and determine whether the
89 // code below is permitted to look at the prefix of the
90 // nested-name-specifier (as we do in C++0x).
91 DeclContext *DC = computeDeclContext(SS, EnteringContext);
92 if (DC && DC->isFileContext()) {
93 AlreadySearched = true;
94 LookupCtx = DC;
95 isDependent = false;
96 } else if (DC && isa<CXXRecordDecl>(DC))
97 LookAtPrefix = false;
98 }
99
100 // C++0x [basic.lookup.qual]p6:
Douglas Gregor124b8782010-02-16 19:09:40 +0000101 // If a pseudo-destructor-name (5.2.4) contains a
102 // nested-name-specifier, the type-names are looked up as types
103 // in the scope designated by the nested-name-specifier. Similarly, in
Chandler Carruth5e895a82010-02-21 10:19:54 +0000104 // a qualified-id of the form:
Douglas Gregor124b8782010-02-16 19:09:40 +0000105 //
106 // :: [opt] nested-name-specifier[opt] class-name :: ~class-name
107 //
108 // the second class-name is looked up in the same scope as the first.
109 //
Douglas Gregor93649fd2010-02-23 00:15:22 +0000110 // To implement this, we look at the prefix of the
111 // nested-name-specifier we were given, and determine the lookup
112 // context from that.
113 //
114 // We also fold in the second case from the C++03 rules quoted further
115 // above.
116 NestedNameSpecifier *Prefix = 0;
117 if (AlreadySearched) {
118 // Nothing left to do.
119 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
120 CXXScopeSpec PrefixSS;
121 PrefixSS.setScopeRep(Prefix);
122 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
123 isDependent = isDependentScopeSpecifier(PrefixSS);
124 } else if (getLangOptions().CPlusPlus0x &&
125 (LookupCtx = computeDeclContext(SS, EnteringContext))) {
126 if (!LookupCtx->isTranslationUnit())
127 LookupCtx = LookupCtx->getParent();
128 isDependent = LookupCtx && LookupCtx->isDependentContext();
129 } else if (ObjectTypePtr) {
Douglas Gregor124b8782010-02-16 19:09:40 +0000130 LookupCtx = computeDeclContext(SearchType);
131 isDependent = SearchType->isDependentType();
132 } else {
133 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000134 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregor124b8782010-02-16 19:09:40 +0000135 }
Douglas Gregor93649fd2010-02-23 00:15:22 +0000136
Douglas Gregoredc90502010-02-25 04:46:04 +0000137 LookInScope = false;
Douglas Gregor124b8782010-02-16 19:09:40 +0000138 } else if (ObjectTypePtr) {
139 // C++ [basic.lookup.classref]p3:
140 // If the unqualified-id is ~type-name, the type-name is looked up
141 // in the context of the entire postfix-expression. If the type T
142 // of the object expression is of a class type C, the type-name is
143 // also looked up in the scope of class C. At least one of the
144 // lookups shall find a name that refers to (possibly
145 // cv-qualified) T.
146 LookupCtx = computeDeclContext(SearchType);
147 isDependent = SearchType->isDependentType();
148 assert((isDependent || !SearchType->isIncompleteType()) &&
149 "Caller should have completed object type");
150
151 LookInScope = true;
152 } else {
153 // Perform lookup into the current scope (only).
154 LookInScope = true;
155 }
156
157 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
158 for (unsigned Step = 0; Step != 2; ++Step) {
159 // Look for the name first in the computed lookup context (if we
160 // have one) and, if that fails to find a match, in the sope (if
161 // we're allowed to look there).
162 Found.clear();
163 if (Step == 0 && LookupCtx)
164 LookupQualifiedName(Found, LookupCtx);
Douglas Gregora2e7dd22010-02-25 01:56:36 +0000165 else if (Step == 1 && LookInScope && S)
Douglas Gregor124b8782010-02-16 19:09:40 +0000166 LookupName(Found, S);
167 else
168 continue;
169
170 // FIXME: Should we be suppressing ambiguities here?
171 if (Found.isAmbiguous())
172 return 0;
173
174 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
175 QualType T = Context.getTypeDeclType(Type);
Douglas Gregor124b8782010-02-16 19:09:40 +0000176
177 if (SearchType.isNull() || SearchType->isDependentType() ||
178 Context.hasSameUnqualifiedType(T, SearchType)) {
179 // We found our type!
180
181 return T.getAsOpaquePtr();
182 }
183 }
184
185 // If the name that we found is a class template name, and it is
186 // the same name as the template name in the last part of the
187 // nested-name-specifier (if present) or the object type, then
188 // this is the destructor for that class.
189 // FIXME: This is a workaround until we get real drafting for core
190 // issue 399, for which there isn't even an obvious direction.
191 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
192 QualType MemberOfType;
193 if (SS.isSet()) {
194 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
195 // Figure out the type of the context, if it has one.
John McCall3cb0ebd2010-03-10 03:28:59 +0000196 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
197 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregor124b8782010-02-16 19:09:40 +0000198 }
199 }
200 if (MemberOfType.isNull())
201 MemberOfType = SearchType;
202
203 if (MemberOfType.isNull())
204 continue;
205
206 // We're referring into a class template specialization. If the
207 // class template we found is the same as the template being
208 // specialized, we found what we are looking for.
209 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
210 if (ClassTemplateSpecializationDecl *Spec
211 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
212 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
213 Template->getCanonicalDecl())
214 return MemberOfType.getAsOpaquePtr();
215 }
216
217 continue;
218 }
219
220 // We're referring to an unresolved class template
221 // specialization. Determine whether we class template we found
222 // is the same as the template being specialized or, if we don't
223 // know which template is being specialized, that it at least
224 // has the same name.
225 if (const TemplateSpecializationType *SpecType
226 = MemberOfType->getAs<TemplateSpecializationType>()) {
227 TemplateName SpecName = SpecType->getTemplateName();
228
229 // The class template we found is the same template being
230 // specialized.
231 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
232 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
233 return MemberOfType.getAsOpaquePtr();
234
235 continue;
236 }
237
238 // The class template we found has the same name as the
239 // (dependent) template name being specialized.
240 if (DependentTemplateName *DepTemplate
241 = SpecName.getAsDependentTemplateName()) {
242 if (DepTemplate->isIdentifier() &&
243 DepTemplate->getIdentifier() == Template->getIdentifier())
244 return MemberOfType.getAsOpaquePtr();
245
246 continue;
247 }
248 }
249 }
250 }
251
252 if (isDependent) {
253 // We didn't find our type, but that's okay: it's dependent
254 // anyway.
255 NestedNameSpecifier *NNS = 0;
256 SourceRange Range;
257 if (SS.isSet()) {
258 NNS = (NestedNameSpecifier *)SS.getScopeRep();
259 Range = SourceRange(SS.getRange().getBegin(), NameLoc);
260 } else {
261 NNS = NestedNameSpecifier::Create(Context, &II);
262 Range = SourceRange(NameLoc);
263 }
264
Abramo Bagnarae4da7a02010-05-19 21:37:53 +0000265 return CheckTypenameType(ETK_None, NNS, II, SourceLocation(),
266 Range, NameLoc).getAsOpaquePtr();
Douglas Gregor124b8782010-02-16 19:09:40 +0000267 }
268
269 if (ObjectTypePtr)
270 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
271 << &II;
272 else
273 Diag(NameLoc, diag::err_destructor_class_name);
274
275 return 0;
276}
277
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000278/// \brief Build a C++ typeid expression with a type operand.
279Sema::OwningExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
280 SourceLocation TypeidLoc,
281 TypeSourceInfo *Operand,
282 SourceLocation RParenLoc) {
283 // C++ [expr.typeid]p4:
284 // The top-level cv-qualifiers of the lvalue expression or the type-id
285 // that is the operand of typeid are always ignored.
286 // If the type of the type-id is a class type or a reference to a class
287 // type, the class shall be completely-defined.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000288 Qualifiers Quals;
289 QualType T
290 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
291 Quals);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000292 if (T->getAs<RecordType>() &&
293 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
294 return ExprError();
Daniel Dunbar380c2132010-05-11 21:32:35 +0000295
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000296 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
297 Operand,
298 SourceRange(TypeidLoc, RParenLoc)));
299}
300
301/// \brief Build a C++ typeid expression with an expression operand.
302Sema::OwningExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
303 SourceLocation TypeidLoc,
304 ExprArg Operand,
305 SourceLocation RParenLoc) {
306 bool isUnevaluatedOperand = true;
307 Expr *E = static_cast<Expr *>(Operand.get());
308 if (E && !E->isTypeDependent()) {
309 QualType T = E->getType();
310 if (const RecordType *RecordT = T->getAs<RecordType>()) {
311 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
312 // C++ [expr.typeid]p3:
313 // [...] If the type of the expression is a class type, the class
314 // shall be completely-defined.
315 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
316 return ExprError();
317
318 // C++ [expr.typeid]p3:
319 // When typeid is applied to an expression other than an lvalue of a
320 // polymorphic class type [...] [the] expression is an unevaluated
321 // operand. [...]
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000322 if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000323 isUnevaluatedOperand = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000324
325 // We require a vtable to query the type at run time.
326 MarkVTableUsed(TypeidLoc, RecordD);
327 }
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000328 }
329
330 // C++ [expr.typeid]p4:
331 // [...] If the type of the type-id is a reference to a possibly
332 // cv-qualified type, the result of the typeid expression refers to a
333 // std::type_info object representing the cv-unqualified referenced
334 // type.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000335 Qualifiers Quals;
336 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
337 if (!Context.hasSameType(T, UnqualT)) {
338 T = UnqualT;
339 ImpCastExprToType(E, UnqualT, CastExpr::CK_NoOp, E->isLvalue(Context));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000340 Operand.release();
341 Operand = Owned(E);
342 }
343 }
344
345 // If this is an unevaluated operand, clear out the set of
346 // declaration references we have been computing and eliminate any
347 // temporaries introduced in its computation.
348 if (isUnevaluatedOperand)
349 ExprEvalContexts.back().Context = Unevaluated;
350
351 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
352 Operand.takeAs<Expr>(),
353 SourceRange(TypeidLoc, RParenLoc)));
354}
355
356/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000357Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000358Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
359 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000360 // Find the std::type_info type.
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000361 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000362 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000363
Chris Lattner572af492008-11-20 05:51:55 +0000364 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCalla24dc2e2009-11-17 02:14:36 +0000365 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
366 LookupQualifiedName(R, StdNamespace);
John McCall1bcee0a2009-12-02 08:25:40 +0000367 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
Chris Lattner572af492008-11-20 05:51:55 +0000368 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000369 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000370
Sebastian Redlc42e1182008-11-11 11:37:55 +0000371 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000372
373 if (isType) {
374 // The operand is a type; handle it as such.
375 TypeSourceInfo *TInfo = 0;
376 QualType T = GetTypeFromParser(TyOrExpr, &TInfo);
377 if (T.isNull())
378 return ExprError();
379
380 if (!TInfo)
381 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000382
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000383 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000384 }
Mike Stump1eb44332009-09-09 15:08:12 +0000385
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000386 // The operand is an expression.
387 return BuildCXXTypeId(TypeInfoType, OpLoc, Owned((Expr*)TyOrExpr), RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000388}
389
Steve Naroff1b273c42007-09-16 14:56:35 +0000390/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000391Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000392Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000393 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000394 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000395 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
396 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000397}
Chris Lattner50dd2892008-02-26 00:51:44 +0000398
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000399/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
400Action::OwningExprResult
401Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
402 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
403}
404
Chris Lattner50dd2892008-02-26 00:51:44 +0000405/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000406Action::OwningExprResult
407Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000408 Expr *Ex = E.takeAs<Expr>();
409 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
410 return ExprError();
411 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
412}
413
414/// CheckCXXThrowOperand - Validate the operand of a throw.
415bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
416 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000417 // A throw-expression initializes a temporary object, called the exception
418 // object, the type of which is determined by removing any top-level
419 // cv-qualifiers from the static type of the operand of throw and adjusting
420 // the type from "array of T" or "function returning T" to "pointer to T"
421 // or "pointer to function returning T", [...]
422 if (E->getType().hasQualifiers())
423 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp,
424 E->isLvalue(Context) == Expr::LV_Valid);
425
Sebastian Redl972041f2009-04-27 20:27:31 +0000426 DefaultFunctionArrayConversion(E);
427
428 // If the type of the exception would be an incomplete type or a pointer
429 // to an incomplete type other than (cv) void the program is ill-formed.
430 QualType Ty = E->getType();
John McCallac418162010-04-22 01:10:34 +0000431 bool isPointer = false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000432 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000433 Ty = Ptr->getPointeeType();
John McCallac418162010-04-22 01:10:34 +0000434 isPointer = true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000435 }
436 if (!isPointer || !Ty->isVoidType()) {
437 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000438 PDiag(isPointer ? diag::err_throw_incomplete_ptr
439 : diag::err_throw_incomplete)
440 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000441 return true;
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000442
Douglas Gregorbf422f92010-04-15 18:05:39 +0000443 if (RequireNonAbstractType(ThrowLoc, E->getType(),
444 PDiag(diag::err_throw_abstract_type)
445 << E->getSourceRange()))
446 return true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000447 }
448
John McCallac418162010-04-22 01:10:34 +0000449 // Initialize the exception result. This implicitly weeds out
450 // abstract types or types with inaccessible copy constructors.
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000451 // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p34.
John McCallac418162010-04-22 01:10:34 +0000452 InitializedEntity Entity =
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000453 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
454 /*NRVO=*/false);
John McCallac418162010-04-22 01:10:34 +0000455 OwningExprResult Res = PerformCopyInitialization(Entity,
456 SourceLocation(),
457 Owned(E));
458 if (Res.isInvalid())
459 return true;
460 E = Res.takeAs<Expr>();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000461
Eli Friedman5ed9b932010-06-03 20:39:03 +0000462 // If the exception has class type, we need additional handling.
463 const RecordType *RecordTy = Ty->getAs<RecordType>();
464 if (!RecordTy)
465 return false;
466 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
467
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000468 // If we are throwing a polymorphic class type or pointer thereof,
469 // exception handling will make use of the vtable.
Eli Friedman5ed9b932010-06-03 20:39:03 +0000470 MarkVTableUsed(ThrowLoc, RD);
471
472 // If the class has a non-trivial destructor, we must be able to call it.
473 if (RD->hasTrivialDestructor())
474 return false;
475
476 CXXDestructorDecl *Destructor =
477 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context));
478 if (!Destructor)
479 return false;
480
481 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
482 CheckDestructorAccess(E->getExprLoc(), Destructor,
483 PDiag(diag::err_access_dtor_temp) << Ty);
Sebastian Redl972041f2009-04-27 20:27:31 +0000484 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000485}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000486
Sebastian Redlf53597f2009-03-15 17:47:39 +0000487Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000488 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
489 /// is a non-lvalue expression whose value is the address of the object for
490 /// which the function is called.
491
John McCallea1471e2010-05-20 01:18:31 +0000492 DeclContext *DC = getFunctionLevelDeclContext();
493 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000494 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000495 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000496 MD->getThisType(Context),
497 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000498
Sebastian Redlf53597f2009-03-15 17:47:39 +0000499 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000500}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000501
502/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
503/// Can be interpreted either as function-style casting ("int(x)")
504/// or class type construction ("ClassType(x,y,z)")
505/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000506Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000507Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
508 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000509 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000510 SourceLocation *CommaLocs,
511 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000512 if (!TypeRep)
513 return ExprError();
514
John McCall9d125032010-01-15 18:39:57 +0000515 TypeSourceInfo *TInfo;
516 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
517 if (!TInfo)
518 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000519 unsigned NumExprs = exprs.size();
520 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000521 SourceLocation TyBeginLoc = TypeRange.getBegin();
522 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
523
Sebastian Redlf53597f2009-03-15 17:47:39 +0000524 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000525 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000526 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000527
528 return Owned(CXXUnresolvedConstructExpr::Create(Context,
529 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000530 LParenLoc,
531 Exprs, NumExprs,
532 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000533 }
534
Anders Carlssonbb60a502009-08-27 03:53:50 +0000535 if (Ty->isArrayType())
536 return ExprError(Diag(TyBeginLoc,
537 diag::err_value_init_for_array_type) << FullRange);
538 if (!Ty->isVoidType() &&
539 RequireCompleteType(TyBeginLoc, Ty,
540 PDiag(diag::err_invalid_incomplete_type_use)
541 << FullRange))
542 return ExprError();
Fariborz Jahanianf071e9b2009-10-23 21:01:39 +0000543
Anders Carlssonbb60a502009-08-27 03:53:50 +0000544 if (RequireNonAbstractType(TyBeginLoc, Ty,
545 diag::err_allocation_of_abstract_type))
546 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000547
548
Douglas Gregor506ae412009-01-16 18:33:17 +0000549 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000550 // If the expression list is a single expression, the type conversion
551 // expression is equivalent (in definedness, and if defined in meaning) to the
552 // corresponding cast expression.
553 //
554 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000555 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson41b2dcd2010-04-24 18:38:56 +0000556 CXXBaseSpecifierArray BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000557 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, BasePath,
558 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000559 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000560
561 exprs.release();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000562
563 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
John McCall9d125032010-01-15 18:39:57 +0000564 TInfo, TyBeginLoc, Kind,
Anders Carlsson41b2dcd2010-04-24 18:38:56 +0000565 Exprs[0], BasePath,
566 RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000567 }
568
Ted Kremenek6217b802009-07-29 21:53:49 +0000569 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000570 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000571
Mike Stump1eb44332009-09-09 15:08:12 +0000572 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlssone7624a72009-08-27 05:08:22 +0000573 !Record->hasTrivialDestructor()) {
Eli Friedman6997aae2010-01-31 20:58:15 +0000574 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
575 InitializationKind Kind
576 = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
577 LParenLoc, RParenLoc)
578 : InitializationKind::CreateValue(TypeRange.getBegin(),
579 LParenLoc, RParenLoc);
580 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
581 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
582 move(exprs));
Douglas Gregor506ae412009-01-16 18:33:17 +0000583
Eli Friedman6997aae2010-01-31 20:58:15 +0000584 // FIXME: Improve AST representation?
585 return move(Result);
Douglas Gregor506ae412009-01-16 18:33:17 +0000586 }
587
588 // Fall through to value-initialize an object of class type that
589 // doesn't have a user-declared default constructor.
590 }
591
592 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000593 // If the expression list specifies more than a single value, the type shall
594 // be a class with a suitably declared constructor.
595 //
596 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000597 return ExprError(Diag(CommaLocs[0],
598 diag::err_builtin_func_cast_more_than_one_arg)
599 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000600
601 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregor506ae412009-01-16 18:33:17 +0000602 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000603 // The expression T(), where T is a simple-type-specifier for a non-array
604 // complete object type or the (possibly cv-qualified) void type, creates an
605 // rvalue of the specified type, which is value-initialized.
606 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000607 exprs.release();
608 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000609}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000610
611
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000612/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
613/// @code new (memory) int[size][4] @endcode
614/// or
615/// @code ::new Foo(23, "hello") @endcode
616/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000617Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000618Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000619 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000620 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000621 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000622 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000623 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000624 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000625 // If the specified type is an array, unwrap it and save the expression.
626 if (D.getNumTypeObjects() > 0 &&
627 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
628 DeclaratorChunk &Chunk = D.getTypeObject(0);
629 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000630 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
631 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000632 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000633 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
634 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000635
636 if (ParenTypeId) {
637 // Can't have dynamic array size when the type-id is in parentheses.
638 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
639 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
640 !NumElts->isIntegerConstantExpr(Context)) {
641 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
642 << NumElts->getSourceRange();
643 return ExprError();
644 }
645 }
646
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000647 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000648 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000649 }
650
Douglas Gregor043cad22009-09-11 00:18:58 +0000651 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000652 if (ArraySize) {
653 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000654 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
655 break;
656
657 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
658 if (Expr *NumElts = (Expr *)Array.NumElts) {
659 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
660 !NumElts->isIntegerConstantExpr(Context)) {
661 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
662 << NumElts->getSourceRange();
663 return ExprError();
664 }
665 }
666 }
667 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000668
John McCalla93c9342009-12-07 02:54:59 +0000669 //FIXME: Store TypeSourceInfo in CXXNew expression.
John McCallbf1a0282010-06-04 23:28:52 +0000670 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
671 QualType AllocType = TInfo->getType();
Chris Lattnereaaebc72009-04-25 08:06:05 +0000672 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000673 return ExprError();
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000674
675 SourceRange R = TInfo->getTypeLoc().getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000676 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000677 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000678 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000679 PlacementRParen,
680 ParenTypeId,
Mike Stump1eb44332009-09-09 15:08:12 +0000681 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000682 D.getSourceRange().getBegin(),
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000683 R,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000684 Owned(ArraySize),
685 ConstructorLParen,
686 move(ConstructorArgs),
687 ConstructorRParen);
688}
689
Mike Stump1eb44332009-09-09 15:08:12 +0000690Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000691Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
692 SourceLocation PlacementLParen,
693 MultiExprArg PlacementArgs,
694 SourceLocation PlacementRParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000695 bool ParenTypeId,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000696 QualType AllocType,
697 SourceLocation TypeLoc,
698 SourceRange TypeRange,
699 ExprArg ArraySizeE,
700 SourceLocation ConstructorLParen,
701 MultiExprArg ConstructorArgs,
702 SourceLocation ConstructorRParen) {
703 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000704 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000705
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000706 // Per C++0x [expr.new]p5, the type being constructed may be a
707 // typedef of an array type.
708 if (!ArraySizeE.get()) {
709 if (const ConstantArrayType *Array
710 = Context.getAsConstantArrayType(AllocType)) {
711 ArraySizeE = Owned(new (Context) IntegerLiteral(Array->getSize(),
712 Context.getSizeType(),
713 TypeRange.getEnd()));
714 AllocType = Array->getElementType();
715 }
716 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000717
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000718 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000719
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000720 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
721 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000722 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000723 if (ArraySize && !ArraySize->isTypeDependent()) {
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000724
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000725 QualType SizeType = ArraySize->getType();
Douglas Gregorc30614b2010-06-29 23:17:37 +0000726
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000727 OwningExprResult ConvertedSize
728 = ConvertToIntegralOrEnumerationType(StartLoc, move(ArraySizeE),
729 PDiag(diag::err_array_size_not_integral),
730 PDiag(diag::err_array_size_incomplete_type)
731 << ArraySize->getSourceRange(),
732 PDiag(diag::err_array_size_explicit_conversion),
733 PDiag(diag::note_array_size_conversion),
734 PDiag(diag::err_array_size_ambiguous_conversion),
735 PDiag(diag::note_array_size_conversion),
736 PDiag(getLangOptions().CPlusPlus0x? 0
737 : diag::ext_array_size_conversion));
738 if (ConvertedSize.isInvalid())
739 return ExprError();
740
741 ArraySize = ConvertedSize.takeAs<Expr>();
742 ArraySizeE = Owned(ArraySize);
743 SizeType = ArraySize->getType();
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000744 if (!SizeType->isIntegralOrEnumerationType())
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000745 return ExprError();
746
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000747 // Let's see if this is a constant < 0. If so, we reject it out of hand.
748 // We don't care about special rules, so we tell the machinery it's not
749 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000750 if (!ArraySize->isValueDependent()) {
751 llvm::APSInt Value;
752 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
753 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000754 llvm::APInt::getNullValue(Value.getBitWidth()),
755 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000756 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
757 diag::err_typecheck_negative_array_size)
758 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000759 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000760 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000761
Eli Friedman73c39ab2009-10-20 08:27:19 +0000762 ImpCastExprToType(ArraySize, Context.getSizeType(),
763 CastExpr::CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000764 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000765
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000766 FunctionDecl *OperatorNew = 0;
767 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000768 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
769 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000770
Sebastian Redl28507842009-02-26 14:39:58 +0000771 if (!AllocType->isDependentType() &&
772 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
773 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000774 SourceRange(PlacementLParen, PlacementRParen),
775 UseGlobal, AllocType, ArraySize, PlaceArgs,
776 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000777 return ExprError();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000778 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000779 if (OperatorNew) {
780 // Add default arguments, if any.
781 const FunctionProtoType *Proto =
782 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000783 VariadicCallType CallType =
784 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Anders Carlsson28e94832010-05-03 02:07:56 +0000785
786 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
787 Proto, 1, PlaceArgs, NumPlaceArgs,
788 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000789 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000790
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000791 NumPlaceArgs = AllPlaceArgs.size();
792 if (NumPlaceArgs > 0)
793 PlaceArgs = &AllPlaceArgs[0];
794 }
795
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000796 bool Init = ConstructorLParen.isValid();
797 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000798 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000799 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
800 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000801 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
802
Anders Carlsson48c95012010-05-03 15:45:23 +0000803 // Array 'new' can't have any initializers.
Anders Carlsson55cbd6e2010-05-16 16:24:20 +0000804 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlsson48c95012010-05-03 15:45:23 +0000805 SourceRange InitRange(ConsArgs[0]->getLocStart(),
806 ConsArgs[NumConsArgs - 1]->getLocEnd());
807
808 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
809 return ExprError();
810 }
811
Douglas Gregor99a2e602009-12-16 01:38:02 +0000812 if (!AllocType->isDependentType() &&
813 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
814 // C++0x [expr.new]p15:
815 // A new-expression that creates an object of type T initializes that
816 // object as follows:
817 InitializationKind Kind
818 // - If the new-initializer is omitted, the object is default-
819 // initialized (8.5); if no initialization is performed,
820 // the object has indeterminate value
821 = !Init? InitializationKind::CreateDefault(TypeLoc)
822 // - Otherwise, the new-initializer is interpreted according to the
823 // initialization rules of 8.5 for direct-initialization.
824 : InitializationKind::CreateDirect(TypeLoc,
825 ConstructorLParen,
826 ConstructorRParen);
827
Douglas Gregor99a2e602009-12-16 01:38:02 +0000828 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +0000829 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000830 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000831 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
832 move(ConstructorArgs));
833 if (FullInit.isInvalid())
834 return ExprError();
835
836 // FullInit is our initializer; walk through it to determine if it's a
837 // constructor call, which CXXNewExpr handles directly.
838 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
839 if (CXXBindTemporaryExpr *Binder
840 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
841 FullInitExpr = Binder->getSubExpr();
842 if (CXXConstructExpr *Construct
843 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
844 Constructor = Construct->getConstructor();
845 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
846 AEnd = Construct->arg_end();
847 A != AEnd; ++A)
848 ConvertedConstructorArgs.push_back(A->Retain());
849 } else {
850 // Take the converted initializer.
851 ConvertedConstructorArgs.push_back(FullInit.release());
852 }
853 } else {
854 // No initialization required.
855 }
856
857 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +0000858 NumConsArgs = ConvertedConstructorArgs.size();
859 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000860 }
Douglas Gregor99a2e602009-12-16 01:38:02 +0000861
Douglas Gregor6d908702010-02-26 05:06:18 +0000862 // Mark the new and delete operators as referenced.
863 if (OperatorNew)
864 MarkDeclarationReferenced(StartLoc, OperatorNew);
865 if (OperatorDelete)
866 MarkDeclarationReferenced(StartLoc, OperatorDelete);
867
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000868 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000869
Sebastian Redlf53597f2009-03-15 17:47:39 +0000870 PlacementArgs.release();
871 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000872 ArraySizeE.release();
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000873
874 // FIXME: The TypeSourceInfo should also be included in CXXNewExpr.
Ted Kremenekad7fe862010-02-11 22:51:03 +0000875 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
876 PlaceArgs, NumPlaceArgs, ParenTypeId,
877 ArraySize, Constructor, Init,
878 ConsArgs, NumConsArgs, OperatorDelete,
879 ResultType, StartLoc,
880 Init ? ConstructorRParen :
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000881 TypeRange.getEnd()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000882}
883
884/// CheckAllocatedType - Checks that a type is suitable as the allocated type
885/// in a new-expression.
886/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000887bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000888 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000889 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
890 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000891 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000892 return Diag(Loc, diag::err_bad_new_type)
893 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000894 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000895 return Diag(Loc, diag::err_bad_new_type)
896 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000897 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000898 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000899 PDiag(diag::err_new_incomplete_type)
900 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000901 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000902 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000903 diag::err_allocation_of_abstract_type))
904 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000905
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000906 return false;
907}
908
Douglas Gregor6d908702010-02-26 05:06:18 +0000909/// \brief Determine whether the given function is a non-placement
910/// deallocation function.
911static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
912 if (FD->isInvalidDecl())
913 return false;
914
915 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
916 return Method->isUsualDeallocationFunction();
917
918 return ((FD->getOverloadedOperator() == OO_Delete ||
919 FD->getOverloadedOperator() == OO_Array_Delete) &&
920 FD->getNumParams() == 1);
921}
922
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000923/// FindAllocationFunctions - Finds the overloads of operator new and delete
924/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000925bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
926 bool UseGlobal, QualType AllocType,
927 bool IsArray, Expr **PlaceArgs,
928 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000929 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000930 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000931 // --- Choosing an allocation function ---
932 // C++ 5.3.4p8 - 14 & 18
933 // 1) If UseGlobal is true, only look in the global scope. Else, also look
934 // in the scope of the allocated class.
935 // 2) If an array size is given, look for operator new[], else look for
936 // operator new.
937 // 3) The first argument is always size_t. Append the arguments from the
938 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000939
940 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
941 // We don't care about the actual value of this argument.
942 // FIXME: Should the Sema create the expression and embed it in the syntax
943 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000944 IntegerLiteral Size(llvm::APInt::getNullValue(
945 Context.Target.getPointerWidth(0)),
946 Context.getSizeType(),
947 SourceLocation());
948 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000949 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
950
Douglas Gregor6d908702010-02-26 05:06:18 +0000951 // C++ [expr.new]p8:
952 // If the allocated type is a non-array type, the allocation
953 // function’s name is operator new and the deallocation function’s
954 // name is operator delete. If the allocated type is an array
955 // type, the allocation function’s name is operator new[] and the
956 // deallocation function’s name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000957 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
958 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +0000959 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
960 IsArray ? OO_Array_Delete : OO_Delete);
961
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000962 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000963 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000964 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +0000965 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000966 AllocArgs.size(), Record, /*AllowMissing=*/true,
967 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000968 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000969 }
970 if (!OperatorNew) {
971 // Didn't find a member overload. Look for a global one.
972 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000973 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000974 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000975 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
976 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000977 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000978 }
979
John McCall9c82afc2010-04-20 02:18:25 +0000980 // We don't need an operator delete if we're running under
981 // -fno-exceptions.
982 if (!getLangOptions().Exceptions) {
983 OperatorDelete = 0;
984 return false;
985 }
986
Anders Carlssond9583892009-05-31 20:26:12 +0000987 // FindAllocationOverload can change the passed in arguments, so we need to
988 // copy them back.
989 if (NumPlaceArgs > 0)
990 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000991
Douglas Gregor6d908702010-02-26 05:06:18 +0000992 // C++ [expr.new]p19:
993 //
994 // If the new-expression begins with a unary :: operator, the
995 // deallocation function’s name is looked up in the global
996 // scope. Otherwise, if the allocated type is a class type T or an
997 // array thereof, the deallocation function’s name is looked up in
998 // the scope of T. If this lookup fails to find the name, or if
999 // the allocated type is not a class type or array thereof, the
1000 // deallocation function’s name is looked up in the global scope.
1001 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
1002 if (AllocType->isRecordType() && !UseGlobal) {
1003 CXXRecordDecl *RD
1004 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
1005 LookupQualifiedName(FoundDelete, RD);
1006 }
John McCall90c8c572010-03-18 08:19:33 +00001007 if (FoundDelete.isAmbiguous())
1008 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +00001009
1010 if (FoundDelete.empty()) {
1011 DeclareGlobalNewDelete();
1012 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1013 }
1014
1015 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +00001016
1017 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1018
John McCall90c8c572010-03-18 08:19:33 +00001019 if (NumPlaceArgs > 0) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001020 // C++ [expr.new]p20:
1021 // A declaration of a placement deallocation function matches the
1022 // declaration of a placement allocation function if it has the
1023 // same number of parameters and, after parameter transformations
1024 // (8.3.5), all parameter types except the first are
1025 // identical. [...]
1026 //
1027 // To perform this comparison, we compute the function type that
1028 // the deallocation function should have, and use that type both
1029 // for template argument deduction and for comparison purposes.
1030 QualType ExpectedFunctionType;
1031 {
1032 const FunctionProtoType *Proto
1033 = OperatorNew->getType()->getAs<FunctionProtoType>();
1034 llvm::SmallVector<QualType, 4> ArgTypes;
1035 ArgTypes.push_back(Context.VoidPtrTy);
1036 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1037 ArgTypes.push_back(Proto->getArgType(I));
1038
1039 ExpectedFunctionType
1040 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
1041 ArgTypes.size(),
1042 Proto->isVariadic(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001043 0, false, false, 0, 0,
1044 FunctionType::ExtInfo());
Douglas Gregor6d908702010-02-26 05:06:18 +00001045 }
1046
1047 for (LookupResult::iterator D = FoundDelete.begin(),
1048 DEnd = FoundDelete.end();
1049 D != DEnd; ++D) {
1050 FunctionDecl *Fn = 0;
1051 if (FunctionTemplateDecl *FnTmpl
1052 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1053 // Perform template argument deduction to try to match the
1054 // expected function type.
1055 TemplateDeductionInfo Info(Context, StartLoc);
1056 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1057 continue;
1058 } else
1059 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1060
1061 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001062 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001063 }
1064 } else {
1065 // C++ [expr.new]p20:
1066 // [...] Any non-placement deallocation function matches a
1067 // non-placement allocation function. [...]
1068 for (LookupResult::iterator D = FoundDelete.begin(),
1069 DEnd = FoundDelete.end();
1070 D != DEnd; ++D) {
1071 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1072 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001073 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001074 }
1075 }
1076
1077 // C++ [expr.new]p20:
1078 // [...] If the lookup finds a single matching deallocation
1079 // function, that function will be called; otherwise, no
1080 // deallocation function will be called.
1081 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001082 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001083
1084 // C++0x [expr.new]p20:
1085 // If the lookup finds the two-parameter form of a usual
1086 // deallocation function (3.7.4.2) and that function, considered
1087 // as a placement deallocation function, would have been
1088 // selected as a match for the allocation function, the program
1089 // is ill-formed.
1090 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1091 isNonPlacementDeallocationFunction(OperatorDelete)) {
1092 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1093 << SourceRange(PlaceArgs[0]->getLocStart(),
1094 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1095 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1096 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001097 } else {
1098 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001099 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001100 }
1101 }
1102
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001103 return false;
1104}
1105
Sebastian Redl7f662392008-12-04 22:20:51 +00001106/// FindAllocationOverload - Find an fitting overload for the allocation
1107/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001108bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1109 DeclarationName Name, Expr** Args,
1110 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +00001111 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001112 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1113 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001114 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001115 if (AllowMissing)
1116 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001117 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001118 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001119 }
1120
John McCall90c8c572010-03-18 08:19:33 +00001121 if (R.isAmbiguous())
1122 return true;
1123
1124 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001125
John McCall5769d612010-02-08 23:07:23 +00001126 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001127 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1128 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001129 // Even member operator new/delete are implicitly treated as
1130 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001131 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001132
John McCall9aa472c2010-03-19 07:35:19 +00001133 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1134 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001135 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1136 Candidates,
1137 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001138 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001139 }
1140
John McCall9aa472c2010-03-19 07:35:19 +00001141 FunctionDecl *Fn = cast<FunctionDecl>(D);
1142 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001143 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001144 }
1145
1146 // Do the resolution.
1147 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001148 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001149 case OR_Success: {
1150 // Got one!
1151 FunctionDecl *FnDecl = Best->Function;
1152 // The first argument is size_t, and the first parameter must be size_t,
1153 // too. This is checked on declaration and can be assumed. (It can't be
1154 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001155 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001156 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1157 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001158 OwningExprResult Result
1159 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
1160 FnDecl->getParamDecl(i)),
1161 SourceLocation(),
1162 Owned(Args[i]->Retain()));
1163 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001164 return true;
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001165
1166 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001167 }
1168 Operator = FnDecl;
John McCall9aa472c2010-03-19 07:35:19 +00001169 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001170 return false;
1171 }
1172
1173 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +00001174 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001175 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001176 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001177 return true;
1178
1179 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +00001180 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +00001181 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001182 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001183 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001184
1185 case OR_Deleted:
1186 Diag(StartLoc, diag::err_ovl_deleted_call)
1187 << Best->Function->isDeleted()
1188 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001189 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001190 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001191 }
1192 assert(false && "Unreachable, bad result from BestViableFunction");
1193 return true;
1194}
1195
1196
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001197/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1198/// delete. These are:
1199/// @code
1200/// void* operator new(std::size_t) throw(std::bad_alloc);
1201/// void* operator new[](std::size_t) throw(std::bad_alloc);
1202/// void operator delete(void *) throw();
1203/// void operator delete[](void *) throw();
1204/// @endcode
1205/// Note that the placement and nothrow forms of new are *not* implicitly
1206/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001207void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001208 if (GlobalNewDeleteDeclared)
1209 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001210
1211 // C++ [basic.std.dynamic]p2:
1212 // [...] The following allocation and deallocation functions (18.4) are
1213 // implicitly declared in global scope in each translation unit of a
1214 // program
1215 //
1216 // void* operator new(std::size_t) throw(std::bad_alloc);
1217 // void* operator new[](std::size_t) throw(std::bad_alloc);
1218 // void operator delete(void*) throw();
1219 // void operator delete[](void*) throw();
1220 //
1221 // These implicit declarations introduce only the function names operator
1222 // new, operator new[], operator delete, operator delete[].
1223 //
1224 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1225 // "std" or "bad_alloc" as necessary to form the exception specification.
1226 // However, we do not make these implicit declarations visible to name
1227 // lookup.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001228 if (!StdBadAlloc) {
1229 // The "std::bad_alloc" class has not yet been declared, so build it
1230 // implicitly.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001231 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
Douglas Gregor66992202010-06-29 17:53:46 +00001232 getStdNamespace(),
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001233 SourceLocation(),
1234 &PP.getIdentifierTable().get("bad_alloc"),
1235 SourceLocation(), 0);
1236 StdBadAlloc->setImplicit(true);
1237 }
1238
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001239 GlobalNewDeleteDeclared = true;
1240
1241 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1242 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001243 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001244
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001245 DeclareGlobalAllocationFunction(
1246 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001247 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001248 DeclareGlobalAllocationFunction(
1249 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001250 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001251 DeclareGlobalAllocationFunction(
1252 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1253 Context.VoidTy, VoidPtr);
1254 DeclareGlobalAllocationFunction(
1255 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1256 Context.VoidTy, VoidPtr);
1257}
1258
1259/// DeclareGlobalAllocationFunction - Declares a single implicit global
1260/// allocation function if it doesn't already exist.
1261void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001262 QualType Return, QualType Argument,
1263 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001264 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1265
1266 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001267 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001268 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001269 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001270 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001271 // Only look at non-template functions, as it is the predefined,
1272 // non-templated allocation function we are trying to declare here.
1273 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1274 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001275 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001276 Func->getParamDecl(0)->getType().getUnqualifiedType());
1277 // FIXME: Do we need to check for default arguments here?
1278 if (Func->getNumParams() == 1 && InitialParamType == Argument)
1279 return;
1280 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001281 }
1282 }
1283
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001284 QualType BadAllocType;
1285 bool HasBadAllocExceptionSpec
1286 = (Name.getCXXOverloadedOperator() == OO_New ||
1287 Name.getCXXOverloadedOperator() == OO_Array_New);
1288 if (HasBadAllocExceptionSpec) {
1289 assert(StdBadAlloc && "Must have std::bad_alloc declared");
1290 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
1291 }
1292
1293 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1294 true, false,
1295 HasBadAllocExceptionSpec? 1 : 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00001296 &BadAllocType,
1297 FunctionType::ExtInfo());
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001298 FunctionDecl *Alloc =
1299 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001300 FnType, /*TInfo=*/0, FunctionDecl::None,
1301 FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001302 Alloc->setImplicit();
Nuno Lopesfc284482009-12-16 16:59:22 +00001303
1304 if (AddMallocAttr)
1305 Alloc->addAttr(::new (Context) MallocAttr());
1306
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001307 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00001308 0, Argument, /*TInfo=*/0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001309 VarDecl::None,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001310 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00001311 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001312
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001313 // FIXME: Also add this declaration to the IdentifierResolver, but
1314 // make sure it is at the end of the chain to coincide with the
1315 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001316 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001317}
1318
Anders Carlsson78f74552009-11-15 18:45:20 +00001319bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1320 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00001321 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001322 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001323 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001324 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +00001325
John McCalla24dc2e2009-11-17 02:14:36 +00001326 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001327 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001328
Chandler Carruth23893242010-06-28 00:30:51 +00001329 Found.suppressDiagnostics();
1330
Anders Carlsson78f74552009-11-15 18:45:20 +00001331 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1332 F != FEnd; ++F) {
1333 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
1334 if (Delete->isUsualDeallocationFunction()) {
1335 Operator = Delete;
Chandler Carruth23893242010-06-28 00:30:51 +00001336 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1337 F.getPair());
Anders Carlsson78f74552009-11-15 18:45:20 +00001338 return false;
1339 }
1340 }
1341
1342 // We did find operator delete/operator delete[] declarations, but
1343 // none of them were suitable.
1344 if (!Found.empty()) {
1345 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1346 << Name << RD;
1347
1348 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1349 F != FEnd; ++F) {
Douglas Gregorb0fd4832010-04-25 20:55:08 +00001350 Diag((*F)->getLocation(), diag::note_member_declared_here)
Anders Carlsson78f74552009-11-15 18:45:20 +00001351 << Name;
1352 }
1353
1354 return true;
1355 }
1356
1357 // Look for a global declaration.
1358 DeclareGlobalNewDelete();
1359 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1360
1361 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1362 Expr* DeallocArgs[1];
1363 DeallocArgs[0] = &Null;
1364 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1365 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1366 Operator))
1367 return true;
1368
1369 assert(Operator && "Did not find a deallocation function!");
1370 return false;
1371}
1372
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001373/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1374/// @code ::delete ptr; @endcode
1375/// or
1376/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +00001377Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001378Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +00001379 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001380 // C++ [expr.delete]p1:
1381 // The operand shall have a pointer type, or a class type having a single
1382 // conversion function to a pointer type. The result has type void.
1383 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001384 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1385
Anders Carlssond67c4c32009-08-16 20:29:29 +00001386 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001387
Sebastian Redlf53597f2009-03-15 17:47:39 +00001388 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +00001389 if (!Ex->isTypeDependent()) {
1390 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001391
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001392 if (const RecordType *Record = Type->getAs<RecordType>()) {
John McCall32daa422010-03-31 01:36:47 +00001393 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1394
Fariborz Jahanian53462782009-09-11 21:44:33 +00001395 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCall32daa422010-03-31 01:36:47 +00001396 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001397 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001398 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001399 NamedDecl *D = I.getDecl();
1400 if (isa<UsingShadowDecl>(D))
1401 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1402
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001403 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001404 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001405 continue;
1406
John McCall32daa422010-03-31 01:36:47 +00001407 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001408
1409 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1410 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1411 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001412 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001413 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001414 if (ObjectPtrConversions.size() == 1) {
1415 // We have a single conversion to a pointer-to-object type. Perform
1416 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001417 // TODO: don't redo the conversion calculation.
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001418 Operand.release();
John McCall32daa422010-03-31 01:36:47 +00001419 if (!PerformImplicitConversion(Ex,
1420 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +00001421 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001422 Operand = Owned(Ex);
1423 Type = Ex->getType();
1424 }
1425 }
1426 else if (ObjectPtrConversions.size() > 1) {
1427 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1428 << Type << Ex->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001429 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1430 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001431 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001432 }
Sebastian Redl28507842009-02-26 14:39:58 +00001433 }
1434
Sebastian Redlf53597f2009-03-15 17:47:39 +00001435 if (!Type->isPointerType())
1436 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1437 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001438
Ted Kremenek6217b802009-07-29 21:53:49 +00001439 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor94a61572010-05-24 17:01:56 +00001440 if (Pointee->isVoidType() && !isSFINAEContext()) {
1441 // The C++ standard bans deleting a pointer to a non-object type, which
1442 // effectively bans deletion of "void*". However, most compilers support
1443 // this, so we treat it as a warning unless we're in a SFINAE context.
1444 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1445 << Type << Ex->getSourceRange();
1446 } else if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001447 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1448 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001449 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001450 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +00001451 PDiag(diag::warn_delete_incomplete)
1452 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001453 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +00001454
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001455 // C++ [expr.delete]p2:
1456 // [Note: a pointer to a const type can be the operand of a
1457 // delete-expression; it is not necessary to cast away the constness
1458 // (5.2.11) of the pointer expression before it is used as the operand
1459 // of the delete-expression. ]
1460 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
1461 CastExpr::CK_NoOp);
1462
1463 // Update the operand.
1464 Operand.take();
1465 Operand = ExprArg(*this, Ex);
1466
Anders Carlssond67c4c32009-08-16 20:29:29 +00001467 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1468 ArrayForm ? OO_Array_Delete : OO_Delete);
1469
Anders Carlsson78f74552009-11-15 18:45:20 +00001470 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
1471 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1472
1473 if (!UseGlobal &&
1474 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001475 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001476
Anders Carlsson78f74552009-11-15 18:45:20 +00001477 if (!RD->hasTrivialDestructor())
1478 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001479 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001480 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +00001481 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001482
Anders Carlssond67c4c32009-08-16 20:29:29 +00001483 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001484 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001485 DeclareGlobalNewDelete();
1486 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001487 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +00001488 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001489 OperatorDelete))
1490 return ExprError();
1491 }
Mike Stump1eb44332009-09-09 15:08:12 +00001492
John McCall9c82afc2010-04-20 02:18:25 +00001493 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1494
Sebastian Redl28507842009-02-26 14:39:58 +00001495 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001496 }
1497
Sebastian Redlf53597f2009-03-15 17:47:39 +00001498 Operand.release();
1499 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001500 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001501}
1502
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001503/// \brief Check the use of the given variable as a C++ condition in an if,
1504/// while, do-while, or switch statement.
Douglas Gregor586596f2010-05-06 17:25:47 +00001505Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
1506 SourceLocation StmtLoc,
1507 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001508 QualType T = ConditionVar->getType();
1509
1510 // C++ [stmt.select]p2:
1511 // The declarator shall not specify a function or an array.
1512 if (T->isFunctionType())
1513 return ExprError(Diag(ConditionVar->getLocation(),
1514 diag::err_invalid_use_of_function_type)
1515 << ConditionVar->getSourceRange());
1516 else if (T->isArrayType())
1517 return ExprError(Diag(ConditionVar->getLocation(),
1518 diag::err_invalid_use_of_array_type)
1519 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001520
Douglas Gregor586596f2010-05-06 17:25:47 +00001521 Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1522 ConditionVar->getLocation(),
1523 ConditionVar->getType().getNonReferenceType());
1524 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc)) {
1525 Condition->Destroy(Context);
1526 return ExprError();
1527 }
1528
1529 return Owned(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001530}
1531
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001532/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1533bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1534 // C++ 6.4p4:
1535 // The value of a condition that is an initialized declaration in a statement
1536 // other than a switch statement is the value of the declared variable
1537 // implicitly converted to type bool. If that conversion is ill-formed, the
1538 // program is ill-formed.
1539 // The value of a condition that is an expression is the value of the
1540 // expression, implicitly converted to bool.
1541 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001542 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001543}
Douglas Gregor77a52232008-09-12 00:47:35 +00001544
1545/// Helper function to determine whether this is the (deprecated) C++
1546/// conversion from a string literal to a pointer to non-const char or
1547/// non-const wchar_t (for narrow and wide string literals,
1548/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001549bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001550Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1551 // Look inside the implicit cast, if it exists.
1552 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1553 From = Cast->getSubExpr();
1554
1555 // A string literal (2.13.4) that is not a wide string literal can
1556 // be converted to an rvalue of type "pointer to char"; a wide
1557 // string literal can be converted to an rvalue of type "pointer
1558 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00001559 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00001560 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001561 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001562 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001563 // This conversion is considered only when there is an
1564 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001565 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001566 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1567 (!StrLit->isWide() &&
1568 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1569 ToPointeeType->getKind() == BuiltinType::Char_S))))
1570 return true;
1571 }
1572
1573 return false;
1574}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001575
Douglas Gregorba70ab62010-04-16 22:17:36 +00001576static Sema::OwningExprResult BuildCXXCastArgument(Sema &S,
1577 SourceLocation CastLoc,
1578 QualType Ty,
1579 CastExpr::CastKind Kind,
1580 CXXMethodDecl *Method,
1581 Sema::ExprArg Arg) {
1582 Expr *From = Arg.takeAs<Expr>();
1583
1584 switch (Kind) {
1585 default: assert(0 && "Unhandled cast kind!");
1586 case CastExpr::CK_ConstructorConversion: {
1587 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
1588
1589 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
1590 Sema::MultiExprArg(S, (void **)&From, 1),
1591 CastLoc, ConstructorArgs))
1592 return S.ExprError();
1593
1594 Sema::OwningExprResult Result =
1595 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
1596 move_arg(ConstructorArgs));
1597 if (Result.isInvalid())
1598 return S.ExprError();
1599
1600 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1601 }
1602
1603 case CastExpr::CK_UserDefinedConversion: {
1604 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1605
1606 // Create an implicit call expr that calls it.
1607 // FIXME: pass the FoundDecl for the user-defined conversion here
1608 CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method);
1609 return S.MaybeBindToTemporary(CE);
1610 }
1611 }
1612}
1613
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001614/// PerformImplicitConversion - Perform an implicit conversion of the
1615/// expression From to the type ToType using the pre-computed implicit
1616/// conversion sequence ICS. Returns true if there was an error, false
1617/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001618/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001619/// used in the error message.
1620bool
1621Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1622 const ImplicitConversionSequence &ICS,
Douglas Gregor68647482009-12-16 03:45:30 +00001623 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall1d318332010-01-12 00:44:57 +00001624 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001625 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001626 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001627 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001628 return true;
1629 break;
1630
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001631 case ImplicitConversionSequence::UserDefinedConversion: {
1632
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001633 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1634 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001635 QualType BeforeToType;
1636 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001637 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001638
1639 // If the user-defined conversion is specified by a conversion function,
1640 // the initial standard conversion sequence converts the source type to
1641 // the implicit object parameter of the conversion function.
1642 BeforeToType = Context.getTagDeclType(Conv->getParent());
1643 } else if (const CXXConstructorDecl *Ctor =
1644 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001645 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001646 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001647 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001648 // If the user-defined conversion is specified by a constructor, the
1649 // initial standard conversion sequence converts the source type to the
1650 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001651 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1652 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001653 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001654 else
1655 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001656 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001657 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001658 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001659 ICS.UserDefined.Before, AA_Converting,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001660 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001661 return true;
1662 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001663
Anders Carlsson0aebc812009-09-09 21:33:21 +00001664 OwningExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00001665 = BuildCXXCastArgument(*this,
1666 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00001667 ToType.getNonReferenceType(),
1668 CastKind, cast<CXXMethodDecl>(FD),
1669 Owned(From));
1670
1671 if (CastArg.isInvalid())
1672 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001673
1674 From = CastArg.takeAs<Expr>();
1675
Eli Friedmand8889622009-11-27 04:41:50 +00001676 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor68647482009-12-16 03:45:30 +00001677 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001678 }
John McCall1d318332010-01-12 00:44:57 +00001679
1680 case ImplicitConversionSequence::AmbiguousConversion:
1681 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1682 PDiag(diag::err_typecheck_ambiguous_condition)
1683 << From->getSourceRange());
1684 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001685
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001686 case ImplicitConversionSequence::EllipsisConversion:
1687 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001688 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001689
1690 case ImplicitConversionSequence::BadConversion:
1691 return true;
1692 }
1693
1694 // Everything went well.
1695 return false;
1696}
1697
1698/// PerformImplicitConversion - Perform an implicit conversion of the
1699/// expression From to the type ToType by following the standard
1700/// conversion sequence SCS. Returns true if there was an error, false
1701/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001702/// expression. Flavor is the context in which we're performing this
1703/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001704bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001705Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001706 const StandardConversionSequence& SCS,
Douglas Gregor68647482009-12-16 03:45:30 +00001707 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001708 // Overall FIXME: we are recomputing too many types here and doing far too
1709 // much extra work. What this means is that we need to keep track of more
1710 // information that is computed when we try the implicit conversion initially,
1711 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001712 QualType FromType = From->getType();
1713
Douglas Gregor225c41e2008-11-03 19:09:14 +00001714 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001715 // FIXME: When can ToType be a reference type?
1716 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001717 if (SCS.Second == ICK_Derived_To_Base) {
1718 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1719 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1720 MultiExprArg(*this, (void **)&From, 1),
1721 /*FIXME:ConstructLoc*/SourceLocation(),
1722 ConstructorArgs))
1723 return true;
1724 OwningExprResult FromResult =
1725 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1726 ToType, SCS.CopyConstructor,
1727 move_arg(ConstructorArgs));
1728 if (FromResult.isInvalid())
1729 return true;
1730 From = FromResult.takeAs<Expr>();
1731 return false;
1732 }
Mike Stump1eb44332009-09-09 15:08:12 +00001733 OwningExprResult FromResult =
1734 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1735 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001736 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001737
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001738 if (FromResult.isInvalid())
1739 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001740
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001741 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001742 return false;
1743 }
1744
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001745 // Resolve overloaded function references.
1746 if (Context.hasSameType(FromType, Context.OverloadTy)) {
1747 DeclAccessPair Found;
1748 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1749 true, Found);
1750 if (!Fn)
1751 return true;
1752
1753 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1754 return true;
1755
1756 From = FixOverloadedFunctionReference(From, Found, Fn);
1757 FromType = From->getType();
1758 }
1759
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001760 // Perform the first implicit conversion.
1761 switch (SCS.First) {
1762 case ICK_Identity:
1763 case ICK_Lvalue_To_Rvalue:
1764 // Nothing to do.
1765 break;
1766
1767 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001768 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001769 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001770 break;
1771
1772 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001773 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001774 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001775 break;
1776
1777 default:
1778 assert(false && "Improper first standard conversion");
1779 break;
1780 }
1781
1782 // Perform the second implicit conversion
1783 switch (SCS.Second) {
1784 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001785 // If both sides are functions (or pointers/references to them), there could
1786 // be incompatible exception declarations.
1787 if (CheckExceptionSpecCompatibility(From, ToType))
1788 return true;
1789 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001790 break;
1791
Douglas Gregor43c79c22009-12-09 00:47:37 +00001792 case ICK_NoReturn_Adjustment:
1793 // If both sides are functions (or pointers/references to them), there could
1794 // be incompatible exception declarations.
1795 if (CheckExceptionSpecCompatibility(From, ToType))
1796 return true;
1797
1798 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1799 CastExpr::CK_NoOp);
1800 break;
1801
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001802 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001803 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001804 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1805 break;
1806
1807 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001808 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001809 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1810 break;
1811
1812 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001813 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001814 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1815 break;
1816
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001817 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001818 if (ToType->isRealFloatingType())
Eli Friedman73c39ab2009-10-20 08:27:19 +00001819 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1820 else
1821 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1822 break;
1823
Douglas Gregorf9201e02009-02-11 23:02:49 +00001824 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001825 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001826 break;
1827
Anders Carlsson61faec12009-09-12 04:46:44 +00001828 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001829 if (SCS.IncompatibleObjC) {
1830 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001831 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001832 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00001833 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00001834 << From->getSourceRange();
1835 }
1836
Anders Carlsson61faec12009-09-12 04:46:44 +00001837
1838 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001839 CXXBaseSpecifierArray BasePath;
1840 if (CheckPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001841 return true;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001842 ImpCastExprToType(From, ToType, Kind, /*isLvalue=*/false, BasePath);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001843 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001844 }
1845
1846 case ICK_Pointer_Member: {
1847 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001848 CXXBaseSpecifierArray BasePath;
1849 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath,
1850 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001851 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001852 if (CheckExceptionSpecCompatibility(From, ToType))
1853 return true;
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001854 ImpCastExprToType(From, ToType, Kind, /*isLvalue=*/false, BasePath);
Anders Carlsson61faec12009-09-12 04:46:44 +00001855 break;
1856 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001857 case ICK_Boolean_Conversion: {
1858 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1859 if (FromType->isMemberPointerType())
1860 Kind = CastExpr::CK_MemberPointerToBoolean;
1861
1862 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001863 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001864 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001865
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001866 case ICK_Derived_To_Base: {
1867 CXXBaseSpecifierArray BasePath;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001868 if (CheckDerivedToBaseConversion(From->getType(),
1869 ToType.getNonReferenceType(),
1870 From->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001871 From->getSourceRange(),
1872 &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001873 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001874 return true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001875
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001876 ImpCastExprToType(From, ToType.getNonReferenceType(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001877 CastExpr::CK_DerivedToBase,
1878 /*isLvalue=*/(From->getType()->isRecordType() &&
1879 From->isLvalue(Context) == Expr::LV_Valid),
1880 BasePath);
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001881 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001882 }
1883
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001884 case ICK_Vector_Conversion:
1885 ImpCastExprToType(From, ToType, CastExpr::CK_BitCast);
1886 break;
1887
1888 case ICK_Vector_Splat:
1889 ImpCastExprToType(From, ToType, CastExpr::CK_VectorSplat);
1890 break;
1891
1892 case ICK_Complex_Real:
1893 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1894 break;
1895
1896 case ICK_Lvalue_To_Rvalue:
1897 case ICK_Array_To_Pointer:
1898 case ICK_Function_To_Pointer:
1899 case ICK_Qualification:
1900 case ICK_Num_Conversion_Kinds:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001901 assert(false && "Improper second standard conversion");
1902 break;
1903 }
1904
1905 switch (SCS.Third) {
1906 case ICK_Identity:
1907 // Nothing to do.
1908 break;
1909
1910 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001911 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1912 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001913 ImpCastExprToType(From, ToType.getNonReferenceType(),
Anders Carlssonf1b48b72010-04-24 16:57:13 +00001914 CastExpr::CK_NoOp, ToType->isLValueReferenceType());
Douglas Gregora9bff302010-02-28 18:30:25 +00001915
1916 if (SCS.DeprecatedStringLiteralToCharPtr)
1917 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
1918 << ToType.getNonReferenceType();
1919
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001920 break;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001921
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001922 default:
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001923 assert(false && "Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001924 break;
1925 }
1926
1927 return false;
1928}
1929
Sebastian Redl64b45f72009-01-05 20:52:13 +00001930Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1931 SourceLocation KWLoc,
1932 SourceLocation LParen,
1933 TypeTy *Ty,
1934 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001935 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001936
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001937 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1938 // all traits except __is_class, __is_enum and __is_union require a the type
1939 // to be complete.
1940 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001941 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001942 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001943 return ExprError();
1944 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001945
1946 // There is no point in eagerly computing the value. The traits are designed
1947 // to be used from type trait templates, so Ty will be a template parameter
1948 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001949 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1950 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001951}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001952
1953QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001954 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001955 const char *OpSpelling = isIndirect ? "->*" : ".*";
1956 // C++ 5.5p2
1957 // The binary operator .* [p3: ->*] binds its second operand, which shall
1958 // be of type "pointer to member of T" (where T is a completely-defined
1959 // class type) [...]
1960 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001961 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001962 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001963 Diag(Loc, diag::err_bad_memptr_rhs)
1964 << OpSpelling << RType << rex->getSourceRange();
1965 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001966 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001967
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001968 QualType Class(MemPtr->getClass(), 0);
1969
Sebastian Redl59fc2692010-04-10 10:14:54 +00001970 if (RequireCompleteType(Loc, Class, diag::err_memptr_rhs_to_incomplete))
1971 return QualType();
1972
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001973 // C++ 5.5p2
1974 // [...] to its first operand, which shall be of class T or of a class of
1975 // which T is an unambiguous and accessible base class. [p3: a pointer to
1976 // such a class]
1977 QualType LType = lex->getType();
1978 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001979 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001980 LType = Ptr->getPointeeType().getNonReferenceType();
1981 else {
1982 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001983 << OpSpelling << 1 << LType
Douglas Gregor849b2432010-03-31 17:46:05 +00001984 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001985 return QualType();
1986 }
1987 }
1988
Douglas Gregora4923eb2009-11-16 21:35:15 +00001989 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00001990 // If we want to check the hierarchy, we need a complete type.
1991 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
1992 << OpSpelling << (int)isIndirect)) {
1993 return QualType();
1994 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001995 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001996 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001997 // FIXME: Would it be useful to print full ambiguity paths, or is that
1998 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001999 if (!IsDerivedFrom(LType, Class, Paths) ||
2000 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
2001 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00002002 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002003 return QualType();
2004 }
Eli Friedman3005efe2010-01-16 00:00:48 +00002005 // Cast LHS to type of use.
2006 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
2007 bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002008
2009 CXXBaseSpecifierArray BasePath;
2010 BuildBasePathArray(Paths, BasePath);
2011 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue,
2012 BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002013 }
2014
Fariborz Jahanian19d70732009-11-18 22:16:17 +00002015 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00002016 // Diagnose use of pointer-to-member type which when used as
2017 // the functional cast in a pointer-to-member expression.
2018 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
2019 return QualType();
2020 }
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002021 // C++ 5.5p2
2022 // The result is an object or a function of the type specified by the
2023 // second operand.
2024 // The cv qualifiers are the union of those in the pointer and the left side,
2025 // in accordance with 5.5p5 and 5.2.5.
2026 // FIXME: This returns a dereferenced member function pointer as a normal
2027 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00002028 // calling them. There's also a GCC extension to get a function pointer to the
2029 // thing, which is another complication, because this type - unlike the type
2030 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002031 // argument.
2032 // We probably need a "MemberFunctionClosureType" or something like that.
2033 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00002034 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002035 return Result;
2036}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002037
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002038/// \brief Try to convert a type to another according to C++0x 5.16p3.
2039///
2040/// This is part of the parameter validation for the ? operator. If either
2041/// value operand is a class type, the two operands are attempted to be
2042/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002043/// It returns true if the program is ill-formed and has already been diagnosed
2044/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002045static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
2046 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00002047 bool &HaveConversion,
2048 QualType &ToType) {
2049 HaveConversion = false;
2050 ToType = To->getType();
2051
2052 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
2053 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002054 // C++0x 5.16p3
2055 // The process for determining whether an operand expression E1 of type T1
2056 // can be converted to match an operand expression E2 of type T2 is defined
2057 // as follows:
2058 // -- If E2 is an lvalue:
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002059 bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid);
2060 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002061 // E1 can be converted to match E2 if E1 can be implicitly converted to
2062 // type "lvalue reference to T2", subject to the constraint that in the
2063 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002064 QualType T = Self.Context.getLValueReferenceType(ToType);
2065 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2066
2067 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2068 if (InitSeq.isDirectReferenceBinding()) {
2069 ToType = T;
2070 HaveConversion = true;
2071 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002072 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002073
2074 if (InitSeq.isAmbiguous())
2075 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002076 }
John McCallb1bdc622010-02-25 01:37:24 +00002077
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002078 // -- If E2 is an rvalue, or if the conversion above cannot be done:
2079 // -- if E1 and E2 have class type, and the underlying class types are
2080 // the same or one is a base class of the other:
2081 QualType FTy = From->getType();
2082 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002083 const RecordType *FRec = FTy->getAs<RecordType>();
2084 const RecordType *TRec = TTy->getAs<RecordType>();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002085 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
2086 Self.IsDerivedFrom(FTy, TTy);
2087 if (FRec && TRec &&
2088 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002089 // E1 can be converted to match E2 if the class of T2 is the
2090 // same type as, or a base class of, the class of T1, and
2091 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00002092 if (FRec == TRec || FDerivedFromT) {
2093 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002094 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2095 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2096 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2097 HaveConversion = true;
2098 return false;
2099 }
2100
2101 if (InitSeq.isAmbiguous())
2102 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2103 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002104 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002105
2106 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002107 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002108
2109 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2110 // implicitly converted to the type that expression E2 would have
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002111 // if E2 were converted to an rvalue (or the type it has, if E2 is
2112 // an rvalue).
2113 //
2114 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2115 // to the array-to-pointer or function-to-pointer conversions.
2116 if (!TTy->getAs<TagType>())
2117 TTy = TTy.getUnqualifiedType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002118
2119 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2120 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2121 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
2122 ToType = TTy;
2123 if (InitSeq.isAmbiguous())
2124 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2125
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002126 return false;
2127}
2128
2129/// \brief Try to find a common type for two according to C++0x 5.16p5.
2130///
2131/// This is part of the parameter validation for the ? operator. If either
2132/// value operand is a class type, overload resolution is used to find a
2133/// conversion to a common type.
2134static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2135 SourceLocation Loc) {
2136 Expr *Args[2] = { LHS, RHS };
John McCall5769d612010-02-08 23:07:23 +00002137 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor573d9c32009-10-21 23:19:44 +00002138 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002139
2140 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00002141 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002142 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002143 // We found a match. Perform the conversions on the arguments and move on.
2144 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00002145 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002146 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00002147 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002148 break;
2149 return false;
2150
Douglas Gregor20093b42009-12-09 23:02:17 +00002151 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002152 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2153 << LHS->getType() << RHS->getType()
2154 << LHS->getSourceRange() << RHS->getSourceRange();
2155 return true;
2156
Douglas Gregor20093b42009-12-09 23:02:17 +00002157 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002158 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2159 << LHS->getType() << RHS->getType()
2160 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00002161 // FIXME: Print the possible common types by printing the return types of
2162 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002163 break;
2164
Douglas Gregor20093b42009-12-09 23:02:17 +00002165 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002166 assert(false && "Conditional operator has only built-in overloads");
2167 break;
2168 }
2169 return true;
2170}
2171
Sebastian Redl76458502009-04-17 16:30:52 +00002172/// \brief Perform an "extended" implicit conversion as returned by
2173/// TryClassUnification.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002174static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2175 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2176 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2177 SourceLocation());
2178 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
2179 Sema::OwningExprResult Result = InitSeq.Perform(Self, Entity, Kind,
2180 Sema::MultiExprArg(Self, (void **)&E, 1));
2181 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00002182 return true;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002183
2184 E = Result.takeAs<Expr>();
Sebastian Redl76458502009-04-17 16:30:52 +00002185 return false;
2186}
2187
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002188/// \brief Check the operands of ?: under C++ semantics.
2189///
2190/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2191/// extension. In this case, LHS == Cond. (But they're not aliases.)
2192QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2193 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002194 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2195 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002196
2197 // C++0x 5.16p1
2198 // The first expression is contextually converted to bool.
2199 if (!Cond->isTypeDependent()) {
2200 if (CheckCXXBooleanCondition(Cond))
2201 return QualType();
2202 }
2203
2204 // Either of the arguments dependent?
2205 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2206 return Context.DependentTy;
2207
2208 // C++0x 5.16p2
2209 // If either the second or the third operand has type (cv) void, ...
2210 QualType LTy = LHS->getType();
2211 QualType RTy = RHS->getType();
2212 bool LVoid = LTy->isVoidType();
2213 bool RVoid = RTy->isVoidType();
2214 if (LVoid || RVoid) {
2215 // ... then the [l2r] conversions are performed on the second and third
2216 // operands ...
Douglas Gregora873dfc2010-02-03 00:27:59 +00002217 DefaultFunctionArrayLvalueConversion(LHS);
2218 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002219 LTy = LHS->getType();
2220 RTy = RHS->getType();
2221
2222 // ... and one of the following shall hold:
2223 // -- The second or the third operand (but not both) is a throw-
2224 // expression; the result is of the type of the other and is an rvalue.
2225 bool LThrow = isa<CXXThrowExpr>(LHS);
2226 bool RThrow = isa<CXXThrowExpr>(RHS);
2227 if (LThrow && !RThrow)
2228 return RTy;
2229 if (RThrow && !LThrow)
2230 return LTy;
2231
2232 // -- Both the second and third operands have type void; the result is of
2233 // type void and is an rvalue.
2234 if (LVoid && RVoid)
2235 return Context.VoidTy;
2236
2237 // Neither holds, error.
2238 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2239 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2240 << LHS->getSourceRange() << RHS->getSourceRange();
2241 return QualType();
2242 }
2243
2244 // Neither is void.
2245
2246 // C++0x 5.16p3
2247 // Otherwise, if the second and third operand have different types, and
2248 // either has (cv) class type, and attempt is made to convert each of those
2249 // operands to the other.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002250 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002251 (LTy->isRecordType() || RTy->isRecordType())) {
2252 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2253 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002254 QualType L2RType, R2LType;
2255 bool HaveL2R, HaveR2L;
2256 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002257 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002258 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002259 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002260
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002261 // If both can be converted, [...] the program is ill-formed.
2262 if (HaveL2R && HaveR2L) {
2263 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2264 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2265 return QualType();
2266 }
2267
2268 // If exactly one conversion is possible, that conversion is applied to
2269 // the chosen operand and the converted operands are used in place of the
2270 // original operands for the remainder of this section.
2271 if (HaveL2R) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002272 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002273 return QualType();
2274 LTy = LHS->getType();
2275 } else if (HaveR2L) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002276 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002277 return QualType();
2278 RTy = RHS->getType();
2279 }
2280 }
2281
2282 // C++0x 5.16p4
2283 // If the second and third operands are lvalues and have the same type,
2284 // the result is of that type [...]
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002285 bool Same = Context.hasSameType(LTy, RTy);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002286 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
2287 RHS->isLvalue(Context) == Expr::LV_Valid)
2288 return LTy;
2289
2290 // C++0x 5.16p5
2291 // Otherwise, the result is an rvalue. If the second and third operands
2292 // do not have the same type, and either has (cv) class type, ...
2293 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2294 // ... overload resolution is used to determine the conversions (if any)
2295 // to be applied to the operands. If the overload resolution fails, the
2296 // program is ill-formed.
2297 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2298 return QualType();
2299 }
2300
2301 // C++0x 5.16p6
2302 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2303 // conversions are performed on the second and third operands.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002304 DefaultFunctionArrayLvalueConversion(LHS);
2305 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002306 LTy = LHS->getType();
2307 RTy = RHS->getType();
2308
2309 // After those conversions, one of the following shall hold:
2310 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00002311 // is of that type. If the operands have class type, the result
2312 // is a prvalue temporary of the result type, which is
2313 // copy-initialized from either the second operand or the third
2314 // operand depending on the value of the first operand.
2315 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
2316 if (LTy->isRecordType()) {
2317 // The operands have class type. Make a temporary copy.
2318 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
2319 OwningExprResult LHSCopy = PerformCopyInitialization(Entity,
2320 SourceLocation(),
2321 Owned(LHS));
2322 if (LHSCopy.isInvalid())
2323 return QualType();
2324
2325 OwningExprResult RHSCopy = PerformCopyInitialization(Entity,
2326 SourceLocation(),
2327 Owned(RHS));
2328 if (RHSCopy.isInvalid())
2329 return QualType();
2330
2331 LHS = LHSCopy.takeAs<Expr>();
2332 RHS = RHSCopy.takeAs<Expr>();
2333 }
2334
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002335 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00002336 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002337
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002338 // Extension: conditional operator involving vector types.
2339 if (LTy->isVectorType() || RTy->isVectorType())
2340 return CheckVectorOperands(QuestionLoc, LHS, RHS);
2341
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002342 // -- The second and third operands have arithmetic or enumeration type;
2343 // the usual arithmetic conversions are performed to bring them to a
2344 // common type, and the result is of that type.
2345 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2346 UsualArithmeticConversions(LHS, RHS);
2347 return LHS->getType();
2348 }
2349
2350 // -- The second and third operands have pointer type, or one has pointer
2351 // type and the other is a null pointer constant; pointer conversions
2352 // and qualification conversions are performed to bring them to their
2353 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00002354 // -- The second and third operands have pointer to member type, or one has
2355 // pointer to member type and the other is a null pointer constant;
2356 // pointer to member conversions and qualification conversions are
2357 // performed to bring them to a common type, whose cv-qualification
2358 // shall match the cv-qualification of either the second or the third
2359 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002360 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002361 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002362 isSFINAEContext()? 0 : &NonStandardCompositeType);
2363 if (!Composite.isNull()) {
2364 if (NonStandardCompositeType)
2365 Diag(QuestionLoc,
2366 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2367 << LTy << RTy << Composite
2368 << LHS->getSourceRange() << RHS->getSourceRange();
2369
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002370 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002371 }
Fariborz Jahanian55016362009-12-10 20:46:08 +00002372
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002373 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00002374 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2375 if (!Composite.isNull())
2376 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002377
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002378 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2379 << LHS->getType() << RHS->getType()
2380 << LHS->getSourceRange() << RHS->getSourceRange();
2381 return QualType();
2382}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002383
2384/// \brief Find a merged pointer type and convert the two expressions to it.
2385///
Douglas Gregor20b3e992009-08-24 17:42:35 +00002386/// This finds the composite pointer type (or member pointer type) for @p E1
2387/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2388/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002389/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002390///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002391/// \param Loc The location of the operator requiring these two expressions to
2392/// be converted to the composite pointer type.
2393///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002394/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2395/// a non-standard (but still sane) composite type to which both expressions
2396/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2397/// will be set true.
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002398QualType Sema::FindCompositePointerType(SourceLocation Loc,
2399 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002400 bool *NonStandardCompositeType) {
2401 if (NonStandardCompositeType)
2402 *NonStandardCompositeType = false;
2403
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002404 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2405 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002406
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00002407 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2408 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00002409 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002410
2411 // C++0x 5.9p2
2412 // Pointer conversions and qualification conversions are performed on
2413 // pointer operands to bring them to their composite pointer type. If
2414 // one operand is a null pointer constant, the composite pointer type is
2415 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00002416 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002417 if (T2->isMemberPointerType())
2418 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
2419 else
2420 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002421 return T2;
2422 }
Douglas Gregorce940492009-09-25 04:25:58 +00002423 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002424 if (T1->isMemberPointerType())
2425 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
2426 else
2427 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002428 return T1;
2429 }
Mike Stump1eb44332009-09-09 15:08:12 +00002430
Douglas Gregor20b3e992009-08-24 17:42:35 +00002431 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002432 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2433 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002434 return QualType();
2435
2436 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2437 // the other has type "pointer to cv2 T" and the composite pointer type is
2438 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2439 // Otherwise, the composite pointer type is a pointer type similar to the
2440 // type of one of the operands, with a cv-qualification signature that is
2441 // the union of the cv-qualification signatures of the operand types.
2442 // In practice, the first part here is redundant; it's subsumed by the second.
2443 // What we do here is, we build the two possible composite types, and try the
2444 // conversions in both directions. If only one works, or if the two composite
2445 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00002446 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00002447 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2448 QualifierVector QualifierUnion;
2449 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2450 ContainingClassVector;
2451 ContainingClassVector MemberOfClass;
2452 QualType Composite1 = Context.getCanonicalType(T1),
2453 Composite2 = Context.getCanonicalType(T2);
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002454 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00002455 do {
2456 const PointerType *Ptr1, *Ptr2;
2457 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2458 (Ptr2 = Composite2->getAs<PointerType>())) {
2459 Composite1 = Ptr1->getPointeeType();
2460 Composite2 = Ptr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002461
2462 // If we're allowed to create a non-standard composite type, keep track
2463 // of where we need to fill in additional 'const' qualifiers.
2464 if (NonStandardCompositeType &&
2465 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2466 NeedConstBefore = QualifierUnion.size();
2467
Douglas Gregor20b3e992009-08-24 17:42:35 +00002468 QualifierUnion.push_back(
2469 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2470 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2471 continue;
2472 }
Mike Stump1eb44332009-09-09 15:08:12 +00002473
Douglas Gregor20b3e992009-08-24 17:42:35 +00002474 const MemberPointerType *MemPtr1, *MemPtr2;
2475 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2476 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2477 Composite1 = MemPtr1->getPointeeType();
2478 Composite2 = MemPtr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002479
2480 // If we're allowed to create a non-standard composite type, keep track
2481 // of where we need to fill in additional 'const' qualifiers.
2482 if (NonStandardCompositeType &&
2483 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2484 NeedConstBefore = QualifierUnion.size();
2485
Douglas Gregor20b3e992009-08-24 17:42:35 +00002486 QualifierUnion.push_back(
2487 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2488 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2489 MemPtr2->getClass()));
2490 continue;
2491 }
Mike Stump1eb44332009-09-09 15:08:12 +00002492
Douglas Gregor20b3e992009-08-24 17:42:35 +00002493 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00002494
Douglas Gregor20b3e992009-08-24 17:42:35 +00002495 // Cannot unwrap any more types.
2496 break;
2497 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00002498
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002499 if (NeedConstBefore && NonStandardCompositeType) {
2500 // Extension: Add 'const' to qualifiers that come before the first qualifier
2501 // mismatch, so that our (non-standard!) composite type meets the
2502 // requirements of C++ [conv.qual]p4 bullet 3.
2503 for (unsigned I = 0; I != NeedConstBefore; ++I) {
2504 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
2505 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
2506 *NonStandardCompositeType = true;
2507 }
2508 }
2509 }
2510
Douglas Gregor20b3e992009-08-24 17:42:35 +00002511 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002512 ContainingClassVector::reverse_iterator MOC
2513 = MemberOfClass.rbegin();
2514 for (QualifierVector::reverse_iterator
2515 I = QualifierUnion.rbegin(),
2516 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00002517 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00002518 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002519 if (MOC->first && MOC->second) {
2520 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00002521 Composite1 = Context.getMemberPointerType(
2522 Context.getQualifiedType(Composite1, Quals),
2523 MOC->first);
2524 Composite2 = Context.getMemberPointerType(
2525 Context.getQualifiedType(Composite2, Quals),
2526 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002527 } else {
2528 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00002529 Composite1
2530 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2531 Composite2
2532 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00002533 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002534 }
2535
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002536 // Try to convert to the first composite pointer type.
2537 InitializedEntity Entity1
2538 = InitializedEntity::InitializeTemporary(Composite1);
2539 InitializationKind Kind
2540 = InitializationKind::CreateCopy(Loc, SourceLocation());
2541 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
2542 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00002543
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002544 if (E1ToC1 && E2ToC1) {
2545 // Conversion to Composite1 is viable.
2546 if (!Context.hasSameType(Composite1, Composite2)) {
2547 // Composite2 is a different type from Composite1. Check whether
2548 // Composite2 is also viable.
2549 InitializedEntity Entity2
2550 = InitializedEntity::InitializeTemporary(Composite2);
2551 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2552 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2553 if (E1ToC2 && E2ToC2) {
2554 // Both Composite1 and Composite2 are viable and are different;
2555 // this is an ambiguity.
2556 return QualType();
2557 }
2558 }
2559
2560 // Convert E1 to Composite1
2561 OwningExprResult E1Result
2562 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E1,1));
2563 if (E1Result.isInvalid())
2564 return QualType();
2565 E1 = E1Result.takeAs<Expr>();
2566
2567 // Convert E2 to Composite1
2568 OwningExprResult E2Result
2569 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E2,1));
2570 if (E2Result.isInvalid())
2571 return QualType();
2572 E2 = E2Result.takeAs<Expr>();
2573
2574 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002575 }
2576
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002577 // Check whether Composite2 is viable.
2578 InitializedEntity Entity2
2579 = InitializedEntity::InitializeTemporary(Composite2);
2580 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2581 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2582 if (!E1ToC2 || !E2ToC2)
2583 return QualType();
2584
2585 // Convert E1 to Composite2
2586 OwningExprResult E1Result
2587 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E1, 1));
2588 if (E1Result.isInvalid())
2589 return QualType();
2590 E1 = E1Result.takeAs<Expr>();
2591
2592 // Convert E2 to Composite2
2593 OwningExprResult E2Result
2594 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E2, 1));
2595 if (E2Result.isInvalid())
2596 return QualType();
2597 E2 = E2Result.takeAs<Expr>();
2598
2599 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002600}
Anders Carlsson165a0a02009-05-17 18:41:29 +00002601
Anders Carlssondef11992009-05-30 20:36:53 +00002602Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00002603 if (!Context.getLangOptions().CPlusPlus)
2604 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002605
Douglas Gregor51326552009-12-24 18:51:59 +00002606 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2607
Ted Kremenek6217b802009-07-29 21:53:49 +00002608 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00002609 if (!RT)
2610 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002611
John McCall86ff3082010-02-04 22:26:26 +00002612 // If this is the result of a call expression, our source might
2613 // actually be a reference, in which case we shouldn't bind.
Anders Carlsson283e4d52009-09-14 01:30:44 +00002614 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2615 QualType Ty = CE->getCallee()->getType();
2616 if (const PointerType *PT = Ty->getAs<PointerType>())
2617 Ty = PT->getPointeeType();
Fariborz Jahanianb372b0f2010-02-18 20:31:02 +00002618 else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>())
2619 Ty = BPT->getPointeeType();
2620
John McCall183700f2009-09-21 23:43:11 +00002621 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00002622 if (FTy->getResultType()->isReferenceType())
2623 return Owned(E);
2624 }
Fariborz Jahaniand4266622010-06-16 18:56:04 +00002625 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
2626 QualType Ty = ME->getType();
2627 if (const PointerType *PT = Ty->getAs<PointerType>())
2628 Ty = PT->getPointeeType();
2629 else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>())
2630 Ty = BPT->getPointeeType();
2631 if (Ty->isReferenceType())
2632 return Owned(E);
2633 }
2634
John McCall86ff3082010-02-04 22:26:26 +00002635
2636 // That should be enough to guarantee that this type is complete.
2637 // If it has a trivial destructor, we can avoid the extra copy.
2638 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2639 if (RD->hasTrivialDestructor())
2640 return Owned(E);
2641
Mike Stump1eb44332009-09-09 15:08:12 +00002642 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00002643 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00002644 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002645 if (CXXDestructorDecl *Destructor =
John McCallc91cc662010-04-07 00:41:46 +00002646 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context))) {
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002647 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00002648 CheckDestructorAccess(E->getExprLoc(), Destructor,
2649 PDiag(diag::err_access_dtor_temp)
2650 << E->getType());
2651 }
Anders Carlssondef11992009-05-30 20:36:53 +00002652 // FIXME: Add the temporary to the temporaries vector.
2653 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2654}
2655
Anders Carlsson0ece4912009-12-15 20:51:39 +00002656Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002657 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002658
John McCall323ed742010-05-06 08:58:33 +00002659 // Check any implicit conversions within the expression.
2660 CheckImplicitConversions(SubExpr);
2661
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002662 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2663 assert(ExprTemporaries.size() >= FirstTemporary);
2664 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002665 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002666
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002667 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002668 &ExprTemporaries[FirstTemporary],
Anders Carlsson0ece4912009-12-15 20:51:39 +00002669 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002670 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2671 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002672
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002673 return E;
2674}
2675
Douglas Gregor90f93822009-12-22 22:17:25 +00002676Sema::OwningExprResult
2677Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2678 if (SubExpr.isInvalid())
2679 return ExprError();
2680
2681 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2682}
2683
Anders Carlsson5ee56e92009-12-16 02:09:40 +00002684FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2685 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2686 assert(ExprTemporaries.size() >= FirstTemporary);
2687
2688 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2689 CXXTemporary **Temporaries =
2690 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2691
2692 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2693
2694 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2695 ExprTemporaries.end());
2696
2697 return E;
2698}
2699
Mike Stump1eb44332009-09-09 15:08:12 +00002700Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002701Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
Douglas Gregord4dca082010-02-24 18:44:31 +00002702 tok::TokenKind OpKind, TypeTy *&ObjectType,
2703 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002704 // Since this might be a postfix expression, get rid of ParenListExprs.
2705 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002706
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002707 Expr *BaseExpr = (Expr*)Base.get();
2708 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002709
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002710 QualType BaseType = BaseExpr->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00002711 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002712 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002713 // If we have a pointer to a dependent type and are using the -> operator,
2714 // the object type is the type that the pointer points to. We might still
2715 // have enough information about that type to do something useful.
2716 if (OpKind == tok::arrow)
2717 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2718 BaseType = Ptr->getPointeeType();
2719
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002720 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregord4dca082010-02-24 18:44:31 +00002721 MayBePseudoDestructor = true;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002722 return move(Base);
2723 }
Mike Stump1eb44332009-09-09 15:08:12 +00002724
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002725 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002726 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002727 // returned, with the original second operand.
2728 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002729 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002730 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002731 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002732 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002733
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002734 while (BaseType->isRecordType()) {
Anders Carlsson15ea3782009-10-13 22:43:21 +00002735 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002736 BaseExpr = (Expr*)Base.get();
2737 if (BaseExpr == NULL)
2738 return ExprError();
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002739 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonde699e52009-10-13 22:55:59 +00002740 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc4e83212009-09-30 01:01:30 +00002741 BaseType = BaseExpr->getType();
2742 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002743 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002744 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002745 for (unsigned i = 0; i < Locations.size(); i++)
2746 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002747 return ExprError();
2748 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002749 }
Mike Stump1eb44332009-09-09 15:08:12 +00002750
Douglas Gregor31658df2009-11-20 19:58:21 +00002751 if (BaseType->isPointerType())
2752 BaseType = BaseType->getPointeeType();
2753 }
Mike Stump1eb44332009-09-09 15:08:12 +00002754
2755 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002756 // vector types or Objective-C interfaces. Just return early and let
2757 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002758 if (!BaseType->isRecordType()) {
2759 // C++ [basic.lookup.classref]p2:
2760 // [...] If the type of the object expression is of pointer to scalar
2761 // type, the unqualified-id is looked up in the context of the complete
2762 // postfix-expression.
Douglas Gregord4dca082010-02-24 18:44:31 +00002763 //
2764 // This also indicates that we should be parsing a
2765 // pseudo-destructor-name.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002766 ObjectType = 0;
Douglas Gregord4dca082010-02-24 18:44:31 +00002767 MayBePseudoDestructor = true;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002768 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002769 }
Mike Stump1eb44332009-09-09 15:08:12 +00002770
Douglas Gregor03c57052009-11-17 05:17:33 +00002771 // The object type must be complete (or dependent).
2772 if (!BaseType->isDependentType() &&
2773 RequireCompleteType(OpLoc, BaseType,
2774 PDiag(diag::err_incomplete_member_access)))
2775 return ExprError();
2776
Douglas Gregorc68afe22009-09-03 21:38:09 +00002777 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002778 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00002779 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00002780 // type C (or of pointer to a class type C), the unqualified-id is looked
2781 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002782 ObjectType = BaseType.getAsOpaquePtr();
Mike Stump1eb44332009-09-09 15:08:12 +00002783 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002784}
2785
Douglas Gregor77549082010-02-24 21:29:12 +00002786Sema::OwningExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
2787 ExprArg MemExpr) {
2788 Expr *E = (Expr *) MemExpr.get();
2789 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
2790 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2791 << isa<CXXPseudoDestructorExpr>(E)
Douglas Gregor849b2432010-03-31 17:46:05 +00002792 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
Douglas Gregor77549082010-02-24 21:29:12 +00002793
2794 return ActOnCallExpr(/*Scope*/ 0,
2795 move(MemExpr),
2796 /*LPLoc*/ ExpectedLParenLoc,
2797 Sema::MultiExprArg(*this, 0, 0),
2798 /*CommaLocs*/ 0,
2799 /*RPLoc*/ ExpectedLParenLoc);
2800}
Douglas Gregord4dca082010-02-24 18:44:31 +00002801
Douglas Gregorb57fb492010-02-24 22:38:50 +00002802Sema::OwningExprResult Sema::BuildPseudoDestructorExpr(ExprArg Base,
2803 SourceLocation OpLoc,
2804 tok::TokenKind OpKind,
2805 const CXXScopeSpec &SS,
Douglas Gregor26d4ac92010-02-24 23:40:28 +00002806 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002807 SourceLocation CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002808 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002809 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002810 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002811 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
Douglas Gregorb57fb492010-02-24 22:38:50 +00002812
2813 // C++ [expr.pseudo]p2:
2814 // The left-hand side of the dot operator shall be of scalar type. The
2815 // left-hand side of the arrow operator shall be of pointer to scalar type.
2816 // This scalar type is the object type.
2817 Expr *BaseE = (Expr *)Base.get();
2818 QualType ObjectType = BaseE->getType();
2819 if (OpKind == tok::arrow) {
2820 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2821 ObjectType = Ptr->getPointeeType();
2822 } else if (!BaseE->isTypeDependent()) {
2823 // The user wrote "p->" when she probably meant "p."; fix it.
2824 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2825 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00002826 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb57fb492010-02-24 22:38:50 +00002827 if (isSFINAEContext())
2828 return ExprError();
2829
2830 OpKind = tok::period;
2831 }
2832 }
2833
2834 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
2835 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2836 << ObjectType << BaseE->getSourceRange();
2837 return ExprError();
2838 }
2839
2840 // C++ [expr.pseudo]p2:
2841 // [...] The cv-unqualified versions of the object type and of the type
2842 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002843 if (DestructedTypeInfo) {
2844 QualType DestructedType = DestructedTypeInfo->getType();
2845 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002846 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002847 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
2848 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
2849 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
2850 << ObjectType << DestructedType << BaseE->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002851 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002852
2853 // Recover by setting the destructed type to the object type.
2854 DestructedType = ObjectType;
2855 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
2856 DestructedTypeStart);
2857 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2858 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00002859 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002860
Douglas Gregorb57fb492010-02-24 22:38:50 +00002861 // C++ [expr.pseudo]p2:
2862 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
2863 // form
2864 //
2865 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
2866 //
2867 // shall designate the same scalar type.
2868 if (ScopeTypeInfo) {
2869 QualType ScopeType = ScopeTypeInfo->getType();
2870 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00002871 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
Douglas Gregorb57fb492010-02-24 22:38:50 +00002872
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002873 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00002874 diag::err_pseudo_dtor_type_mismatch)
2875 << ObjectType << ScopeType << BaseE->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002876 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00002877
2878 ScopeType = QualType();
2879 ScopeTypeInfo = 0;
2880 }
2881 }
2882
2883 OwningExprResult Result
2884 = Owned(new (Context) CXXPseudoDestructorExpr(Context,
2885 Base.takeAs<Expr>(),
2886 OpKind == tok::arrow,
2887 OpLoc,
2888 (NestedNameSpecifier *) SS.getScopeRep(),
2889 SS.getRange(),
2890 ScopeTypeInfo,
2891 CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002892 TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002893 Destructed));
2894
Douglas Gregorb57fb492010-02-24 22:38:50 +00002895 if (HasTrailingLParen)
2896 return move(Result);
2897
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002898 return DiagnoseDtorReference(Destructed.getLocation(), move(Result));
Douglas Gregor77549082010-02-24 21:29:12 +00002899}
2900
2901Sema::OwningExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, ExprArg Base,
2902 SourceLocation OpLoc,
2903 tok::TokenKind OpKind,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002904 CXXScopeSpec &SS,
Douglas Gregor77549082010-02-24 21:29:12 +00002905 UnqualifiedId &FirstTypeName,
2906 SourceLocation CCLoc,
2907 SourceLocation TildeLoc,
2908 UnqualifiedId &SecondTypeName,
2909 bool HasTrailingLParen) {
2910 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2911 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2912 "Invalid first type name in pseudo-destructor");
2913 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2914 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2915 "Invalid second type name in pseudo-destructor");
2916
2917 Expr *BaseE = (Expr *)Base.get();
Douglas Gregor77549082010-02-24 21:29:12 +00002918
2919 // C++ [expr.pseudo]p2:
2920 // The left-hand side of the dot operator shall be of scalar type. The
2921 // left-hand side of the arrow operator shall be of pointer to scalar type.
2922 // This scalar type is the object type.
2923 QualType ObjectType = BaseE->getType();
2924 if (OpKind == tok::arrow) {
2925 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2926 ObjectType = Ptr->getPointeeType();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002927 } else if (!ObjectType->isDependentType()) {
Douglas Gregor77549082010-02-24 21:29:12 +00002928 // The user wrote "p->" when she probably meant "p."; fix it.
2929 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002930 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00002931 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor77549082010-02-24 21:29:12 +00002932 if (isSFINAEContext())
2933 return ExprError();
2934
2935 OpKind = tok::period;
2936 }
2937 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002938
2939 // Compute the object type that we should use for name lookup purposes. Only
2940 // record types and dependent types matter.
2941 void *ObjectTypePtrForLookup = 0;
2942 if (!SS.isSet()) {
Gabor Greif170e5082010-06-17 11:29:31 +00002943 ObjectTypePtrForLookup = const_cast<RecordType*>(
2944 ObjectType->getAs<RecordType>());
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002945 if (!ObjectTypePtrForLookup && ObjectType->isDependentType())
2946 ObjectTypePtrForLookup = Context.DependentTy.getAsOpaquePtr();
2947 }
Douglas Gregor77549082010-02-24 21:29:12 +00002948
Douglas Gregorb57fb492010-02-24 22:38:50 +00002949 // Convert the name of the type being destructed (following the ~) into a
2950 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00002951 QualType DestructedType;
2952 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002953 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00002954 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2955 TypeTy *T = getTypeName(*SecondTypeName.Identifier,
2956 SecondTypeName.StartLocation,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002957 S, &SS, true, ObjectTypePtrForLookup);
2958 if (!T &&
2959 ((SS.isSet() && !computeDeclContext(SS, false)) ||
2960 (!SS.isSet() && ObjectType->isDependentType()))) {
2961 // The name of the type being destroyed is a dependent name, and we
2962 // couldn't find anything useful in scope. Just store the identifier and
2963 // it's location, and we'll perform (qualified) name lookup again at
2964 // template instantiation time.
2965 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
2966 SecondTypeName.StartLocation);
2967 } else if (!T) {
Douglas Gregor77549082010-02-24 21:29:12 +00002968 Diag(SecondTypeName.StartLocation,
2969 diag::err_pseudo_dtor_destructor_non_type)
2970 << SecondTypeName.Identifier << ObjectType;
2971 if (isSFINAEContext())
2972 return ExprError();
2973
2974 // Recover by assuming we had the right type all along.
2975 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002976 } else
Douglas Gregor77549082010-02-24 21:29:12 +00002977 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002978 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00002979 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00002980 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002981 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2982 TemplateId->getTemplateArgs(),
2983 TemplateId->NumArgs);
2984 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2985 TemplateId->TemplateNameLoc,
2986 TemplateId->LAngleLoc,
2987 TemplateArgsPtr,
2988 TemplateId->RAngleLoc);
2989 if (T.isInvalid() || !T.get()) {
2990 // Recover by assuming we had the right type all along.
2991 DestructedType = ObjectType;
2992 } else
2993 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002994 }
2995
Douglas Gregorb57fb492010-02-24 22:38:50 +00002996 // If we've performed some kind of recovery, (re-)build the type source
2997 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002998 if (!DestructedType.isNull()) {
2999 if (!DestructedTypeInfo)
3000 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003001 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003002 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3003 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00003004
3005 // Convert the name of the scope type (the type prior to '::') into a type.
3006 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00003007 QualType ScopeType;
3008 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3009 FirstTypeName.Identifier) {
3010 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
3011 TypeTy *T = getTypeName(*FirstTypeName.Identifier,
3012 FirstTypeName.StartLocation,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003013 S, &SS, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00003014 if (!T) {
3015 Diag(FirstTypeName.StartLocation,
3016 diag::err_pseudo_dtor_destructor_non_type)
3017 << FirstTypeName.Identifier << ObjectType;
Douglas Gregor77549082010-02-24 21:29:12 +00003018
Douglas Gregorb57fb492010-02-24 22:38:50 +00003019 if (isSFINAEContext())
3020 return ExprError();
3021
3022 // Just drop this type. It's unnecessary anyway.
3023 ScopeType = QualType();
3024 } else
3025 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003026 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003027 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00003028 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003029 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3030 TemplateId->getTemplateArgs(),
3031 TemplateId->NumArgs);
3032 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
3033 TemplateId->TemplateNameLoc,
3034 TemplateId->LAngleLoc,
3035 TemplateArgsPtr,
3036 TemplateId->RAngleLoc);
3037 if (T.isInvalid() || !T.get()) {
3038 // Recover by dropping this type.
3039 ScopeType = QualType();
3040 } else
3041 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003042 }
3043 }
Douglas Gregorb4a418f2010-02-24 23:02:30 +00003044
3045 if (!ScopeType.isNull() && !ScopeTypeInfo)
3046 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
3047 FirstTypeName.StartLocation);
3048
3049
Douglas Gregorb57fb492010-02-24 22:38:50 +00003050 return BuildPseudoDestructorExpr(move(Base), OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00003051 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003052 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00003053}
3054
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003055CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
John McCall6bb80172010-03-30 21:47:33 +00003056 NamedDecl *FoundDecl,
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003057 CXXMethodDecl *Method) {
John McCall6bb80172010-03-30 21:47:33 +00003058 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
3059 FoundDecl, Method))
Eli Friedman772fffa2009-12-09 04:53:56 +00003060 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
3061
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003062 MemberExpr *ME =
3063 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
3064 SourceLocation(), Method->getType());
Eli Friedman772fffa2009-12-09 04:53:56 +00003065 QualType ResultType = Method->getResultType().getNonReferenceType();
Douglas Gregor7edfb692009-11-23 12:27:39 +00003066 MarkDeclarationReferenced(Exp->getLocStart(), Method);
3067 CXXMemberCallExpr *CE =
3068 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
3069 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003070 return CE;
3071}
3072
Anders Carlsson165a0a02009-05-17 18:41:29 +00003073Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
3074 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003075 if (FullExpr)
Anders Carlsson0ece4912009-12-15 20:51:39 +00003076 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Douglas Gregoreecf38f2010-05-06 21:39:56 +00003077 else
3078 return ExprError();
3079
Anders Carlsson165a0a02009-05-17 18:41:29 +00003080 return Owned(FullExpr);
3081}