blob: 97300f7d63e152a34bd2e6419f0bd4d3abd59c97 [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()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000724 QualType SizeType = ArraySize->getType();
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000725 if (!SizeType->isIntegralOrEnumerationType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000726 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
727 diag::err_array_size_not_integral)
728 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000729 // Let's see if this is a constant < 0. If so, we reject it out of hand.
730 // We don't care about special rules, so we tell the machinery it's not
731 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000732 if (!ArraySize->isValueDependent()) {
733 llvm::APSInt Value;
734 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
735 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000736 llvm::APInt::getNullValue(Value.getBitWidth()),
737 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000738 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
739 diag::err_typecheck_negative_array_size)
740 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000741 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000742 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000743
Eli Friedman73c39ab2009-10-20 08:27:19 +0000744 ImpCastExprToType(ArraySize, Context.getSizeType(),
745 CastExpr::CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000746 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000747
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000748 FunctionDecl *OperatorNew = 0;
749 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000750 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
751 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000752
Sebastian Redl28507842009-02-26 14:39:58 +0000753 if (!AllocType->isDependentType() &&
754 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
755 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000756 SourceRange(PlacementLParen, PlacementRParen),
757 UseGlobal, AllocType, ArraySize, PlaceArgs,
758 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000759 return ExprError();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000760 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000761 if (OperatorNew) {
762 // Add default arguments, if any.
763 const FunctionProtoType *Proto =
764 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000765 VariadicCallType CallType =
766 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Anders Carlsson28e94832010-05-03 02:07:56 +0000767
768 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
769 Proto, 1, PlaceArgs, NumPlaceArgs,
770 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000771 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000772
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000773 NumPlaceArgs = AllPlaceArgs.size();
774 if (NumPlaceArgs > 0)
775 PlaceArgs = &AllPlaceArgs[0];
776 }
777
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000778 bool Init = ConstructorLParen.isValid();
779 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000780 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000781 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
782 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000783 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
784
Anders Carlsson48c95012010-05-03 15:45:23 +0000785 // Array 'new' can't have any initializers.
Anders Carlsson55cbd6e2010-05-16 16:24:20 +0000786 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlsson48c95012010-05-03 15:45:23 +0000787 SourceRange InitRange(ConsArgs[0]->getLocStart(),
788 ConsArgs[NumConsArgs - 1]->getLocEnd());
789
790 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
791 return ExprError();
792 }
793
Douglas Gregor99a2e602009-12-16 01:38:02 +0000794 if (!AllocType->isDependentType() &&
795 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
796 // C++0x [expr.new]p15:
797 // A new-expression that creates an object of type T initializes that
798 // object as follows:
799 InitializationKind Kind
800 // - If the new-initializer is omitted, the object is default-
801 // initialized (8.5); if no initialization is performed,
802 // the object has indeterminate value
803 = !Init? InitializationKind::CreateDefault(TypeLoc)
804 // - Otherwise, the new-initializer is interpreted according to the
805 // initialization rules of 8.5 for direct-initialization.
806 : InitializationKind::CreateDirect(TypeLoc,
807 ConstructorLParen,
808 ConstructorRParen);
809
Douglas Gregor99a2e602009-12-16 01:38:02 +0000810 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +0000811 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000812 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000813 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
814 move(ConstructorArgs));
815 if (FullInit.isInvalid())
816 return ExprError();
817
818 // FullInit is our initializer; walk through it to determine if it's a
819 // constructor call, which CXXNewExpr handles directly.
820 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
821 if (CXXBindTemporaryExpr *Binder
822 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
823 FullInitExpr = Binder->getSubExpr();
824 if (CXXConstructExpr *Construct
825 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
826 Constructor = Construct->getConstructor();
827 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
828 AEnd = Construct->arg_end();
829 A != AEnd; ++A)
830 ConvertedConstructorArgs.push_back(A->Retain());
831 } else {
832 // Take the converted initializer.
833 ConvertedConstructorArgs.push_back(FullInit.release());
834 }
835 } else {
836 // No initialization required.
837 }
838
839 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +0000840 NumConsArgs = ConvertedConstructorArgs.size();
841 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000842 }
Douglas Gregor99a2e602009-12-16 01:38:02 +0000843
Douglas Gregor6d908702010-02-26 05:06:18 +0000844 // Mark the new and delete operators as referenced.
845 if (OperatorNew)
846 MarkDeclarationReferenced(StartLoc, OperatorNew);
847 if (OperatorDelete)
848 MarkDeclarationReferenced(StartLoc, OperatorDelete);
849
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000850 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000851
Sebastian Redlf53597f2009-03-15 17:47:39 +0000852 PlacementArgs.release();
853 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000854 ArraySizeE.release();
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000855
856 // FIXME: The TypeSourceInfo should also be included in CXXNewExpr.
Ted Kremenekad7fe862010-02-11 22:51:03 +0000857 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
858 PlaceArgs, NumPlaceArgs, ParenTypeId,
859 ArraySize, Constructor, Init,
860 ConsArgs, NumConsArgs, OperatorDelete,
861 ResultType, StartLoc,
862 Init ? ConstructorRParen :
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000863 TypeRange.getEnd()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000864}
865
866/// CheckAllocatedType - Checks that a type is suitable as the allocated type
867/// in a new-expression.
868/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000869bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000870 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000871 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
872 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000873 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000874 return Diag(Loc, diag::err_bad_new_type)
875 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000876 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000877 return Diag(Loc, diag::err_bad_new_type)
878 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000879 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000880 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000881 PDiag(diag::err_new_incomplete_type)
882 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000883 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000884 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000885 diag::err_allocation_of_abstract_type))
886 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000887
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000888 return false;
889}
890
Douglas Gregor6d908702010-02-26 05:06:18 +0000891/// \brief Determine whether the given function is a non-placement
892/// deallocation function.
893static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
894 if (FD->isInvalidDecl())
895 return false;
896
897 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
898 return Method->isUsualDeallocationFunction();
899
900 return ((FD->getOverloadedOperator() == OO_Delete ||
901 FD->getOverloadedOperator() == OO_Array_Delete) &&
902 FD->getNumParams() == 1);
903}
904
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000905/// FindAllocationFunctions - Finds the overloads of operator new and delete
906/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000907bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
908 bool UseGlobal, QualType AllocType,
909 bool IsArray, Expr **PlaceArgs,
910 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000911 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000912 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000913 // --- Choosing an allocation function ---
914 // C++ 5.3.4p8 - 14 & 18
915 // 1) If UseGlobal is true, only look in the global scope. Else, also look
916 // in the scope of the allocated class.
917 // 2) If an array size is given, look for operator new[], else look for
918 // operator new.
919 // 3) The first argument is always size_t. Append the arguments from the
920 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000921
922 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
923 // We don't care about the actual value of this argument.
924 // FIXME: Should the Sema create the expression and embed it in the syntax
925 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000926 IntegerLiteral Size(llvm::APInt::getNullValue(
927 Context.Target.getPointerWidth(0)),
928 Context.getSizeType(),
929 SourceLocation());
930 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000931 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
932
Douglas Gregor6d908702010-02-26 05:06:18 +0000933 // C++ [expr.new]p8:
934 // If the allocated type is a non-array type, the allocation
935 // function’s name is operator new and the deallocation function’s
936 // name is operator delete. If the allocated type is an array
937 // type, the allocation function’s name is operator new[] and the
938 // deallocation function’s name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000939 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
940 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +0000941 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
942 IsArray ? OO_Array_Delete : OO_Delete);
943
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000944 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000945 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000946 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +0000947 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000948 AllocArgs.size(), Record, /*AllowMissing=*/true,
949 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000950 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000951 }
952 if (!OperatorNew) {
953 // Didn't find a member overload. Look for a global one.
954 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000955 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000956 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000957 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
958 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000959 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000960 }
961
John McCall9c82afc2010-04-20 02:18:25 +0000962 // We don't need an operator delete if we're running under
963 // -fno-exceptions.
964 if (!getLangOptions().Exceptions) {
965 OperatorDelete = 0;
966 return false;
967 }
968
Anders Carlssond9583892009-05-31 20:26:12 +0000969 // FindAllocationOverload can change the passed in arguments, so we need to
970 // copy them back.
971 if (NumPlaceArgs > 0)
972 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000973
Douglas Gregor6d908702010-02-26 05:06:18 +0000974 // C++ [expr.new]p19:
975 //
976 // If the new-expression begins with a unary :: operator, the
977 // deallocation function’s name is looked up in the global
978 // scope. Otherwise, if the allocated type is a class type T or an
979 // array thereof, the deallocation function’s name is looked up in
980 // the scope of T. If this lookup fails to find the name, or if
981 // the allocated type is not a class type or array thereof, the
982 // deallocation function’s name is looked up in the global scope.
983 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
984 if (AllocType->isRecordType() && !UseGlobal) {
985 CXXRecordDecl *RD
986 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
987 LookupQualifiedName(FoundDelete, RD);
988 }
John McCall90c8c572010-03-18 08:19:33 +0000989 if (FoundDelete.isAmbiguous())
990 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +0000991
992 if (FoundDelete.empty()) {
993 DeclareGlobalNewDelete();
994 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
995 }
996
997 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +0000998
999 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1000
John McCall90c8c572010-03-18 08:19:33 +00001001 if (NumPlaceArgs > 0) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001002 // C++ [expr.new]p20:
1003 // A declaration of a placement deallocation function matches the
1004 // declaration of a placement allocation function if it has the
1005 // same number of parameters and, after parameter transformations
1006 // (8.3.5), all parameter types except the first are
1007 // identical. [...]
1008 //
1009 // To perform this comparison, we compute the function type that
1010 // the deallocation function should have, and use that type both
1011 // for template argument deduction and for comparison purposes.
1012 QualType ExpectedFunctionType;
1013 {
1014 const FunctionProtoType *Proto
1015 = OperatorNew->getType()->getAs<FunctionProtoType>();
1016 llvm::SmallVector<QualType, 4> ArgTypes;
1017 ArgTypes.push_back(Context.VoidPtrTy);
1018 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1019 ArgTypes.push_back(Proto->getArgType(I));
1020
1021 ExpectedFunctionType
1022 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
1023 ArgTypes.size(),
1024 Proto->isVariadic(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001025 0, false, false, 0, 0,
1026 FunctionType::ExtInfo());
Douglas Gregor6d908702010-02-26 05:06:18 +00001027 }
1028
1029 for (LookupResult::iterator D = FoundDelete.begin(),
1030 DEnd = FoundDelete.end();
1031 D != DEnd; ++D) {
1032 FunctionDecl *Fn = 0;
1033 if (FunctionTemplateDecl *FnTmpl
1034 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1035 // Perform template argument deduction to try to match the
1036 // expected function type.
1037 TemplateDeductionInfo Info(Context, StartLoc);
1038 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1039 continue;
1040 } else
1041 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1042
1043 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001044 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001045 }
1046 } else {
1047 // C++ [expr.new]p20:
1048 // [...] Any non-placement deallocation function matches a
1049 // non-placement allocation function. [...]
1050 for (LookupResult::iterator D = FoundDelete.begin(),
1051 DEnd = FoundDelete.end();
1052 D != DEnd; ++D) {
1053 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1054 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001055 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001056 }
1057 }
1058
1059 // C++ [expr.new]p20:
1060 // [...] If the lookup finds a single matching deallocation
1061 // function, that function will be called; otherwise, no
1062 // deallocation function will be called.
1063 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001064 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001065
1066 // C++0x [expr.new]p20:
1067 // If the lookup finds the two-parameter form of a usual
1068 // deallocation function (3.7.4.2) and that function, considered
1069 // as a placement deallocation function, would have been
1070 // selected as a match for the allocation function, the program
1071 // is ill-formed.
1072 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1073 isNonPlacementDeallocationFunction(OperatorDelete)) {
1074 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1075 << SourceRange(PlaceArgs[0]->getLocStart(),
1076 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1077 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1078 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001079 } else {
1080 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001081 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001082 }
1083 }
1084
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001085 return false;
1086}
1087
Sebastian Redl7f662392008-12-04 22:20:51 +00001088/// FindAllocationOverload - Find an fitting overload for the allocation
1089/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001090bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1091 DeclarationName Name, Expr** Args,
1092 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +00001093 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001094 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1095 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001096 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001097 if (AllowMissing)
1098 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001099 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001100 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001101 }
1102
John McCall90c8c572010-03-18 08:19:33 +00001103 if (R.isAmbiguous())
1104 return true;
1105
1106 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001107
John McCall5769d612010-02-08 23:07:23 +00001108 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001109 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1110 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001111 // Even member operator new/delete are implicitly treated as
1112 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001113 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001114
John McCall9aa472c2010-03-19 07:35:19 +00001115 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1116 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001117 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1118 Candidates,
1119 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001120 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001121 }
1122
John McCall9aa472c2010-03-19 07:35:19 +00001123 FunctionDecl *Fn = cast<FunctionDecl>(D);
1124 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001125 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001126 }
1127
1128 // Do the resolution.
1129 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001130 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001131 case OR_Success: {
1132 // Got one!
1133 FunctionDecl *FnDecl = Best->Function;
1134 // The first argument is size_t, and the first parameter must be size_t,
1135 // too. This is checked on declaration and can be assumed. (It can't be
1136 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001137 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001138 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1139 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001140 OwningExprResult Result
1141 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
1142 FnDecl->getParamDecl(i)),
1143 SourceLocation(),
1144 Owned(Args[i]->Retain()));
1145 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001146 return true;
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001147
1148 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001149 }
1150 Operator = FnDecl;
John McCall9aa472c2010-03-19 07:35:19 +00001151 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001152 return false;
1153 }
1154
1155 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +00001156 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001157 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001158 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001159 return true;
1160
1161 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +00001162 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +00001163 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001164 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001165 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001166
1167 case OR_Deleted:
1168 Diag(StartLoc, diag::err_ovl_deleted_call)
1169 << Best->Function->isDeleted()
1170 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001171 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001172 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001173 }
1174 assert(false && "Unreachable, bad result from BestViableFunction");
1175 return true;
1176}
1177
1178
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001179/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1180/// delete. These are:
1181/// @code
1182/// void* operator new(std::size_t) throw(std::bad_alloc);
1183/// void* operator new[](std::size_t) throw(std::bad_alloc);
1184/// void operator delete(void *) throw();
1185/// void operator delete[](void *) throw();
1186/// @endcode
1187/// Note that the placement and nothrow forms of new are *not* implicitly
1188/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001189void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001190 if (GlobalNewDeleteDeclared)
1191 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001192
1193 // C++ [basic.std.dynamic]p2:
1194 // [...] The following allocation and deallocation functions (18.4) are
1195 // implicitly declared in global scope in each translation unit of a
1196 // program
1197 //
1198 // void* operator new(std::size_t) throw(std::bad_alloc);
1199 // void* operator new[](std::size_t) throw(std::bad_alloc);
1200 // void operator delete(void*) throw();
1201 // void operator delete[](void*) throw();
1202 //
1203 // These implicit declarations introduce only the function names operator
1204 // new, operator new[], operator delete, operator delete[].
1205 //
1206 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1207 // "std" or "bad_alloc" as necessary to form the exception specification.
1208 // However, we do not make these implicit declarations visible to name
1209 // lookup.
1210 if (!StdNamespace) {
1211 // The "std" namespace has not yet been defined, so build one implicitly.
1212 StdNamespace = NamespaceDecl::Create(Context,
1213 Context.getTranslationUnitDecl(),
1214 SourceLocation(),
1215 &PP.getIdentifierTable().get("std"));
1216 StdNamespace->setImplicit(true);
1217 }
1218
1219 if (!StdBadAlloc) {
1220 // The "std::bad_alloc" class has not yet been declared, so build it
1221 // implicitly.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001222 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001223 StdNamespace,
1224 SourceLocation(),
1225 &PP.getIdentifierTable().get("bad_alloc"),
1226 SourceLocation(), 0);
1227 StdBadAlloc->setImplicit(true);
1228 }
1229
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001230 GlobalNewDeleteDeclared = true;
1231
1232 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1233 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001234 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001235
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001236 DeclareGlobalAllocationFunction(
1237 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001238 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001239 DeclareGlobalAllocationFunction(
1240 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001241 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001242 DeclareGlobalAllocationFunction(
1243 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1244 Context.VoidTy, VoidPtr);
1245 DeclareGlobalAllocationFunction(
1246 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1247 Context.VoidTy, VoidPtr);
1248}
1249
1250/// DeclareGlobalAllocationFunction - Declares a single implicit global
1251/// allocation function if it doesn't already exist.
1252void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001253 QualType Return, QualType Argument,
1254 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001255 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1256
1257 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001258 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001259 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001260 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001261 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001262 // Only look at non-template functions, as it is the predefined,
1263 // non-templated allocation function we are trying to declare here.
1264 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1265 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001266 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001267 Func->getParamDecl(0)->getType().getUnqualifiedType());
1268 // FIXME: Do we need to check for default arguments here?
1269 if (Func->getNumParams() == 1 && InitialParamType == Argument)
1270 return;
1271 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001272 }
1273 }
1274
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001275 QualType BadAllocType;
1276 bool HasBadAllocExceptionSpec
1277 = (Name.getCXXOverloadedOperator() == OO_New ||
1278 Name.getCXXOverloadedOperator() == OO_Array_New);
1279 if (HasBadAllocExceptionSpec) {
1280 assert(StdBadAlloc && "Must have std::bad_alloc declared");
1281 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
1282 }
1283
1284 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1285 true, false,
1286 HasBadAllocExceptionSpec? 1 : 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00001287 &BadAllocType,
1288 FunctionType::ExtInfo());
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001289 FunctionDecl *Alloc =
1290 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001291 FnType, /*TInfo=*/0, FunctionDecl::None,
1292 FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001293 Alloc->setImplicit();
Nuno Lopesfc284482009-12-16 16:59:22 +00001294
1295 if (AddMallocAttr)
1296 Alloc->addAttr(::new (Context) MallocAttr());
1297
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001298 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00001299 0, Argument, /*TInfo=*/0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001300 VarDecl::None,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001301 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00001302 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001303
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001304 // FIXME: Also add this declaration to the IdentifierResolver, but
1305 // make sure it is at the end of the chain to coincide with the
1306 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001307 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001308}
1309
Anders Carlsson78f74552009-11-15 18:45:20 +00001310bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1311 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00001312 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001313 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001314 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001315 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +00001316
John McCalla24dc2e2009-11-17 02:14:36 +00001317 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001318 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001319
Chandler Carruth23893242010-06-28 00:30:51 +00001320 Found.suppressDiagnostics();
1321
Anders Carlsson78f74552009-11-15 18:45:20 +00001322 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1323 F != FEnd; ++F) {
1324 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
1325 if (Delete->isUsualDeallocationFunction()) {
1326 Operator = Delete;
Chandler Carruth23893242010-06-28 00:30:51 +00001327 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1328 F.getPair());
Anders Carlsson78f74552009-11-15 18:45:20 +00001329 return false;
1330 }
1331 }
1332
1333 // We did find operator delete/operator delete[] declarations, but
1334 // none of them were suitable.
1335 if (!Found.empty()) {
1336 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1337 << Name << RD;
1338
1339 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1340 F != FEnd; ++F) {
Douglas Gregorb0fd4832010-04-25 20:55:08 +00001341 Diag((*F)->getLocation(), diag::note_member_declared_here)
Anders Carlsson78f74552009-11-15 18:45:20 +00001342 << Name;
1343 }
1344
1345 return true;
1346 }
1347
1348 // Look for a global declaration.
1349 DeclareGlobalNewDelete();
1350 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1351
1352 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1353 Expr* DeallocArgs[1];
1354 DeallocArgs[0] = &Null;
1355 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1356 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1357 Operator))
1358 return true;
1359
1360 assert(Operator && "Did not find a deallocation function!");
1361 return false;
1362}
1363
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001364/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1365/// @code ::delete ptr; @endcode
1366/// or
1367/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +00001368Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001369Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +00001370 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001371 // C++ [expr.delete]p1:
1372 // The operand shall have a pointer type, or a class type having a single
1373 // conversion function to a pointer type. The result has type void.
1374 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001375 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1376
Anders Carlssond67c4c32009-08-16 20:29:29 +00001377 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001378
Sebastian Redlf53597f2009-03-15 17:47:39 +00001379 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +00001380 if (!Ex->isTypeDependent()) {
1381 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001382
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001383 if (const RecordType *Record = Type->getAs<RecordType>()) {
John McCall32daa422010-03-31 01:36:47 +00001384 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1385
Fariborz Jahanian53462782009-09-11 21:44:33 +00001386 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCall32daa422010-03-31 01:36:47 +00001387 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001388 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001389 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001390 NamedDecl *D = I.getDecl();
1391 if (isa<UsingShadowDecl>(D))
1392 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1393
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001394 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001395 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001396 continue;
1397
John McCall32daa422010-03-31 01:36:47 +00001398 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001399
1400 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1401 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1402 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001403 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001404 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001405 if (ObjectPtrConversions.size() == 1) {
1406 // We have a single conversion to a pointer-to-object type. Perform
1407 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001408 // TODO: don't redo the conversion calculation.
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001409 Operand.release();
John McCall32daa422010-03-31 01:36:47 +00001410 if (!PerformImplicitConversion(Ex,
1411 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +00001412 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001413 Operand = Owned(Ex);
1414 Type = Ex->getType();
1415 }
1416 }
1417 else if (ObjectPtrConversions.size() > 1) {
1418 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1419 << Type << Ex->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001420 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1421 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001422 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001423 }
Sebastian Redl28507842009-02-26 14:39:58 +00001424 }
1425
Sebastian Redlf53597f2009-03-15 17:47:39 +00001426 if (!Type->isPointerType())
1427 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1428 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001429
Ted Kremenek6217b802009-07-29 21:53:49 +00001430 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor94a61572010-05-24 17:01:56 +00001431 if (Pointee->isVoidType() && !isSFINAEContext()) {
1432 // The C++ standard bans deleting a pointer to a non-object type, which
1433 // effectively bans deletion of "void*". However, most compilers support
1434 // this, so we treat it as a warning unless we're in a SFINAE context.
1435 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1436 << Type << Ex->getSourceRange();
1437 } else if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001438 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1439 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001440 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001441 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +00001442 PDiag(diag::warn_delete_incomplete)
1443 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001444 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +00001445
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001446 // C++ [expr.delete]p2:
1447 // [Note: a pointer to a const type can be the operand of a
1448 // delete-expression; it is not necessary to cast away the constness
1449 // (5.2.11) of the pointer expression before it is used as the operand
1450 // of the delete-expression. ]
1451 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
1452 CastExpr::CK_NoOp);
1453
1454 // Update the operand.
1455 Operand.take();
1456 Operand = ExprArg(*this, Ex);
1457
Anders Carlssond67c4c32009-08-16 20:29:29 +00001458 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1459 ArrayForm ? OO_Array_Delete : OO_Delete);
1460
Anders Carlsson78f74552009-11-15 18:45:20 +00001461 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
1462 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1463
1464 if (!UseGlobal &&
1465 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001466 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001467
Anders Carlsson78f74552009-11-15 18:45:20 +00001468 if (!RD->hasTrivialDestructor())
1469 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001470 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001471 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +00001472 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001473
Anders Carlssond67c4c32009-08-16 20:29:29 +00001474 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001475 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001476 DeclareGlobalNewDelete();
1477 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001478 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +00001479 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001480 OperatorDelete))
1481 return ExprError();
1482 }
Mike Stump1eb44332009-09-09 15:08:12 +00001483
John McCall9c82afc2010-04-20 02:18:25 +00001484 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1485
Sebastian Redl28507842009-02-26 14:39:58 +00001486 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001487 }
1488
Sebastian Redlf53597f2009-03-15 17:47:39 +00001489 Operand.release();
1490 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001491 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001492}
1493
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001494/// \brief Check the use of the given variable as a C++ condition in an if,
1495/// while, do-while, or switch statement.
Douglas Gregor586596f2010-05-06 17:25:47 +00001496Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
1497 SourceLocation StmtLoc,
1498 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001499 QualType T = ConditionVar->getType();
1500
1501 // C++ [stmt.select]p2:
1502 // The declarator shall not specify a function or an array.
1503 if (T->isFunctionType())
1504 return ExprError(Diag(ConditionVar->getLocation(),
1505 diag::err_invalid_use_of_function_type)
1506 << ConditionVar->getSourceRange());
1507 else if (T->isArrayType())
1508 return ExprError(Diag(ConditionVar->getLocation(),
1509 diag::err_invalid_use_of_array_type)
1510 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001511
Douglas Gregor586596f2010-05-06 17:25:47 +00001512 Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1513 ConditionVar->getLocation(),
1514 ConditionVar->getType().getNonReferenceType());
1515 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc)) {
1516 Condition->Destroy(Context);
1517 return ExprError();
1518 }
1519
1520 return Owned(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001521}
1522
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001523/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1524bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1525 // C++ 6.4p4:
1526 // The value of a condition that is an initialized declaration in a statement
1527 // other than a switch statement is the value of the declared variable
1528 // implicitly converted to type bool. If that conversion is ill-formed, the
1529 // program is ill-formed.
1530 // The value of a condition that is an expression is the value of the
1531 // expression, implicitly converted to bool.
1532 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001533 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001534}
Douglas Gregor77a52232008-09-12 00:47:35 +00001535
1536/// Helper function to determine whether this is the (deprecated) C++
1537/// conversion from a string literal to a pointer to non-const char or
1538/// non-const wchar_t (for narrow and wide string literals,
1539/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001540bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001541Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1542 // Look inside the implicit cast, if it exists.
1543 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1544 From = Cast->getSubExpr();
1545
1546 // A string literal (2.13.4) that is not a wide string literal can
1547 // be converted to an rvalue of type "pointer to char"; a wide
1548 // string literal can be converted to an rvalue of type "pointer
1549 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00001550 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00001551 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001552 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001553 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001554 // This conversion is considered only when there is an
1555 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001556 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001557 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1558 (!StrLit->isWide() &&
1559 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1560 ToPointeeType->getKind() == BuiltinType::Char_S))))
1561 return true;
1562 }
1563
1564 return false;
1565}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001566
Douglas Gregorba70ab62010-04-16 22:17:36 +00001567static Sema::OwningExprResult BuildCXXCastArgument(Sema &S,
1568 SourceLocation CastLoc,
1569 QualType Ty,
1570 CastExpr::CastKind Kind,
1571 CXXMethodDecl *Method,
1572 Sema::ExprArg Arg) {
1573 Expr *From = Arg.takeAs<Expr>();
1574
1575 switch (Kind) {
1576 default: assert(0 && "Unhandled cast kind!");
1577 case CastExpr::CK_ConstructorConversion: {
1578 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
1579
1580 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
1581 Sema::MultiExprArg(S, (void **)&From, 1),
1582 CastLoc, ConstructorArgs))
1583 return S.ExprError();
1584
1585 Sema::OwningExprResult Result =
1586 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
1587 move_arg(ConstructorArgs));
1588 if (Result.isInvalid())
1589 return S.ExprError();
1590
1591 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1592 }
1593
1594 case CastExpr::CK_UserDefinedConversion: {
1595 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1596
1597 // Create an implicit call expr that calls it.
1598 // FIXME: pass the FoundDecl for the user-defined conversion here
1599 CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method);
1600 return S.MaybeBindToTemporary(CE);
1601 }
1602 }
1603}
1604
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001605/// PerformImplicitConversion - Perform an implicit conversion of the
1606/// expression From to the type ToType using the pre-computed implicit
1607/// conversion sequence ICS. Returns true if there was an error, false
1608/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001609/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001610/// used in the error message.
1611bool
1612Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1613 const ImplicitConversionSequence &ICS,
Douglas Gregor68647482009-12-16 03:45:30 +00001614 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall1d318332010-01-12 00:44:57 +00001615 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001616 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001617 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001618 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001619 return true;
1620 break;
1621
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001622 case ImplicitConversionSequence::UserDefinedConversion: {
1623
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001624 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1625 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001626 QualType BeforeToType;
1627 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001628 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001629
1630 // If the user-defined conversion is specified by a conversion function,
1631 // the initial standard conversion sequence converts the source type to
1632 // the implicit object parameter of the conversion function.
1633 BeforeToType = Context.getTagDeclType(Conv->getParent());
1634 } else if (const CXXConstructorDecl *Ctor =
1635 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001636 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001637 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001638 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001639 // If the user-defined conversion is specified by a constructor, the
1640 // initial standard conversion sequence converts the source type to the
1641 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001642 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1643 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001644 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001645 else
1646 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001647 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001648 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001649 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001650 ICS.UserDefined.Before, AA_Converting,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001651 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001652 return true;
1653 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001654
Anders Carlsson0aebc812009-09-09 21:33:21 +00001655 OwningExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00001656 = BuildCXXCastArgument(*this,
1657 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00001658 ToType.getNonReferenceType(),
1659 CastKind, cast<CXXMethodDecl>(FD),
1660 Owned(From));
1661
1662 if (CastArg.isInvalid())
1663 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001664
1665 From = CastArg.takeAs<Expr>();
1666
Eli Friedmand8889622009-11-27 04:41:50 +00001667 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor68647482009-12-16 03:45:30 +00001668 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001669 }
John McCall1d318332010-01-12 00:44:57 +00001670
1671 case ImplicitConversionSequence::AmbiguousConversion:
1672 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1673 PDiag(diag::err_typecheck_ambiguous_condition)
1674 << From->getSourceRange());
1675 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001676
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001677 case ImplicitConversionSequence::EllipsisConversion:
1678 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001679 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001680
1681 case ImplicitConversionSequence::BadConversion:
1682 return true;
1683 }
1684
1685 // Everything went well.
1686 return false;
1687}
1688
1689/// PerformImplicitConversion - Perform an implicit conversion of the
1690/// expression From to the type ToType by following the standard
1691/// conversion sequence SCS. Returns true if there was an error, false
1692/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001693/// expression. Flavor is the context in which we're performing this
1694/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001695bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001696Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001697 const StandardConversionSequence& SCS,
Douglas Gregor68647482009-12-16 03:45:30 +00001698 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001699 // Overall FIXME: we are recomputing too many types here and doing far too
1700 // much extra work. What this means is that we need to keep track of more
1701 // information that is computed when we try the implicit conversion initially,
1702 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001703 QualType FromType = From->getType();
1704
Douglas Gregor225c41e2008-11-03 19:09:14 +00001705 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001706 // FIXME: When can ToType be a reference type?
1707 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001708 if (SCS.Second == ICK_Derived_To_Base) {
1709 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1710 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1711 MultiExprArg(*this, (void **)&From, 1),
1712 /*FIXME:ConstructLoc*/SourceLocation(),
1713 ConstructorArgs))
1714 return true;
1715 OwningExprResult FromResult =
1716 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1717 ToType, SCS.CopyConstructor,
1718 move_arg(ConstructorArgs));
1719 if (FromResult.isInvalid())
1720 return true;
1721 From = FromResult.takeAs<Expr>();
1722 return false;
1723 }
Mike Stump1eb44332009-09-09 15:08:12 +00001724 OwningExprResult FromResult =
1725 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1726 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001727 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001728
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001729 if (FromResult.isInvalid())
1730 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001731
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001732 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001733 return false;
1734 }
1735
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001736 // Resolve overloaded function references.
1737 if (Context.hasSameType(FromType, Context.OverloadTy)) {
1738 DeclAccessPair Found;
1739 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1740 true, Found);
1741 if (!Fn)
1742 return true;
1743
1744 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1745 return true;
1746
1747 From = FixOverloadedFunctionReference(From, Found, Fn);
1748 FromType = From->getType();
1749 }
1750
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001751 // Perform the first implicit conversion.
1752 switch (SCS.First) {
1753 case ICK_Identity:
1754 case ICK_Lvalue_To_Rvalue:
1755 // Nothing to do.
1756 break;
1757
1758 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001759 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001760 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001761 break;
1762
1763 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001764 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001765 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001766 break;
1767
1768 default:
1769 assert(false && "Improper first standard conversion");
1770 break;
1771 }
1772
1773 // Perform the second implicit conversion
1774 switch (SCS.Second) {
1775 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001776 // If both sides are functions (or pointers/references to them), there could
1777 // be incompatible exception declarations.
1778 if (CheckExceptionSpecCompatibility(From, ToType))
1779 return true;
1780 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001781 break;
1782
Douglas Gregor43c79c22009-12-09 00:47:37 +00001783 case ICK_NoReturn_Adjustment:
1784 // If both sides are functions (or pointers/references to them), there could
1785 // be incompatible exception declarations.
1786 if (CheckExceptionSpecCompatibility(From, ToType))
1787 return true;
1788
1789 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1790 CastExpr::CK_NoOp);
1791 break;
1792
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001793 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001794 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001795 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1796 break;
1797
1798 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001799 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001800 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1801 break;
1802
1803 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001804 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001805 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1806 break;
1807
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001808 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001809 if (ToType->isRealFloatingType())
Eli Friedman73c39ab2009-10-20 08:27:19 +00001810 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1811 else
1812 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1813 break;
1814
Douglas Gregorf9201e02009-02-11 23:02:49 +00001815 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001816 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001817 break;
1818
Anders Carlsson61faec12009-09-12 04:46:44 +00001819 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001820 if (SCS.IncompatibleObjC) {
1821 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001822 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001823 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00001824 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00001825 << From->getSourceRange();
1826 }
1827
Anders Carlsson61faec12009-09-12 04:46:44 +00001828
1829 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001830 CXXBaseSpecifierArray BasePath;
1831 if (CheckPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001832 return true;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001833 ImpCastExprToType(From, ToType, Kind, /*isLvalue=*/false, BasePath);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001834 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001835 }
1836
1837 case ICK_Pointer_Member: {
1838 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001839 CXXBaseSpecifierArray BasePath;
1840 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath,
1841 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001842 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001843 if (CheckExceptionSpecCompatibility(From, ToType))
1844 return true;
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001845 ImpCastExprToType(From, ToType, Kind, /*isLvalue=*/false, BasePath);
Anders Carlsson61faec12009-09-12 04:46:44 +00001846 break;
1847 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001848 case ICK_Boolean_Conversion: {
1849 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1850 if (FromType->isMemberPointerType())
1851 Kind = CastExpr::CK_MemberPointerToBoolean;
1852
1853 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001854 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001855 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001856
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001857 case ICK_Derived_To_Base: {
1858 CXXBaseSpecifierArray BasePath;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001859 if (CheckDerivedToBaseConversion(From->getType(),
1860 ToType.getNonReferenceType(),
1861 From->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001862 From->getSourceRange(),
1863 &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001864 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001865 return true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001866
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001867 ImpCastExprToType(From, ToType.getNonReferenceType(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001868 CastExpr::CK_DerivedToBase,
1869 /*isLvalue=*/(From->getType()->isRecordType() &&
1870 From->isLvalue(Context) == Expr::LV_Valid),
1871 BasePath);
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001872 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001873 }
1874
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001875 case ICK_Vector_Conversion:
1876 ImpCastExprToType(From, ToType, CastExpr::CK_BitCast);
1877 break;
1878
1879 case ICK_Vector_Splat:
1880 ImpCastExprToType(From, ToType, CastExpr::CK_VectorSplat);
1881 break;
1882
1883 case ICK_Complex_Real:
1884 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1885 break;
1886
1887 case ICK_Lvalue_To_Rvalue:
1888 case ICK_Array_To_Pointer:
1889 case ICK_Function_To_Pointer:
1890 case ICK_Qualification:
1891 case ICK_Num_Conversion_Kinds:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001892 assert(false && "Improper second standard conversion");
1893 break;
1894 }
1895
1896 switch (SCS.Third) {
1897 case ICK_Identity:
1898 // Nothing to do.
1899 break;
1900
1901 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001902 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1903 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001904 ImpCastExprToType(From, ToType.getNonReferenceType(),
Anders Carlssonf1b48b72010-04-24 16:57:13 +00001905 CastExpr::CK_NoOp, ToType->isLValueReferenceType());
Douglas Gregora9bff302010-02-28 18:30:25 +00001906
1907 if (SCS.DeprecatedStringLiteralToCharPtr)
1908 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
1909 << ToType.getNonReferenceType();
1910
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001911 break;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001912
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001913 default:
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001914 assert(false && "Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001915 break;
1916 }
1917
1918 return false;
1919}
1920
Sebastian Redl64b45f72009-01-05 20:52:13 +00001921Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1922 SourceLocation KWLoc,
1923 SourceLocation LParen,
1924 TypeTy *Ty,
1925 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001926 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001927
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001928 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1929 // all traits except __is_class, __is_enum and __is_union require a the type
1930 // to be complete.
1931 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001932 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001933 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001934 return ExprError();
1935 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001936
1937 // There is no point in eagerly computing the value. The traits are designed
1938 // to be used from type trait templates, so Ty will be a template parameter
1939 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001940 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1941 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001942}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001943
1944QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001945 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001946 const char *OpSpelling = isIndirect ? "->*" : ".*";
1947 // C++ 5.5p2
1948 // The binary operator .* [p3: ->*] binds its second operand, which shall
1949 // be of type "pointer to member of T" (where T is a completely-defined
1950 // class type) [...]
1951 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001952 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001953 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001954 Diag(Loc, diag::err_bad_memptr_rhs)
1955 << OpSpelling << RType << rex->getSourceRange();
1956 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001957 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001958
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001959 QualType Class(MemPtr->getClass(), 0);
1960
Sebastian Redl59fc2692010-04-10 10:14:54 +00001961 if (RequireCompleteType(Loc, Class, diag::err_memptr_rhs_to_incomplete))
1962 return QualType();
1963
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001964 // C++ 5.5p2
1965 // [...] to its first operand, which shall be of class T or of a class of
1966 // which T is an unambiguous and accessible base class. [p3: a pointer to
1967 // such a class]
1968 QualType LType = lex->getType();
1969 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001970 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001971 LType = Ptr->getPointeeType().getNonReferenceType();
1972 else {
1973 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001974 << OpSpelling << 1 << LType
Douglas Gregor849b2432010-03-31 17:46:05 +00001975 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001976 return QualType();
1977 }
1978 }
1979
Douglas Gregora4923eb2009-11-16 21:35:15 +00001980 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00001981 // If we want to check the hierarchy, we need a complete type.
1982 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
1983 << OpSpelling << (int)isIndirect)) {
1984 return QualType();
1985 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001986 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001987 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001988 // FIXME: Would it be useful to print full ambiguity paths, or is that
1989 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001990 if (!IsDerivedFrom(LType, Class, Paths) ||
1991 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1992 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00001993 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001994 return QualType();
1995 }
Eli Friedman3005efe2010-01-16 00:00:48 +00001996 // Cast LHS to type of use.
1997 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
1998 bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001999
2000 CXXBaseSpecifierArray BasePath;
2001 BuildBasePathArray(Paths, BasePath);
2002 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue,
2003 BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002004 }
2005
Fariborz Jahanian19d70732009-11-18 22:16:17 +00002006 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00002007 // Diagnose use of pointer-to-member type which when used as
2008 // the functional cast in a pointer-to-member expression.
2009 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
2010 return QualType();
2011 }
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002012 // C++ 5.5p2
2013 // The result is an object or a function of the type specified by the
2014 // second operand.
2015 // The cv qualifiers are the union of those in the pointer and the left side,
2016 // in accordance with 5.5p5 and 5.2.5.
2017 // FIXME: This returns a dereferenced member function pointer as a normal
2018 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00002019 // calling them. There's also a GCC extension to get a function pointer to the
2020 // thing, which is another complication, because this type - unlike the type
2021 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002022 // argument.
2023 // We probably need a "MemberFunctionClosureType" or something like that.
2024 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00002025 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002026 return Result;
2027}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002028
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002029/// \brief Try to convert a type to another according to C++0x 5.16p3.
2030///
2031/// This is part of the parameter validation for the ? operator. If either
2032/// value operand is a class type, the two operands are attempted to be
2033/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002034/// It returns true if the program is ill-formed and has already been diagnosed
2035/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002036static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
2037 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00002038 bool &HaveConversion,
2039 QualType &ToType) {
2040 HaveConversion = false;
2041 ToType = To->getType();
2042
2043 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
2044 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002045 // C++0x 5.16p3
2046 // The process for determining whether an operand expression E1 of type T1
2047 // can be converted to match an operand expression E2 of type T2 is defined
2048 // as follows:
2049 // -- If E2 is an lvalue:
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002050 bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid);
2051 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002052 // E1 can be converted to match E2 if E1 can be implicitly converted to
2053 // type "lvalue reference to T2", subject to the constraint that in the
2054 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002055 QualType T = Self.Context.getLValueReferenceType(ToType);
2056 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2057
2058 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2059 if (InitSeq.isDirectReferenceBinding()) {
2060 ToType = T;
2061 HaveConversion = true;
2062 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002063 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002064
2065 if (InitSeq.isAmbiguous())
2066 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002067 }
John McCallb1bdc622010-02-25 01:37:24 +00002068
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002069 // -- If E2 is an rvalue, or if the conversion above cannot be done:
2070 // -- if E1 and E2 have class type, and the underlying class types are
2071 // the same or one is a base class of the other:
2072 QualType FTy = From->getType();
2073 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002074 const RecordType *FRec = FTy->getAs<RecordType>();
2075 const RecordType *TRec = TTy->getAs<RecordType>();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002076 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
2077 Self.IsDerivedFrom(FTy, TTy);
2078 if (FRec && TRec &&
2079 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002080 // E1 can be converted to match E2 if the class of T2 is the
2081 // same type as, or a base class of, the class of T1, and
2082 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00002083 if (FRec == TRec || FDerivedFromT) {
2084 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002085 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2086 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2087 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2088 HaveConversion = true;
2089 return false;
2090 }
2091
2092 if (InitSeq.isAmbiguous())
2093 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2094 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002095 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002096
2097 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002098 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002099
2100 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2101 // implicitly converted to the type that expression E2 would have
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002102 // if E2 were converted to an rvalue (or the type it has, if E2 is
2103 // an rvalue).
2104 //
2105 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2106 // to the array-to-pointer or function-to-pointer conversions.
2107 if (!TTy->getAs<TagType>())
2108 TTy = TTy.getUnqualifiedType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002109
2110 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2111 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2112 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
2113 ToType = TTy;
2114 if (InitSeq.isAmbiguous())
2115 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2116
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002117 return false;
2118}
2119
2120/// \brief Try to find a common type for two according to C++0x 5.16p5.
2121///
2122/// This is part of the parameter validation for the ? operator. If either
2123/// value operand is a class type, overload resolution is used to find a
2124/// conversion to a common type.
2125static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2126 SourceLocation Loc) {
2127 Expr *Args[2] = { LHS, RHS };
John McCall5769d612010-02-08 23:07:23 +00002128 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor573d9c32009-10-21 23:19:44 +00002129 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002130
2131 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00002132 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002133 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002134 // We found a match. Perform the conversions on the arguments and move on.
2135 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00002136 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002137 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00002138 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002139 break;
2140 return false;
2141
Douglas Gregor20093b42009-12-09 23:02:17 +00002142 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002143 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2144 << LHS->getType() << RHS->getType()
2145 << LHS->getSourceRange() << RHS->getSourceRange();
2146 return true;
2147
Douglas Gregor20093b42009-12-09 23:02:17 +00002148 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002149 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2150 << LHS->getType() << RHS->getType()
2151 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00002152 // FIXME: Print the possible common types by printing the return types of
2153 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002154 break;
2155
Douglas Gregor20093b42009-12-09 23:02:17 +00002156 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002157 assert(false && "Conditional operator has only built-in overloads");
2158 break;
2159 }
2160 return true;
2161}
2162
Sebastian Redl76458502009-04-17 16:30:52 +00002163/// \brief Perform an "extended" implicit conversion as returned by
2164/// TryClassUnification.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002165static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2166 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2167 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2168 SourceLocation());
2169 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
2170 Sema::OwningExprResult Result = InitSeq.Perform(Self, Entity, Kind,
2171 Sema::MultiExprArg(Self, (void **)&E, 1));
2172 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00002173 return true;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002174
2175 E = Result.takeAs<Expr>();
Sebastian Redl76458502009-04-17 16:30:52 +00002176 return false;
2177}
2178
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002179/// \brief Check the operands of ?: under C++ semantics.
2180///
2181/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2182/// extension. In this case, LHS == Cond. (But they're not aliases.)
2183QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2184 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002185 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2186 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002187
2188 // C++0x 5.16p1
2189 // The first expression is contextually converted to bool.
2190 if (!Cond->isTypeDependent()) {
2191 if (CheckCXXBooleanCondition(Cond))
2192 return QualType();
2193 }
2194
2195 // Either of the arguments dependent?
2196 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2197 return Context.DependentTy;
2198
2199 // C++0x 5.16p2
2200 // If either the second or the third operand has type (cv) void, ...
2201 QualType LTy = LHS->getType();
2202 QualType RTy = RHS->getType();
2203 bool LVoid = LTy->isVoidType();
2204 bool RVoid = RTy->isVoidType();
2205 if (LVoid || RVoid) {
2206 // ... then the [l2r] conversions are performed on the second and third
2207 // operands ...
Douglas Gregora873dfc2010-02-03 00:27:59 +00002208 DefaultFunctionArrayLvalueConversion(LHS);
2209 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002210 LTy = LHS->getType();
2211 RTy = RHS->getType();
2212
2213 // ... and one of the following shall hold:
2214 // -- The second or the third operand (but not both) is a throw-
2215 // expression; the result is of the type of the other and is an rvalue.
2216 bool LThrow = isa<CXXThrowExpr>(LHS);
2217 bool RThrow = isa<CXXThrowExpr>(RHS);
2218 if (LThrow && !RThrow)
2219 return RTy;
2220 if (RThrow && !LThrow)
2221 return LTy;
2222
2223 // -- Both the second and third operands have type void; the result is of
2224 // type void and is an rvalue.
2225 if (LVoid && RVoid)
2226 return Context.VoidTy;
2227
2228 // Neither holds, error.
2229 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2230 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2231 << LHS->getSourceRange() << RHS->getSourceRange();
2232 return QualType();
2233 }
2234
2235 // Neither is void.
2236
2237 // C++0x 5.16p3
2238 // Otherwise, if the second and third operand have different types, and
2239 // either has (cv) class type, and attempt is made to convert each of those
2240 // operands to the other.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002241 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002242 (LTy->isRecordType() || RTy->isRecordType())) {
2243 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2244 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002245 QualType L2RType, R2LType;
2246 bool HaveL2R, HaveR2L;
2247 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002248 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002249 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002250 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002251
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002252 // If both can be converted, [...] the program is ill-formed.
2253 if (HaveL2R && HaveR2L) {
2254 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2255 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2256 return QualType();
2257 }
2258
2259 // If exactly one conversion is possible, that conversion is applied to
2260 // the chosen operand and the converted operands are used in place of the
2261 // original operands for the remainder of this section.
2262 if (HaveL2R) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002263 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002264 return QualType();
2265 LTy = LHS->getType();
2266 } else if (HaveR2L) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002267 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002268 return QualType();
2269 RTy = RHS->getType();
2270 }
2271 }
2272
2273 // C++0x 5.16p4
2274 // If the second and third operands are lvalues and have the same type,
2275 // the result is of that type [...]
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002276 bool Same = Context.hasSameType(LTy, RTy);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002277 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
2278 RHS->isLvalue(Context) == Expr::LV_Valid)
2279 return LTy;
2280
2281 // C++0x 5.16p5
2282 // Otherwise, the result is an rvalue. If the second and third operands
2283 // do not have the same type, and either has (cv) class type, ...
2284 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2285 // ... overload resolution is used to determine the conversions (if any)
2286 // to be applied to the operands. If the overload resolution fails, the
2287 // program is ill-formed.
2288 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2289 return QualType();
2290 }
2291
2292 // C++0x 5.16p6
2293 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2294 // conversions are performed on the second and third operands.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002295 DefaultFunctionArrayLvalueConversion(LHS);
2296 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002297 LTy = LHS->getType();
2298 RTy = RHS->getType();
2299
2300 // After those conversions, one of the following shall hold:
2301 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00002302 // is of that type. If the operands have class type, the result
2303 // is a prvalue temporary of the result type, which is
2304 // copy-initialized from either the second operand or the third
2305 // operand depending on the value of the first operand.
2306 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
2307 if (LTy->isRecordType()) {
2308 // The operands have class type. Make a temporary copy.
2309 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
2310 OwningExprResult LHSCopy = PerformCopyInitialization(Entity,
2311 SourceLocation(),
2312 Owned(LHS));
2313 if (LHSCopy.isInvalid())
2314 return QualType();
2315
2316 OwningExprResult RHSCopy = PerformCopyInitialization(Entity,
2317 SourceLocation(),
2318 Owned(RHS));
2319 if (RHSCopy.isInvalid())
2320 return QualType();
2321
2322 LHS = LHSCopy.takeAs<Expr>();
2323 RHS = RHSCopy.takeAs<Expr>();
2324 }
2325
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002326 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00002327 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002328
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002329 // Extension: conditional operator involving vector types.
2330 if (LTy->isVectorType() || RTy->isVectorType())
2331 return CheckVectorOperands(QuestionLoc, LHS, RHS);
2332
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002333 // -- The second and third operands have arithmetic or enumeration type;
2334 // the usual arithmetic conversions are performed to bring them to a
2335 // common type, and the result is of that type.
2336 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2337 UsualArithmeticConversions(LHS, RHS);
2338 return LHS->getType();
2339 }
2340
2341 // -- The second and third operands have pointer type, or one has pointer
2342 // type and the other is a null pointer constant; pointer conversions
2343 // and qualification conversions are performed to bring them to their
2344 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00002345 // -- The second and third operands have pointer to member type, or one has
2346 // pointer to member type and the other is a null pointer constant;
2347 // pointer to member conversions and qualification conversions are
2348 // performed to bring them to a common type, whose cv-qualification
2349 // shall match the cv-qualification of either the second or the third
2350 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002351 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002352 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002353 isSFINAEContext()? 0 : &NonStandardCompositeType);
2354 if (!Composite.isNull()) {
2355 if (NonStandardCompositeType)
2356 Diag(QuestionLoc,
2357 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2358 << LTy << RTy << Composite
2359 << LHS->getSourceRange() << RHS->getSourceRange();
2360
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002361 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002362 }
Fariborz Jahanian55016362009-12-10 20:46:08 +00002363
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002364 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00002365 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2366 if (!Composite.isNull())
2367 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002368
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002369 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2370 << LHS->getType() << RHS->getType()
2371 << LHS->getSourceRange() << RHS->getSourceRange();
2372 return QualType();
2373}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002374
2375/// \brief Find a merged pointer type and convert the two expressions to it.
2376///
Douglas Gregor20b3e992009-08-24 17:42:35 +00002377/// This finds the composite pointer type (or member pointer type) for @p E1
2378/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2379/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002380/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002381///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002382/// \param Loc The location of the operator requiring these two expressions to
2383/// be converted to the composite pointer type.
2384///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002385/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2386/// a non-standard (but still sane) composite type to which both expressions
2387/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2388/// will be set true.
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002389QualType Sema::FindCompositePointerType(SourceLocation Loc,
2390 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002391 bool *NonStandardCompositeType) {
2392 if (NonStandardCompositeType)
2393 *NonStandardCompositeType = false;
2394
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002395 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2396 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002397
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00002398 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2399 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00002400 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002401
2402 // C++0x 5.9p2
2403 // Pointer conversions and qualification conversions are performed on
2404 // pointer operands to bring them to their composite pointer type. If
2405 // one operand is a null pointer constant, the composite pointer type is
2406 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00002407 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002408 if (T2->isMemberPointerType())
2409 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
2410 else
2411 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002412 return T2;
2413 }
Douglas Gregorce940492009-09-25 04:25:58 +00002414 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002415 if (T1->isMemberPointerType())
2416 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
2417 else
2418 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002419 return T1;
2420 }
Mike Stump1eb44332009-09-09 15:08:12 +00002421
Douglas Gregor20b3e992009-08-24 17:42:35 +00002422 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002423 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2424 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002425 return QualType();
2426
2427 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2428 // the other has type "pointer to cv2 T" and the composite pointer type is
2429 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2430 // Otherwise, the composite pointer type is a pointer type similar to the
2431 // type of one of the operands, with a cv-qualification signature that is
2432 // the union of the cv-qualification signatures of the operand types.
2433 // In practice, the first part here is redundant; it's subsumed by the second.
2434 // What we do here is, we build the two possible composite types, and try the
2435 // conversions in both directions. If only one works, or if the two composite
2436 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00002437 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00002438 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2439 QualifierVector QualifierUnion;
2440 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2441 ContainingClassVector;
2442 ContainingClassVector MemberOfClass;
2443 QualType Composite1 = Context.getCanonicalType(T1),
2444 Composite2 = Context.getCanonicalType(T2);
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002445 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00002446 do {
2447 const PointerType *Ptr1, *Ptr2;
2448 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2449 (Ptr2 = Composite2->getAs<PointerType>())) {
2450 Composite1 = Ptr1->getPointeeType();
2451 Composite2 = Ptr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002452
2453 // If we're allowed to create a non-standard composite type, keep track
2454 // of where we need to fill in additional 'const' qualifiers.
2455 if (NonStandardCompositeType &&
2456 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2457 NeedConstBefore = QualifierUnion.size();
2458
Douglas Gregor20b3e992009-08-24 17:42:35 +00002459 QualifierUnion.push_back(
2460 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2461 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2462 continue;
2463 }
Mike Stump1eb44332009-09-09 15:08:12 +00002464
Douglas Gregor20b3e992009-08-24 17:42:35 +00002465 const MemberPointerType *MemPtr1, *MemPtr2;
2466 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2467 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2468 Composite1 = MemPtr1->getPointeeType();
2469 Composite2 = MemPtr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002470
2471 // If we're allowed to create a non-standard composite type, keep track
2472 // of where we need to fill in additional 'const' qualifiers.
2473 if (NonStandardCompositeType &&
2474 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2475 NeedConstBefore = QualifierUnion.size();
2476
Douglas Gregor20b3e992009-08-24 17:42:35 +00002477 QualifierUnion.push_back(
2478 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2479 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2480 MemPtr2->getClass()));
2481 continue;
2482 }
Mike Stump1eb44332009-09-09 15:08:12 +00002483
Douglas Gregor20b3e992009-08-24 17:42:35 +00002484 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00002485
Douglas Gregor20b3e992009-08-24 17:42:35 +00002486 // Cannot unwrap any more types.
2487 break;
2488 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00002489
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002490 if (NeedConstBefore && NonStandardCompositeType) {
2491 // Extension: Add 'const' to qualifiers that come before the first qualifier
2492 // mismatch, so that our (non-standard!) composite type meets the
2493 // requirements of C++ [conv.qual]p4 bullet 3.
2494 for (unsigned I = 0; I != NeedConstBefore; ++I) {
2495 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
2496 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
2497 *NonStandardCompositeType = true;
2498 }
2499 }
2500 }
2501
Douglas Gregor20b3e992009-08-24 17:42:35 +00002502 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002503 ContainingClassVector::reverse_iterator MOC
2504 = MemberOfClass.rbegin();
2505 for (QualifierVector::reverse_iterator
2506 I = QualifierUnion.rbegin(),
2507 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00002508 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00002509 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002510 if (MOC->first && MOC->second) {
2511 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00002512 Composite1 = Context.getMemberPointerType(
2513 Context.getQualifiedType(Composite1, Quals),
2514 MOC->first);
2515 Composite2 = Context.getMemberPointerType(
2516 Context.getQualifiedType(Composite2, Quals),
2517 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002518 } else {
2519 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00002520 Composite1
2521 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2522 Composite2
2523 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00002524 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002525 }
2526
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002527 // Try to convert to the first composite pointer type.
2528 InitializedEntity Entity1
2529 = InitializedEntity::InitializeTemporary(Composite1);
2530 InitializationKind Kind
2531 = InitializationKind::CreateCopy(Loc, SourceLocation());
2532 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
2533 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00002534
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002535 if (E1ToC1 && E2ToC1) {
2536 // Conversion to Composite1 is viable.
2537 if (!Context.hasSameType(Composite1, Composite2)) {
2538 // Composite2 is a different type from Composite1. Check whether
2539 // Composite2 is also viable.
2540 InitializedEntity Entity2
2541 = InitializedEntity::InitializeTemporary(Composite2);
2542 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2543 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2544 if (E1ToC2 && E2ToC2) {
2545 // Both Composite1 and Composite2 are viable and are different;
2546 // this is an ambiguity.
2547 return QualType();
2548 }
2549 }
2550
2551 // Convert E1 to Composite1
2552 OwningExprResult E1Result
2553 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E1,1));
2554 if (E1Result.isInvalid())
2555 return QualType();
2556 E1 = E1Result.takeAs<Expr>();
2557
2558 // Convert E2 to Composite1
2559 OwningExprResult E2Result
2560 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E2,1));
2561 if (E2Result.isInvalid())
2562 return QualType();
2563 E2 = E2Result.takeAs<Expr>();
2564
2565 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002566 }
2567
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002568 // Check whether Composite2 is viable.
2569 InitializedEntity Entity2
2570 = InitializedEntity::InitializeTemporary(Composite2);
2571 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2572 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2573 if (!E1ToC2 || !E2ToC2)
2574 return QualType();
2575
2576 // Convert E1 to Composite2
2577 OwningExprResult E1Result
2578 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E1, 1));
2579 if (E1Result.isInvalid())
2580 return QualType();
2581 E1 = E1Result.takeAs<Expr>();
2582
2583 // Convert E2 to Composite2
2584 OwningExprResult E2Result
2585 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E2, 1));
2586 if (E2Result.isInvalid())
2587 return QualType();
2588 E2 = E2Result.takeAs<Expr>();
2589
2590 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002591}
Anders Carlsson165a0a02009-05-17 18:41:29 +00002592
Anders Carlssondef11992009-05-30 20:36:53 +00002593Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00002594 if (!Context.getLangOptions().CPlusPlus)
2595 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002596
Douglas Gregor51326552009-12-24 18:51:59 +00002597 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2598
Ted Kremenek6217b802009-07-29 21:53:49 +00002599 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00002600 if (!RT)
2601 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002602
John McCall86ff3082010-02-04 22:26:26 +00002603 // If this is the result of a call expression, our source might
2604 // actually be a reference, in which case we shouldn't bind.
Anders Carlsson283e4d52009-09-14 01:30:44 +00002605 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2606 QualType Ty = CE->getCallee()->getType();
2607 if (const PointerType *PT = Ty->getAs<PointerType>())
2608 Ty = PT->getPointeeType();
Fariborz Jahanianb372b0f2010-02-18 20:31:02 +00002609 else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>())
2610 Ty = BPT->getPointeeType();
2611
John McCall183700f2009-09-21 23:43:11 +00002612 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00002613 if (FTy->getResultType()->isReferenceType())
2614 return Owned(E);
2615 }
Fariborz Jahaniand4266622010-06-16 18:56:04 +00002616 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
2617 QualType Ty = ME->getType();
2618 if (const PointerType *PT = Ty->getAs<PointerType>())
2619 Ty = PT->getPointeeType();
2620 else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>())
2621 Ty = BPT->getPointeeType();
2622 if (Ty->isReferenceType())
2623 return Owned(E);
2624 }
2625
John McCall86ff3082010-02-04 22:26:26 +00002626
2627 // That should be enough to guarantee that this type is complete.
2628 // If it has a trivial destructor, we can avoid the extra copy.
2629 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2630 if (RD->hasTrivialDestructor())
2631 return Owned(E);
2632
Mike Stump1eb44332009-09-09 15:08:12 +00002633 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00002634 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00002635 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002636 if (CXXDestructorDecl *Destructor =
John McCallc91cc662010-04-07 00:41:46 +00002637 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context))) {
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002638 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00002639 CheckDestructorAccess(E->getExprLoc(), Destructor,
2640 PDiag(diag::err_access_dtor_temp)
2641 << E->getType());
2642 }
Anders Carlssondef11992009-05-30 20:36:53 +00002643 // FIXME: Add the temporary to the temporaries vector.
2644 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2645}
2646
Anders Carlsson0ece4912009-12-15 20:51:39 +00002647Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002648 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002649
John McCall323ed742010-05-06 08:58:33 +00002650 // Check any implicit conversions within the expression.
2651 CheckImplicitConversions(SubExpr);
2652
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002653 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2654 assert(ExprTemporaries.size() >= FirstTemporary);
2655 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002656 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002657
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002658 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002659 &ExprTemporaries[FirstTemporary],
Anders Carlsson0ece4912009-12-15 20:51:39 +00002660 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002661 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2662 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002663
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002664 return E;
2665}
2666
Douglas Gregor90f93822009-12-22 22:17:25 +00002667Sema::OwningExprResult
2668Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2669 if (SubExpr.isInvalid())
2670 return ExprError();
2671
2672 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2673}
2674
Anders Carlsson5ee56e92009-12-16 02:09:40 +00002675FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2676 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2677 assert(ExprTemporaries.size() >= FirstTemporary);
2678
2679 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2680 CXXTemporary **Temporaries =
2681 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2682
2683 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2684
2685 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2686 ExprTemporaries.end());
2687
2688 return E;
2689}
2690
Mike Stump1eb44332009-09-09 15:08:12 +00002691Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002692Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
Douglas Gregord4dca082010-02-24 18:44:31 +00002693 tok::TokenKind OpKind, TypeTy *&ObjectType,
2694 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002695 // Since this might be a postfix expression, get rid of ParenListExprs.
2696 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002697
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002698 Expr *BaseExpr = (Expr*)Base.get();
2699 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002700
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002701 QualType BaseType = BaseExpr->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00002702 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002703 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002704 // If we have a pointer to a dependent type and are using the -> operator,
2705 // the object type is the type that the pointer points to. We might still
2706 // have enough information about that type to do something useful.
2707 if (OpKind == tok::arrow)
2708 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2709 BaseType = Ptr->getPointeeType();
2710
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002711 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregord4dca082010-02-24 18:44:31 +00002712 MayBePseudoDestructor = true;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002713 return move(Base);
2714 }
Mike Stump1eb44332009-09-09 15:08:12 +00002715
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002716 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002717 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002718 // returned, with the original second operand.
2719 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002720 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002721 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002722 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002723 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002724
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002725 while (BaseType->isRecordType()) {
Anders Carlsson15ea3782009-10-13 22:43:21 +00002726 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002727 BaseExpr = (Expr*)Base.get();
2728 if (BaseExpr == NULL)
2729 return ExprError();
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002730 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonde699e52009-10-13 22:55:59 +00002731 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc4e83212009-09-30 01:01:30 +00002732 BaseType = BaseExpr->getType();
2733 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002734 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002735 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002736 for (unsigned i = 0; i < Locations.size(); i++)
2737 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002738 return ExprError();
2739 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002740 }
Mike Stump1eb44332009-09-09 15:08:12 +00002741
Douglas Gregor31658df2009-11-20 19:58:21 +00002742 if (BaseType->isPointerType())
2743 BaseType = BaseType->getPointeeType();
2744 }
Mike Stump1eb44332009-09-09 15:08:12 +00002745
2746 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002747 // vector types or Objective-C interfaces. Just return early and let
2748 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002749 if (!BaseType->isRecordType()) {
2750 // C++ [basic.lookup.classref]p2:
2751 // [...] If the type of the object expression is of pointer to scalar
2752 // type, the unqualified-id is looked up in the context of the complete
2753 // postfix-expression.
Douglas Gregord4dca082010-02-24 18:44:31 +00002754 //
2755 // This also indicates that we should be parsing a
2756 // pseudo-destructor-name.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002757 ObjectType = 0;
Douglas Gregord4dca082010-02-24 18:44:31 +00002758 MayBePseudoDestructor = true;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002759 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002760 }
Mike Stump1eb44332009-09-09 15:08:12 +00002761
Douglas Gregor03c57052009-11-17 05:17:33 +00002762 // The object type must be complete (or dependent).
2763 if (!BaseType->isDependentType() &&
2764 RequireCompleteType(OpLoc, BaseType,
2765 PDiag(diag::err_incomplete_member_access)))
2766 return ExprError();
2767
Douglas Gregorc68afe22009-09-03 21:38:09 +00002768 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002769 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00002770 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00002771 // type C (or of pointer to a class type C), the unqualified-id is looked
2772 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002773 ObjectType = BaseType.getAsOpaquePtr();
Mike Stump1eb44332009-09-09 15:08:12 +00002774 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002775}
2776
Douglas Gregor77549082010-02-24 21:29:12 +00002777Sema::OwningExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
2778 ExprArg MemExpr) {
2779 Expr *E = (Expr *) MemExpr.get();
2780 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
2781 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2782 << isa<CXXPseudoDestructorExpr>(E)
Douglas Gregor849b2432010-03-31 17:46:05 +00002783 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
Douglas Gregor77549082010-02-24 21:29:12 +00002784
2785 return ActOnCallExpr(/*Scope*/ 0,
2786 move(MemExpr),
2787 /*LPLoc*/ ExpectedLParenLoc,
2788 Sema::MultiExprArg(*this, 0, 0),
2789 /*CommaLocs*/ 0,
2790 /*RPLoc*/ ExpectedLParenLoc);
2791}
Douglas Gregord4dca082010-02-24 18:44:31 +00002792
Douglas Gregorb57fb492010-02-24 22:38:50 +00002793Sema::OwningExprResult Sema::BuildPseudoDestructorExpr(ExprArg Base,
2794 SourceLocation OpLoc,
2795 tok::TokenKind OpKind,
2796 const CXXScopeSpec &SS,
Douglas Gregor26d4ac92010-02-24 23:40:28 +00002797 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002798 SourceLocation CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002799 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002800 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002801 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002802 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
Douglas Gregorb57fb492010-02-24 22:38:50 +00002803
2804 // C++ [expr.pseudo]p2:
2805 // The left-hand side of the dot operator shall be of scalar type. The
2806 // left-hand side of the arrow operator shall be of pointer to scalar type.
2807 // This scalar type is the object type.
2808 Expr *BaseE = (Expr *)Base.get();
2809 QualType ObjectType = BaseE->getType();
2810 if (OpKind == tok::arrow) {
2811 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2812 ObjectType = Ptr->getPointeeType();
2813 } else if (!BaseE->isTypeDependent()) {
2814 // The user wrote "p->" when she probably meant "p."; fix it.
2815 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2816 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00002817 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb57fb492010-02-24 22:38:50 +00002818 if (isSFINAEContext())
2819 return ExprError();
2820
2821 OpKind = tok::period;
2822 }
2823 }
2824
2825 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
2826 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2827 << ObjectType << BaseE->getSourceRange();
2828 return ExprError();
2829 }
2830
2831 // C++ [expr.pseudo]p2:
2832 // [...] The cv-unqualified versions of the object type and of the type
2833 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002834 if (DestructedTypeInfo) {
2835 QualType DestructedType = DestructedTypeInfo->getType();
2836 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002837 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002838 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
2839 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
2840 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
2841 << ObjectType << DestructedType << BaseE->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002842 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002843
2844 // Recover by setting the destructed type to the object type.
2845 DestructedType = ObjectType;
2846 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
2847 DestructedTypeStart);
2848 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2849 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00002850 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002851
Douglas Gregorb57fb492010-02-24 22:38:50 +00002852 // C++ [expr.pseudo]p2:
2853 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
2854 // form
2855 //
2856 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
2857 //
2858 // shall designate the same scalar type.
2859 if (ScopeTypeInfo) {
2860 QualType ScopeType = ScopeTypeInfo->getType();
2861 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00002862 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
Douglas Gregorb57fb492010-02-24 22:38:50 +00002863
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002864 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00002865 diag::err_pseudo_dtor_type_mismatch)
2866 << ObjectType << ScopeType << BaseE->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002867 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00002868
2869 ScopeType = QualType();
2870 ScopeTypeInfo = 0;
2871 }
2872 }
2873
2874 OwningExprResult Result
2875 = Owned(new (Context) CXXPseudoDestructorExpr(Context,
2876 Base.takeAs<Expr>(),
2877 OpKind == tok::arrow,
2878 OpLoc,
2879 (NestedNameSpecifier *) SS.getScopeRep(),
2880 SS.getRange(),
2881 ScopeTypeInfo,
2882 CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002883 TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002884 Destructed));
2885
Douglas Gregorb57fb492010-02-24 22:38:50 +00002886 if (HasTrailingLParen)
2887 return move(Result);
2888
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002889 return DiagnoseDtorReference(Destructed.getLocation(), move(Result));
Douglas Gregor77549082010-02-24 21:29:12 +00002890}
2891
2892Sema::OwningExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, ExprArg Base,
2893 SourceLocation OpLoc,
2894 tok::TokenKind OpKind,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002895 CXXScopeSpec &SS,
Douglas Gregor77549082010-02-24 21:29:12 +00002896 UnqualifiedId &FirstTypeName,
2897 SourceLocation CCLoc,
2898 SourceLocation TildeLoc,
2899 UnqualifiedId &SecondTypeName,
2900 bool HasTrailingLParen) {
2901 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2902 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2903 "Invalid first type name in pseudo-destructor");
2904 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2905 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2906 "Invalid second type name in pseudo-destructor");
2907
2908 Expr *BaseE = (Expr *)Base.get();
Douglas Gregor77549082010-02-24 21:29:12 +00002909
2910 // C++ [expr.pseudo]p2:
2911 // The left-hand side of the dot operator shall be of scalar type. The
2912 // left-hand side of the arrow operator shall be of pointer to scalar type.
2913 // This scalar type is the object type.
2914 QualType ObjectType = BaseE->getType();
2915 if (OpKind == tok::arrow) {
2916 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2917 ObjectType = Ptr->getPointeeType();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002918 } else if (!ObjectType->isDependentType()) {
Douglas Gregor77549082010-02-24 21:29:12 +00002919 // The user wrote "p->" when she probably meant "p."; fix it.
2920 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002921 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00002922 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor77549082010-02-24 21:29:12 +00002923 if (isSFINAEContext())
2924 return ExprError();
2925
2926 OpKind = tok::period;
2927 }
2928 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002929
2930 // Compute the object type that we should use for name lookup purposes. Only
2931 // record types and dependent types matter.
2932 void *ObjectTypePtrForLookup = 0;
2933 if (!SS.isSet()) {
Gabor Greif170e5082010-06-17 11:29:31 +00002934 ObjectTypePtrForLookup = const_cast<RecordType*>(
2935 ObjectType->getAs<RecordType>());
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002936 if (!ObjectTypePtrForLookup && ObjectType->isDependentType())
2937 ObjectTypePtrForLookup = Context.DependentTy.getAsOpaquePtr();
2938 }
Douglas Gregor77549082010-02-24 21:29:12 +00002939
Douglas Gregorb57fb492010-02-24 22:38:50 +00002940 // Convert the name of the type being destructed (following the ~) into a
2941 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00002942 QualType DestructedType;
2943 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002944 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00002945 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2946 TypeTy *T = getTypeName(*SecondTypeName.Identifier,
2947 SecondTypeName.StartLocation,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002948 S, &SS, true, ObjectTypePtrForLookup);
2949 if (!T &&
2950 ((SS.isSet() && !computeDeclContext(SS, false)) ||
2951 (!SS.isSet() && ObjectType->isDependentType()))) {
2952 // The name of the type being destroyed is a dependent name, and we
2953 // couldn't find anything useful in scope. Just store the identifier and
2954 // it's location, and we'll perform (qualified) name lookup again at
2955 // template instantiation time.
2956 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
2957 SecondTypeName.StartLocation);
2958 } else if (!T) {
Douglas Gregor77549082010-02-24 21:29:12 +00002959 Diag(SecondTypeName.StartLocation,
2960 diag::err_pseudo_dtor_destructor_non_type)
2961 << SecondTypeName.Identifier << ObjectType;
2962 if (isSFINAEContext())
2963 return ExprError();
2964
2965 // Recover by assuming we had the right type all along.
2966 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002967 } else
Douglas Gregor77549082010-02-24 21:29:12 +00002968 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002969 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00002970 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00002971 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002972 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2973 TemplateId->getTemplateArgs(),
2974 TemplateId->NumArgs);
2975 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2976 TemplateId->TemplateNameLoc,
2977 TemplateId->LAngleLoc,
2978 TemplateArgsPtr,
2979 TemplateId->RAngleLoc);
2980 if (T.isInvalid() || !T.get()) {
2981 // Recover by assuming we had the right type all along.
2982 DestructedType = ObjectType;
2983 } else
2984 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002985 }
2986
Douglas Gregorb57fb492010-02-24 22:38:50 +00002987 // If we've performed some kind of recovery, (re-)build the type source
2988 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002989 if (!DestructedType.isNull()) {
2990 if (!DestructedTypeInfo)
2991 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002992 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002993 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2994 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00002995
2996 // Convert the name of the scope type (the type prior to '::') into a type.
2997 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00002998 QualType ScopeType;
2999 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3000 FirstTypeName.Identifier) {
3001 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
3002 TypeTy *T = getTypeName(*FirstTypeName.Identifier,
3003 FirstTypeName.StartLocation,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003004 S, &SS, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00003005 if (!T) {
3006 Diag(FirstTypeName.StartLocation,
3007 diag::err_pseudo_dtor_destructor_non_type)
3008 << FirstTypeName.Identifier << ObjectType;
Douglas Gregor77549082010-02-24 21:29:12 +00003009
Douglas Gregorb57fb492010-02-24 22:38:50 +00003010 if (isSFINAEContext())
3011 return ExprError();
3012
3013 // Just drop this type. It's unnecessary anyway.
3014 ScopeType = QualType();
3015 } else
3016 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003017 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003018 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00003019 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003020 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3021 TemplateId->getTemplateArgs(),
3022 TemplateId->NumArgs);
3023 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
3024 TemplateId->TemplateNameLoc,
3025 TemplateId->LAngleLoc,
3026 TemplateArgsPtr,
3027 TemplateId->RAngleLoc);
3028 if (T.isInvalid() || !T.get()) {
3029 // Recover by dropping this type.
3030 ScopeType = QualType();
3031 } else
3032 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003033 }
3034 }
Douglas Gregorb4a418f2010-02-24 23:02:30 +00003035
3036 if (!ScopeType.isNull() && !ScopeTypeInfo)
3037 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
3038 FirstTypeName.StartLocation);
3039
3040
Douglas Gregorb57fb492010-02-24 22:38:50 +00003041 return BuildPseudoDestructorExpr(move(Base), OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00003042 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003043 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00003044}
3045
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003046CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
John McCall6bb80172010-03-30 21:47:33 +00003047 NamedDecl *FoundDecl,
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003048 CXXMethodDecl *Method) {
John McCall6bb80172010-03-30 21:47:33 +00003049 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
3050 FoundDecl, Method))
Eli Friedman772fffa2009-12-09 04:53:56 +00003051 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
3052
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003053 MemberExpr *ME =
3054 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
3055 SourceLocation(), Method->getType());
Eli Friedman772fffa2009-12-09 04:53:56 +00003056 QualType ResultType = Method->getResultType().getNonReferenceType();
Douglas Gregor7edfb692009-11-23 12:27:39 +00003057 MarkDeclarationReferenced(Exp->getLocStart(), Method);
3058 CXXMemberCallExpr *CE =
3059 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
3060 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003061 return CE;
3062}
3063
Anders Carlsson165a0a02009-05-17 18:41:29 +00003064Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
3065 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003066 if (FullExpr)
Anders Carlsson0ece4912009-12-15 20:51:39 +00003067 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Douglas Gregoreecf38f2010-05-06 21:39:56 +00003068 else
3069 return ExprError();
3070
Anders Carlsson165a0a02009-05-17 18:41:29 +00003071 return Owned(FullExpr);
3072}