blob: a5abfe851b891f7becde9dece502d7c098eb40aa [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.
Sebastian Redlc0fee502010-07-07 23:17:38 +000056 // For this reason, we're currently only doing the C++03 version of this
57 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregor124b8782010-02-16 19:09:40 +000058 QualType SearchType;
59 DeclContext *LookupCtx = 0;
60 bool isDependent = false;
61 bool LookInScope = false;
62
63 // If we have an object type, it's because we are in a
64 // pseudo-destructor-expression or a member access expression, and
65 // we know what type we're looking for.
66 if (ObjectTypePtr)
67 SearchType = GetTypeFromParser(ObjectTypePtr);
68
69 if (SS.isSet()) {
Douglas Gregor93649fd2010-02-23 00:15:22 +000070 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
71
72 bool AlreadySearched = false;
73 bool LookAtPrefix = true;
Sebastian Redlc0fee502010-07-07 23:17:38 +000074 // C++ [basic.lookup.qual]p6:
75 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
76 // the type-names are looked up as types in the scope designated by the
77 // nested-name-specifier. In a qualified-id of the form:
78 //
79 // ::[opt] nested-name-specifier ̃ class-name
80 //
81 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth5e895a82010-02-21 10:19:54 +000082 // a qualified-id of the form:
Douglas Gregor124b8782010-02-16 19:09:40 +000083 //
Sebastian Redlc0fee502010-07-07 23:17:38 +000084 // ::opt nested-name-specifier class-name :: ̃ class-name
Douglas Gregor124b8782010-02-16 19:09:40 +000085 //
Sebastian Redlc0fee502010-07-07 23:17:38 +000086 // the class-names are looked up as types in the scope designated by
87 // the nested-name-specifier.
Douglas Gregor124b8782010-02-16 19:09:40 +000088 //
Sebastian Redlc0fee502010-07-07 23:17:38 +000089 // Here, we check the first case (completely) and determine whether the
90 // code below is permitted to look at the prefix of the
91 // nested-name-specifier.
92 DeclContext *DC = computeDeclContext(SS, EnteringContext);
93 if (DC && DC->isFileContext()) {
94 AlreadySearched = true;
95 LookupCtx = DC;
96 isDependent = false;
97 } else if (DC && isa<CXXRecordDecl>(DC))
98 LookAtPrefix = false;
99
100 // The second case from the C++03 rules quoted further above.
Douglas Gregor93649fd2010-02-23 00:15:22 +0000101 NestedNameSpecifier *Prefix = 0;
102 if (AlreadySearched) {
103 // Nothing left to do.
104 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
105 CXXScopeSpec PrefixSS;
106 PrefixSS.setScopeRep(Prefix);
107 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
108 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000109 } else if (ObjectTypePtr) {
Douglas Gregor124b8782010-02-16 19:09:40 +0000110 LookupCtx = computeDeclContext(SearchType);
111 isDependent = SearchType->isDependentType();
112 } else {
113 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000114 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregor124b8782010-02-16 19:09:40 +0000115 }
Douglas Gregor93649fd2010-02-23 00:15:22 +0000116
Douglas Gregoredc90502010-02-25 04:46:04 +0000117 LookInScope = false;
Douglas Gregor124b8782010-02-16 19:09:40 +0000118 } else if (ObjectTypePtr) {
119 // C++ [basic.lookup.classref]p3:
120 // If the unqualified-id is ~type-name, the type-name is looked up
121 // in the context of the entire postfix-expression. If the type T
122 // of the object expression is of a class type C, the type-name is
123 // also looked up in the scope of class C. At least one of the
124 // lookups shall find a name that refers to (possibly
125 // cv-qualified) T.
126 LookupCtx = computeDeclContext(SearchType);
127 isDependent = SearchType->isDependentType();
128 assert((isDependent || !SearchType->isIncompleteType()) &&
129 "Caller should have completed object type");
130
131 LookInScope = true;
132 } else {
133 // Perform lookup into the current scope (only).
134 LookInScope = true;
135 }
136
137 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
138 for (unsigned Step = 0; Step != 2; ++Step) {
139 // Look for the name first in the computed lookup context (if we
140 // have one) and, if that fails to find a match, in the sope (if
141 // we're allowed to look there).
142 Found.clear();
143 if (Step == 0 && LookupCtx)
144 LookupQualifiedName(Found, LookupCtx);
Douglas Gregora2e7dd22010-02-25 01:56:36 +0000145 else if (Step == 1 && LookInScope && S)
Douglas Gregor124b8782010-02-16 19:09:40 +0000146 LookupName(Found, S);
147 else
148 continue;
149
150 // FIXME: Should we be suppressing ambiguities here?
151 if (Found.isAmbiguous())
152 return 0;
153
154 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
155 QualType T = Context.getTypeDeclType(Type);
Douglas Gregor124b8782010-02-16 19:09:40 +0000156
157 if (SearchType.isNull() || SearchType->isDependentType() ||
158 Context.hasSameUnqualifiedType(T, SearchType)) {
159 // We found our type!
160
161 return T.getAsOpaquePtr();
162 }
163 }
164
165 // If the name that we found is a class template name, and it is
166 // the same name as the template name in the last part of the
167 // nested-name-specifier (if present) or the object type, then
168 // this is the destructor for that class.
169 // FIXME: This is a workaround until we get real drafting for core
170 // issue 399, for which there isn't even an obvious direction.
171 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
172 QualType MemberOfType;
173 if (SS.isSet()) {
174 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
175 // Figure out the type of the context, if it has one.
John McCall3cb0ebd2010-03-10 03:28:59 +0000176 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
177 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregor124b8782010-02-16 19:09:40 +0000178 }
179 }
180 if (MemberOfType.isNull())
181 MemberOfType = SearchType;
182
183 if (MemberOfType.isNull())
184 continue;
185
186 // We're referring into a class template specialization. If the
187 // class template we found is the same as the template being
188 // specialized, we found what we are looking for.
189 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
190 if (ClassTemplateSpecializationDecl *Spec
191 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
192 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
193 Template->getCanonicalDecl())
194 return MemberOfType.getAsOpaquePtr();
195 }
196
197 continue;
198 }
199
200 // We're referring to an unresolved class template
201 // specialization. Determine whether we class template we found
202 // is the same as the template being specialized or, if we don't
203 // know which template is being specialized, that it at least
204 // has the same name.
205 if (const TemplateSpecializationType *SpecType
206 = MemberOfType->getAs<TemplateSpecializationType>()) {
207 TemplateName SpecName = SpecType->getTemplateName();
208
209 // The class template we found is the same template being
210 // specialized.
211 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
212 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
213 return MemberOfType.getAsOpaquePtr();
214
215 continue;
216 }
217
218 // The class template we found has the same name as the
219 // (dependent) template name being specialized.
220 if (DependentTemplateName *DepTemplate
221 = SpecName.getAsDependentTemplateName()) {
222 if (DepTemplate->isIdentifier() &&
223 DepTemplate->getIdentifier() == Template->getIdentifier())
224 return MemberOfType.getAsOpaquePtr();
225
226 continue;
227 }
228 }
229 }
230 }
231
232 if (isDependent) {
233 // We didn't find our type, but that's okay: it's dependent
234 // anyway.
235 NestedNameSpecifier *NNS = 0;
236 SourceRange Range;
237 if (SS.isSet()) {
238 NNS = (NestedNameSpecifier *)SS.getScopeRep();
239 Range = SourceRange(SS.getRange().getBegin(), NameLoc);
240 } else {
241 NNS = NestedNameSpecifier::Create(Context, &II);
242 Range = SourceRange(NameLoc);
243 }
244
Abramo Bagnarae4da7a02010-05-19 21:37:53 +0000245 return CheckTypenameType(ETK_None, NNS, II, SourceLocation(),
246 Range, NameLoc).getAsOpaquePtr();
Douglas Gregor124b8782010-02-16 19:09:40 +0000247 }
248
249 if (ObjectTypePtr)
250 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
251 << &II;
252 else
253 Diag(NameLoc, diag::err_destructor_class_name);
254
255 return 0;
256}
257
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000258/// \brief Build a C++ typeid expression with a type operand.
259Sema::OwningExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
260 SourceLocation TypeidLoc,
261 TypeSourceInfo *Operand,
262 SourceLocation RParenLoc) {
263 // C++ [expr.typeid]p4:
264 // The top-level cv-qualifiers of the lvalue expression or the type-id
265 // that is the operand of typeid are always ignored.
266 // If the type of the type-id is a class type or a reference to a class
267 // type, the class shall be completely-defined.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000268 Qualifiers Quals;
269 QualType T
270 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
271 Quals);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000272 if (T->getAs<RecordType>() &&
273 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
274 return ExprError();
Daniel Dunbar380c2132010-05-11 21:32:35 +0000275
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000276 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
277 Operand,
278 SourceRange(TypeidLoc, RParenLoc)));
279}
280
281/// \brief Build a C++ typeid expression with an expression operand.
282Sema::OwningExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
283 SourceLocation TypeidLoc,
284 ExprArg Operand,
285 SourceLocation RParenLoc) {
286 bool isUnevaluatedOperand = true;
287 Expr *E = static_cast<Expr *>(Operand.get());
288 if (E && !E->isTypeDependent()) {
289 QualType T = E->getType();
290 if (const RecordType *RecordT = T->getAs<RecordType>()) {
291 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
292 // C++ [expr.typeid]p3:
293 // [...] If the type of the expression is a class type, the class
294 // shall be completely-defined.
295 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
296 return ExprError();
297
298 // C++ [expr.typeid]p3:
299 // When typeid is applied to an expression other than an lvalue of a
300 // polymorphic class type [...] [the] expression is an unevaluated
301 // operand. [...]
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000302 if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000303 isUnevaluatedOperand = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000304
305 // We require a vtable to query the type at run time.
306 MarkVTableUsed(TypeidLoc, RecordD);
307 }
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000308 }
309
310 // C++ [expr.typeid]p4:
311 // [...] If the type of the type-id is a reference to a possibly
312 // cv-qualified type, the result of the typeid expression refers to a
313 // std::type_info object representing the cv-unqualified referenced
314 // type.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000315 Qualifiers Quals;
316 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
317 if (!Context.hasSameType(T, UnqualT)) {
318 T = UnqualT;
319 ImpCastExprToType(E, UnqualT, CastExpr::CK_NoOp, E->isLvalue(Context));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000320 Operand.release();
321 Operand = Owned(E);
322 }
323 }
324
325 // If this is an unevaluated operand, clear out the set of
326 // declaration references we have been computing and eliminate any
327 // temporaries introduced in its computation.
328 if (isUnevaluatedOperand)
329 ExprEvalContexts.back().Context = Unevaluated;
330
331 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
332 Operand.takeAs<Expr>(),
333 SourceRange(TypeidLoc, RParenLoc)));
334}
335
336/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000337Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000338Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
339 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000340 // Find the std::type_info type.
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000341 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000342 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000343
Chris Lattner572af492008-11-20 05:51:55 +0000344 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCalla24dc2e2009-11-17 02:14:36 +0000345 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
346 LookupQualifiedName(R, StdNamespace);
John McCall1bcee0a2009-12-02 08:25:40 +0000347 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
Chris Lattner572af492008-11-20 05:51:55 +0000348 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000349 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000350
Sebastian Redlc42e1182008-11-11 11:37:55 +0000351 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000352
353 if (isType) {
354 // The operand is a type; handle it as such.
355 TypeSourceInfo *TInfo = 0;
356 QualType T = GetTypeFromParser(TyOrExpr, &TInfo);
357 if (T.isNull())
358 return ExprError();
359
360 if (!TInfo)
361 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000362
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000363 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000364 }
Mike Stump1eb44332009-09-09 15:08:12 +0000365
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000366 // The operand is an expression.
367 return BuildCXXTypeId(TypeInfoType, OpLoc, Owned((Expr*)TyOrExpr), RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000368}
369
Steve Naroff1b273c42007-09-16 14:56:35 +0000370/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000371Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000372Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000373 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000374 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000375 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
376 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000377}
Chris Lattner50dd2892008-02-26 00:51:44 +0000378
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000379/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
380Action::OwningExprResult
381Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
382 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
383}
384
Chris Lattner50dd2892008-02-26 00:51:44 +0000385/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000386Action::OwningExprResult
387Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000388 Expr *Ex = E.takeAs<Expr>();
389 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
390 return ExprError();
391 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
392}
393
394/// CheckCXXThrowOperand - Validate the operand of a throw.
395bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
396 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000397 // A throw-expression initializes a temporary object, called the exception
398 // object, the type of which is determined by removing any top-level
399 // cv-qualifiers from the static type of the operand of throw and adjusting
400 // the type from "array of T" or "function returning T" to "pointer to T"
401 // or "pointer to function returning T", [...]
402 if (E->getType().hasQualifiers())
403 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp,
404 E->isLvalue(Context) == Expr::LV_Valid);
405
Sebastian Redl972041f2009-04-27 20:27:31 +0000406 DefaultFunctionArrayConversion(E);
407
408 // If the type of the exception would be an incomplete type or a pointer
409 // to an incomplete type other than (cv) void the program is ill-formed.
410 QualType Ty = E->getType();
John McCallac418162010-04-22 01:10:34 +0000411 bool isPointer = false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000412 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000413 Ty = Ptr->getPointeeType();
John McCallac418162010-04-22 01:10:34 +0000414 isPointer = true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000415 }
416 if (!isPointer || !Ty->isVoidType()) {
417 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000418 PDiag(isPointer ? diag::err_throw_incomplete_ptr
419 : diag::err_throw_incomplete)
420 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000421 return true;
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000422
Douglas Gregorbf422f92010-04-15 18:05:39 +0000423 if (RequireNonAbstractType(ThrowLoc, E->getType(),
424 PDiag(diag::err_throw_abstract_type)
425 << E->getSourceRange()))
426 return true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000427 }
428
John McCallac418162010-04-22 01:10:34 +0000429 // Initialize the exception result. This implicitly weeds out
430 // abstract types or types with inaccessible copy constructors.
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000431 // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p34.
John McCallac418162010-04-22 01:10:34 +0000432 InitializedEntity Entity =
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000433 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
434 /*NRVO=*/false);
John McCallac418162010-04-22 01:10:34 +0000435 OwningExprResult Res = PerformCopyInitialization(Entity,
436 SourceLocation(),
437 Owned(E));
438 if (Res.isInvalid())
439 return true;
440 E = Res.takeAs<Expr>();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000441
Eli Friedman5ed9b932010-06-03 20:39:03 +0000442 // If the exception has class type, we need additional handling.
443 const RecordType *RecordTy = Ty->getAs<RecordType>();
444 if (!RecordTy)
445 return false;
446 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
447
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000448 // If we are throwing a polymorphic class type or pointer thereof,
449 // exception handling will make use of the vtable.
Eli Friedman5ed9b932010-06-03 20:39:03 +0000450 MarkVTableUsed(ThrowLoc, RD);
451
452 // If the class has a non-trivial destructor, we must be able to call it.
453 if (RD->hasTrivialDestructor())
454 return false;
455
Douglas Gregor1d110e02010-07-01 14:13:13 +0000456 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +0000457 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman5ed9b932010-06-03 20:39:03 +0000458 if (!Destructor)
459 return false;
460
461 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
462 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregored8abf12010-07-08 06:14:04 +0000463 PDiag(diag::err_access_dtor_exception) << Ty);
Sebastian Redl972041f2009-04-27 20:27:31 +0000464 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000465}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000466
Sebastian Redlf53597f2009-03-15 17:47:39 +0000467Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000468 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
469 /// is a non-lvalue expression whose value is the address of the object for
470 /// which the function is called.
471
John McCallea1471e2010-05-20 01:18:31 +0000472 DeclContext *DC = getFunctionLevelDeclContext();
473 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000474 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000475 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000476 MD->getThisType(Context),
477 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000478
Sebastian Redlf53597f2009-03-15 17:47:39 +0000479 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000480}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000481
482/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
483/// Can be interpreted either as function-style casting ("int(x)")
484/// or class type construction ("ClassType(x,y,z)")
485/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000486Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000487Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
488 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000489 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000490 SourceLocation *CommaLocs,
491 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000492 if (!TypeRep)
493 return ExprError();
494
John McCall9d125032010-01-15 18:39:57 +0000495 TypeSourceInfo *TInfo;
496 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
497 if (!TInfo)
498 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000499 unsigned NumExprs = exprs.size();
500 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000501 SourceLocation TyBeginLoc = TypeRange.getBegin();
502 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
503
Sebastian Redlf53597f2009-03-15 17:47:39 +0000504 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000505 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000506 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000507
508 return Owned(CXXUnresolvedConstructExpr::Create(Context,
509 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000510 LParenLoc,
511 Exprs, NumExprs,
512 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000513 }
514
Anders Carlssonbb60a502009-08-27 03:53:50 +0000515 if (Ty->isArrayType())
516 return ExprError(Diag(TyBeginLoc,
517 diag::err_value_init_for_array_type) << FullRange);
518 if (!Ty->isVoidType() &&
519 RequireCompleteType(TyBeginLoc, Ty,
520 PDiag(diag::err_invalid_incomplete_type_use)
521 << FullRange))
522 return ExprError();
Fariborz Jahanianf071e9b2009-10-23 21:01:39 +0000523
Anders Carlssonbb60a502009-08-27 03:53:50 +0000524 if (RequireNonAbstractType(TyBeginLoc, Ty,
525 diag::err_allocation_of_abstract_type))
526 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000527
528
Douglas Gregor506ae412009-01-16 18:33:17 +0000529 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000530 // If the expression list is a single expression, the type conversion
531 // expression is equivalent (in definedness, and if defined in meaning) to the
532 // corresponding cast expression.
533 //
534 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000535 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson41b2dcd2010-04-24 18:38:56 +0000536 CXXBaseSpecifierArray BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000537 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, BasePath,
538 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000539 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000540
541 exprs.release();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000542
543 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
John McCall9d125032010-01-15 18:39:57 +0000544 TInfo, TyBeginLoc, Kind,
Anders Carlsson41b2dcd2010-04-24 18:38:56 +0000545 Exprs[0], BasePath,
546 RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000547 }
548
Douglas Gregored8abf12010-07-08 06:14:04 +0000549 if (Ty->isRecordType()) {
550 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
551 InitializationKind Kind
552 = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
553 LParenLoc, RParenLoc)
554 : InitializationKind::CreateValue(TypeRange.getBegin(),
555 LParenLoc, RParenLoc);
556 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
557 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
558 move(exprs));
Sebastian Redlf53597f2009-03-15 17:47:39 +0000559
Douglas Gregored8abf12010-07-08 06:14:04 +0000560 // FIXME: Improve AST representation?
561 return move(Result);
Douglas Gregor506ae412009-01-16 18:33:17 +0000562 }
563
564 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000565 // If the expression list specifies more than a single value, the type shall
566 // be a class with a suitably declared constructor.
567 //
568 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000569 return ExprError(Diag(CommaLocs[0],
570 diag::err_builtin_func_cast_more_than_one_arg)
571 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000572
573 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregor506ae412009-01-16 18:33:17 +0000574 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000575 // The expression T(), where T is a simple-type-specifier for a non-array
576 // complete object type or the (possibly cv-qualified) void type, creates an
577 // rvalue of the specified type, which is value-initialized.
578 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000579 exprs.release();
Douglas Gregored8abf12010-07-08 06:14:04 +0000580 return Owned(new (Context) CXXScalarValueInitExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000581}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000582
583
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000584/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
585/// @code new (memory) int[size][4] @endcode
586/// or
587/// @code ::new Foo(23, "hello") @endcode
588/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000589Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000590Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000591 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000592 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000593 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000594 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000595 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000596 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000597 // If the specified type is an array, unwrap it and save the expression.
598 if (D.getNumTypeObjects() > 0 &&
599 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
600 DeclaratorChunk &Chunk = D.getTypeObject(0);
601 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000602 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
603 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000604 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000605 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
606 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000607
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000608 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000609 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000610 }
611
Douglas Gregor043cad22009-09-11 00:18:58 +0000612 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000613 if (ArraySize) {
614 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000615 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
616 break;
617
618 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
619 if (Expr *NumElts = (Expr *)Array.NumElts) {
620 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
621 !NumElts->isIntegerConstantExpr(Context)) {
622 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
623 << NumElts->getSourceRange();
624 return ExprError();
625 }
626 }
627 }
628 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000629
John McCalla93c9342009-12-07 02:54:59 +0000630 //FIXME: Store TypeSourceInfo in CXXNew expression.
John McCallbf1a0282010-06-04 23:28:52 +0000631 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
632 QualType AllocType = TInfo->getType();
Chris Lattnereaaebc72009-04-25 08:06:05 +0000633 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000634 return ExprError();
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000635
636 SourceRange R = TInfo->getTypeLoc().getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000637 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000638 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000639 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000640 PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000641 TypeIdParens,
Mike Stump1eb44332009-09-09 15:08:12 +0000642 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000643 D.getSourceRange().getBegin(),
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000644 R,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000645 Owned(ArraySize),
646 ConstructorLParen,
647 move(ConstructorArgs),
648 ConstructorRParen);
649}
650
Mike Stump1eb44332009-09-09 15:08:12 +0000651Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000652Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
653 SourceLocation PlacementLParen,
654 MultiExprArg PlacementArgs,
655 SourceLocation PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000656 SourceRange TypeIdParens,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000657 QualType AllocType,
658 SourceLocation TypeLoc,
659 SourceRange TypeRange,
660 ExprArg ArraySizeE,
661 SourceLocation ConstructorLParen,
662 MultiExprArg ConstructorArgs,
663 SourceLocation ConstructorRParen) {
664 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000665 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000666
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000667 // Per C++0x [expr.new]p5, the type being constructed may be a
668 // typedef of an array type.
669 if (!ArraySizeE.get()) {
670 if (const ConstantArrayType *Array
671 = Context.getAsConstantArrayType(AllocType)) {
672 ArraySizeE = Owned(new (Context) IntegerLiteral(Array->getSize(),
673 Context.getSizeType(),
674 TypeRange.getEnd()));
675 AllocType = Array->getElementType();
676 }
677 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000678
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000679 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000680
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000681 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
682 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000683 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000684 if (ArraySize && !ArraySize->isTypeDependent()) {
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000685
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000686 QualType SizeType = ArraySize->getType();
Douglas Gregorc30614b2010-06-29 23:17:37 +0000687
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000688 OwningExprResult ConvertedSize
689 = ConvertToIntegralOrEnumerationType(StartLoc, move(ArraySizeE),
690 PDiag(diag::err_array_size_not_integral),
691 PDiag(diag::err_array_size_incomplete_type)
692 << ArraySize->getSourceRange(),
693 PDiag(diag::err_array_size_explicit_conversion),
694 PDiag(diag::note_array_size_conversion),
695 PDiag(diag::err_array_size_ambiguous_conversion),
696 PDiag(diag::note_array_size_conversion),
697 PDiag(getLangOptions().CPlusPlus0x? 0
698 : diag::ext_array_size_conversion));
699 if (ConvertedSize.isInvalid())
700 return ExprError();
701
702 ArraySize = ConvertedSize.takeAs<Expr>();
703 ArraySizeE = Owned(ArraySize);
704 SizeType = ArraySize->getType();
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000705 if (!SizeType->isIntegralOrEnumerationType())
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000706 return ExprError();
707
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000708 // Let's see if this is a constant < 0. If so, we reject it out of hand.
709 // We don't care about special rules, so we tell the machinery it's not
710 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000711 if (!ArraySize->isValueDependent()) {
712 llvm::APSInt Value;
713 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
714 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000715 llvm::APInt::getNullValue(Value.getBitWidth()),
716 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000717 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
718 diag::err_typecheck_negative_array_size)
719 << ArraySize->getSourceRange());
Douglas Gregor4bd40312010-07-13 15:54:32 +0000720 } else if (TypeIdParens.isValid()) {
721 // Can't have dynamic array size when the type-id is in parentheses.
722 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
723 << ArraySize->getSourceRange()
724 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
725 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
726
727 TypeIdParens = SourceRange();
Sebastian Redl28507842009-02-26 14:39:58 +0000728 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000729 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000730
Eli Friedman73c39ab2009-10-20 08:27:19 +0000731 ImpCastExprToType(ArraySize, Context.getSizeType(),
732 CastExpr::CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000733 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000734
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000735 FunctionDecl *OperatorNew = 0;
736 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000737 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
738 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000739
Sebastian Redl28507842009-02-26 14:39:58 +0000740 if (!AllocType->isDependentType() &&
741 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
742 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000743 SourceRange(PlacementLParen, PlacementRParen),
744 UseGlobal, AllocType, ArraySize, PlaceArgs,
745 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000746 return ExprError();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000747 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000748 if (OperatorNew) {
749 // Add default arguments, if any.
750 const FunctionProtoType *Proto =
751 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000752 VariadicCallType CallType =
753 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Anders Carlsson28e94832010-05-03 02:07:56 +0000754
755 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
756 Proto, 1, PlaceArgs, NumPlaceArgs,
757 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000758 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000759
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000760 NumPlaceArgs = AllPlaceArgs.size();
761 if (NumPlaceArgs > 0)
762 PlaceArgs = &AllPlaceArgs[0];
763 }
764
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000765 bool Init = ConstructorLParen.isValid();
766 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000767 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000768 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
769 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000770 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
771
Anders Carlsson48c95012010-05-03 15:45:23 +0000772 // Array 'new' can't have any initializers.
Anders Carlsson55cbd6e2010-05-16 16:24:20 +0000773 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlsson48c95012010-05-03 15:45:23 +0000774 SourceRange InitRange(ConsArgs[0]->getLocStart(),
775 ConsArgs[NumConsArgs - 1]->getLocEnd());
776
777 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
778 return ExprError();
779 }
780
Douglas Gregor99a2e602009-12-16 01:38:02 +0000781 if (!AllocType->isDependentType() &&
782 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
783 // C++0x [expr.new]p15:
784 // A new-expression that creates an object of type T initializes that
785 // object as follows:
786 InitializationKind Kind
787 // - If the new-initializer is omitted, the object is default-
788 // initialized (8.5); if no initialization is performed,
789 // the object has indeterminate value
790 = !Init? InitializationKind::CreateDefault(TypeLoc)
791 // - Otherwise, the new-initializer is interpreted according to the
792 // initialization rules of 8.5 for direct-initialization.
793 : InitializationKind::CreateDirect(TypeLoc,
794 ConstructorLParen,
795 ConstructorRParen);
796
Douglas Gregor99a2e602009-12-16 01:38:02 +0000797 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +0000798 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000799 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000800 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
801 move(ConstructorArgs));
802 if (FullInit.isInvalid())
803 return ExprError();
804
805 // FullInit is our initializer; walk through it to determine if it's a
806 // constructor call, which CXXNewExpr handles directly.
807 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
808 if (CXXBindTemporaryExpr *Binder
809 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
810 FullInitExpr = Binder->getSubExpr();
811 if (CXXConstructExpr *Construct
812 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
813 Constructor = Construct->getConstructor();
814 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
815 AEnd = Construct->arg_end();
816 A != AEnd; ++A)
817 ConvertedConstructorArgs.push_back(A->Retain());
818 } else {
819 // Take the converted initializer.
820 ConvertedConstructorArgs.push_back(FullInit.release());
821 }
822 } else {
823 // No initialization required.
824 }
825
826 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +0000827 NumConsArgs = ConvertedConstructorArgs.size();
828 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000829 }
Douglas Gregor99a2e602009-12-16 01:38:02 +0000830
Douglas Gregor6d908702010-02-26 05:06:18 +0000831 // Mark the new and delete operators as referenced.
832 if (OperatorNew)
833 MarkDeclarationReferenced(StartLoc, OperatorNew);
834 if (OperatorDelete)
835 MarkDeclarationReferenced(StartLoc, OperatorDelete);
836
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000837 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000838
Sebastian Redlf53597f2009-03-15 17:47:39 +0000839 PlacementArgs.release();
840 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000841 ArraySizeE.release();
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000842
843 // FIXME: The TypeSourceInfo should also be included in CXXNewExpr.
Ted Kremenekad7fe862010-02-11 22:51:03 +0000844 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000845 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenekad7fe862010-02-11 22:51:03 +0000846 ArraySize, Constructor, Init,
847 ConsArgs, NumConsArgs, OperatorDelete,
848 ResultType, StartLoc,
849 Init ? ConstructorRParen :
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000850 TypeRange.getEnd()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000851}
852
853/// CheckAllocatedType - Checks that a type is suitable as the allocated type
854/// in a new-expression.
855/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000856bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000857 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000858 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
859 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000860 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000861 return Diag(Loc, diag::err_bad_new_type)
862 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000863 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000864 return Diag(Loc, diag::err_bad_new_type)
865 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000866 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000867 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000868 PDiag(diag::err_new_incomplete_type)
869 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000870 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000871 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000872 diag::err_allocation_of_abstract_type))
873 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000874
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000875 return false;
876}
877
Douglas Gregor6d908702010-02-26 05:06:18 +0000878/// \brief Determine whether the given function is a non-placement
879/// deallocation function.
880static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
881 if (FD->isInvalidDecl())
882 return false;
883
884 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
885 return Method->isUsualDeallocationFunction();
886
887 return ((FD->getOverloadedOperator() == OO_Delete ||
888 FD->getOverloadedOperator() == OO_Array_Delete) &&
889 FD->getNumParams() == 1);
890}
891
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000892/// FindAllocationFunctions - Finds the overloads of operator new and delete
893/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000894bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
895 bool UseGlobal, QualType AllocType,
896 bool IsArray, Expr **PlaceArgs,
897 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000898 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000899 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000900 // --- Choosing an allocation function ---
901 // C++ 5.3.4p8 - 14 & 18
902 // 1) If UseGlobal is true, only look in the global scope. Else, also look
903 // in the scope of the allocated class.
904 // 2) If an array size is given, look for operator new[], else look for
905 // operator new.
906 // 3) The first argument is always size_t. Append the arguments from the
907 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000908
909 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
910 // We don't care about the actual value of this argument.
911 // FIXME: Should the Sema create the expression and embed it in the syntax
912 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000913 IntegerLiteral Size(llvm::APInt::getNullValue(
914 Context.Target.getPointerWidth(0)),
915 Context.getSizeType(),
916 SourceLocation());
917 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000918 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
919
Douglas Gregor6d908702010-02-26 05:06:18 +0000920 // C++ [expr.new]p8:
921 // If the allocated type is a non-array type, the allocation
922 // function’s name is operator new and the deallocation function’s
923 // name is operator delete. If the allocated type is an array
924 // type, the allocation function’s name is operator new[] and the
925 // deallocation function’s name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000926 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
927 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +0000928 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
929 IsArray ? OO_Array_Delete : OO_Delete);
930
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000931 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000932 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000933 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +0000934 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000935 AllocArgs.size(), Record, /*AllowMissing=*/true,
936 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000937 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000938 }
939 if (!OperatorNew) {
940 // Didn't find a member overload. Look for a global one.
941 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000942 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000943 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000944 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
945 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000946 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000947 }
948
John McCall9c82afc2010-04-20 02:18:25 +0000949 // We don't need an operator delete if we're running under
950 // -fno-exceptions.
951 if (!getLangOptions().Exceptions) {
952 OperatorDelete = 0;
953 return false;
954 }
955
Anders Carlssond9583892009-05-31 20:26:12 +0000956 // FindAllocationOverload can change the passed in arguments, so we need to
957 // copy them back.
958 if (NumPlaceArgs > 0)
959 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000960
Douglas Gregor6d908702010-02-26 05:06:18 +0000961 // C++ [expr.new]p19:
962 //
963 // If the new-expression begins with a unary :: operator, the
964 // deallocation function’s name is looked up in the global
965 // scope. Otherwise, if the allocated type is a class type T or an
966 // array thereof, the deallocation function’s name is looked up in
967 // the scope of T. If this lookup fails to find the name, or if
968 // the allocated type is not a class type or array thereof, the
969 // deallocation function’s name is looked up in the global scope.
970 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
971 if (AllocType->isRecordType() && !UseGlobal) {
972 CXXRecordDecl *RD
973 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
974 LookupQualifiedName(FoundDelete, RD);
975 }
John McCall90c8c572010-03-18 08:19:33 +0000976 if (FoundDelete.isAmbiguous())
977 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +0000978
979 if (FoundDelete.empty()) {
980 DeclareGlobalNewDelete();
981 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
982 }
983
984 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +0000985
986 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
987
John McCall90c8c572010-03-18 08:19:33 +0000988 if (NumPlaceArgs > 0) {
Douglas Gregor6d908702010-02-26 05:06:18 +0000989 // C++ [expr.new]p20:
990 // A declaration of a placement deallocation function matches the
991 // declaration of a placement allocation function if it has the
992 // same number of parameters and, after parameter transformations
993 // (8.3.5), all parameter types except the first are
994 // identical. [...]
995 //
996 // To perform this comparison, we compute the function type that
997 // the deallocation function should have, and use that type both
998 // for template argument deduction and for comparison purposes.
999 QualType ExpectedFunctionType;
1000 {
1001 const FunctionProtoType *Proto
1002 = OperatorNew->getType()->getAs<FunctionProtoType>();
1003 llvm::SmallVector<QualType, 4> ArgTypes;
1004 ArgTypes.push_back(Context.VoidPtrTy);
1005 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1006 ArgTypes.push_back(Proto->getArgType(I));
1007
1008 ExpectedFunctionType
1009 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
1010 ArgTypes.size(),
1011 Proto->isVariadic(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001012 0, false, false, 0, 0,
1013 FunctionType::ExtInfo());
Douglas Gregor6d908702010-02-26 05:06:18 +00001014 }
1015
1016 for (LookupResult::iterator D = FoundDelete.begin(),
1017 DEnd = FoundDelete.end();
1018 D != DEnd; ++D) {
1019 FunctionDecl *Fn = 0;
1020 if (FunctionTemplateDecl *FnTmpl
1021 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1022 // Perform template argument deduction to try to match the
1023 // expected function type.
1024 TemplateDeductionInfo Info(Context, StartLoc);
1025 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1026 continue;
1027 } else
1028 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1029
1030 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001031 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001032 }
1033 } else {
1034 // C++ [expr.new]p20:
1035 // [...] Any non-placement deallocation function matches a
1036 // non-placement allocation function. [...]
1037 for (LookupResult::iterator D = FoundDelete.begin(),
1038 DEnd = FoundDelete.end();
1039 D != DEnd; ++D) {
1040 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1041 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001042 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001043 }
1044 }
1045
1046 // C++ [expr.new]p20:
1047 // [...] If the lookup finds a single matching deallocation
1048 // function, that function will be called; otherwise, no
1049 // deallocation function will be called.
1050 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001051 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001052
1053 // C++0x [expr.new]p20:
1054 // If the lookup finds the two-parameter form of a usual
1055 // deallocation function (3.7.4.2) and that function, considered
1056 // as a placement deallocation function, would have been
1057 // selected as a match for the allocation function, the program
1058 // is ill-formed.
1059 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1060 isNonPlacementDeallocationFunction(OperatorDelete)) {
1061 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1062 << SourceRange(PlaceArgs[0]->getLocStart(),
1063 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1064 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1065 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001066 } else {
1067 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001068 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001069 }
1070 }
1071
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001072 return false;
1073}
1074
Sebastian Redl7f662392008-12-04 22:20:51 +00001075/// FindAllocationOverload - Find an fitting overload for the allocation
1076/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001077bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1078 DeclarationName Name, Expr** Args,
1079 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +00001080 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001081 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1082 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001083 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001084 if (AllowMissing)
1085 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001086 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001087 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001088 }
1089
John McCall90c8c572010-03-18 08:19:33 +00001090 if (R.isAmbiguous())
1091 return true;
1092
1093 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001094
John McCall5769d612010-02-08 23:07:23 +00001095 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001096 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1097 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001098 // Even member operator new/delete are implicitly treated as
1099 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001100 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001101
John McCall9aa472c2010-03-19 07:35:19 +00001102 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1103 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001104 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1105 Candidates,
1106 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001107 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001108 }
1109
John McCall9aa472c2010-03-19 07:35:19 +00001110 FunctionDecl *Fn = cast<FunctionDecl>(D);
1111 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001112 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001113 }
1114
1115 // Do the resolution.
1116 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001117 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001118 case OR_Success: {
1119 // Got one!
1120 FunctionDecl *FnDecl = Best->Function;
1121 // The first argument is size_t, and the first parameter must be size_t,
1122 // too. This is checked on declaration and can be assumed. (It can't be
1123 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001124 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001125 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1126 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001127 OwningExprResult Result
1128 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
1129 FnDecl->getParamDecl(i)),
1130 SourceLocation(),
1131 Owned(Args[i]->Retain()));
1132 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001133 return true;
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001134
1135 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001136 }
1137 Operator = FnDecl;
John McCall9aa472c2010-03-19 07:35:19 +00001138 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001139 return false;
1140 }
1141
1142 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +00001143 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001144 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001145 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001146 return true;
1147
1148 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +00001149 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +00001150 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001151 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001152 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001153
1154 case OR_Deleted:
1155 Diag(StartLoc, diag::err_ovl_deleted_call)
1156 << Best->Function->isDeleted()
1157 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001158 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001159 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001160 }
1161 assert(false && "Unreachable, bad result from BestViableFunction");
1162 return true;
1163}
1164
1165
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001166/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1167/// delete. These are:
1168/// @code
1169/// void* operator new(std::size_t) throw(std::bad_alloc);
1170/// void* operator new[](std::size_t) throw(std::bad_alloc);
1171/// void operator delete(void *) throw();
1172/// void operator delete[](void *) throw();
1173/// @endcode
1174/// Note that the placement and nothrow forms of new are *not* implicitly
1175/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001176void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001177 if (GlobalNewDeleteDeclared)
1178 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001179
1180 // C++ [basic.std.dynamic]p2:
1181 // [...] The following allocation and deallocation functions (18.4) are
1182 // implicitly declared in global scope in each translation unit of a
1183 // program
1184 //
1185 // void* operator new(std::size_t) throw(std::bad_alloc);
1186 // void* operator new[](std::size_t) throw(std::bad_alloc);
1187 // void operator delete(void*) throw();
1188 // void operator delete[](void*) throw();
1189 //
1190 // These implicit declarations introduce only the function names operator
1191 // new, operator new[], operator delete, operator delete[].
1192 //
1193 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1194 // "std" or "bad_alloc" as necessary to form the exception specification.
1195 // However, we do not make these implicit declarations visible to name
1196 // lookup.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001197 if (!StdBadAlloc) {
1198 // The "std::bad_alloc" class has not yet been declared, so build it
1199 // implicitly.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001200 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
Douglas Gregor66992202010-06-29 17:53:46 +00001201 getStdNamespace(),
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001202 SourceLocation(),
1203 &PP.getIdentifierTable().get("bad_alloc"),
1204 SourceLocation(), 0);
1205 StdBadAlloc->setImplicit(true);
1206 }
1207
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001208 GlobalNewDeleteDeclared = true;
1209
1210 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1211 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001212 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001213
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001214 DeclareGlobalAllocationFunction(
1215 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001216 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001217 DeclareGlobalAllocationFunction(
1218 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001219 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001220 DeclareGlobalAllocationFunction(
1221 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1222 Context.VoidTy, VoidPtr);
1223 DeclareGlobalAllocationFunction(
1224 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1225 Context.VoidTy, VoidPtr);
1226}
1227
1228/// DeclareGlobalAllocationFunction - Declares a single implicit global
1229/// allocation function if it doesn't already exist.
1230void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001231 QualType Return, QualType Argument,
1232 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001233 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1234
1235 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001236 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001237 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001238 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001239 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001240 // Only look at non-template functions, as it is the predefined,
1241 // non-templated allocation function we are trying to declare here.
1242 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1243 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001244 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001245 Func->getParamDecl(0)->getType().getUnqualifiedType());
1246 // FIXME: Do we need to check for default arguments here?
1247 if (Func->getNumParams() == 1 && InitialParamType == Argument)
1248 return;
1249 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001250 }
1251 }
1252
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001253 QualType BadAllocType;
1254 bool HasBadAllocExceptionSpec
1255 = (Name.getCXXOverloadedOperator() == OO_New ||
1256 Name.getCXXOverloadedOperator() == OO_Array_New);
1257 if (HasBadAllocExceptionSpec) {
1258 assert(StdBadAlloc && "Must have std::bad_alloc declared");
1259 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
1260 }
1261
1262 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1263 true, false,
1264 HasBadAllocExceptionSpec? 1 : 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00001265 &BadAllocType,
1266 FunctionType::ExtInfo());
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001267 FunctionDecl *Alloc =
1268 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001269 FnType, /*TInfo=*/0, FunctionDecl::None,
1270 FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001271 Alloc->setImplicit();
Nuno Lopesfc284482009-12-16 16:59:22 +00001272
1273 if (AddMallocAttr)
1274 Alloc->addAttr(::new (Context) MallocAttr());
1275
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001276 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00001277 0, Argument, /*TInfo=*/0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001278 VarDecl::None,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001279 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00001280 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001281
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001282 // FIXME: Also add this declaration to the IdentifierResolver, but
1283 // make sure it is at the end of the chain to coincide with the
1284 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001285 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001286}
1287
Anders Carlsson78f74552009-11-15 18:45:20 +00001288bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1289 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00001290 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001291 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001292 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001293 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +00001294
John McCalla24dc2e2009-11-17 02:14:36 +00001295 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001296 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001297
Chandler Carruth23893242010-06-28 00:30:51 +00001298 Found.suppressDiagnostics();
1299
Anders Carlsson78f74552009-11-15 18:45:20 +00001300 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1301 F != FEnd; ++F) {
1302 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
1303 if (Delete->isUsualDeallocationFunction()) {
1304 Operator = Delete;
Chandler Carruth23893242010-06-28 00:30:51 +00001305 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1306 F.getPair());
Anders Carlsson78f74552009-11-15 18:45:20 +00001307 return false;
1308 }
1309 }
1310
1311 // We did find operator delete/operator delete[] declarations, but
1312 // none of them were suitable.
1313 if (!Found.empty()) {
1314 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1315 << Name << RD;
1316
1317 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1318 F != FEnd; ++F) {
Douglas Gregorb0fd4832010-04-25 20:55:08 +00001319 Diag((*F)->getLocation(), diag::note_member_declared_here)
Anders Carlsson78f74552009-11-15 18:45:20 +00001320 << Name;
1321 }
1322
1323 return true;
1324 }
1325
1326 // Look for a global declaration.
1327 DeclareGlobalNewDelete();
1328 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1329
1330 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1331 Expr* DeallocArgs[1];
1332 DeallocArgs[0] = &Null;
1333 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1334 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1335 Operator))
1336 return true;
1337
1338 assert(Operator && "Did not find a deallocation function!");
1339 return false;
1340}
1341
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001342/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1343/// @code ::delete ptr; @endcode
1344/// or
1345/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +00001346Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001347Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +00001348 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001349 // C++ [expr.delete]p1:
1350 // The operand shall have a pointer type, or a class type having a single
1351 // conversion function to a pointer type. The result has type void.
1352 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001353 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1354
Anders Carlssond67c4c32009-08-16 20:29:29 +00001355 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001356
Sebastian Redlf53597f2009-03-15 17:47:39 +00001357 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +00001358 if (!Ex->isTypeDependent()) {
1359 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001360
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001361 if (const RecordType *Record = Type->getAs<RecordType>()) {
John McCall32daa422010-03-31 01:36:47 +00001362 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1363
Fariborz Jahanian53462782009-09-11 21:44:33 +00001364 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCall32daa422010-03-31 01:36:47 +00001365 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001366 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001367 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001368 NamedDecl *D = I.getDecl();
1369 if (isa<UsingShadowDecl>(D))
1370 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1371
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001372 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001373 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001374 continue;
1375
John McCall32daa422010-03-31 01:36:47 +00001376 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001377
1378 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1379 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1380 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001381 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001382 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001383 if (ObjectPtrConversions.size() == 1) {
1384 // We have a single conversion to a pointer-to-object type. Perform
1385 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001386 // TODO: don't redo the conversion calculation.
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001387 Operand.release();
John McCall32daa422010-03-31 01:36:47 +00001388 if (!PerformImplicitConversion(Ex,
1389 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +00001390 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001391 Operand = Owned(Ex);
1392 Type = Ex->getType();
1393 }
1394 }
1395 else if (ObjectPtrConversions.size() > 1) {
1396 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1397 << Type << Ex->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001398 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1399 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001400 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001401 }
Sebastian Redl28507842009-02-26 14:39:58 +00001402 }
1403
Sebastian Redlf53597f2009-03-15 17:47:39 +00001404 if (!Type->isPointerType())
1405 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1406 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001407
Ted Kremenek6217b802009-07-29 21:53:49 +00001408 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor94a61572010-05-24 17:01:56 +00001409 if (Pointee->isVoidType() && !isSFINAEContext()) {
1410 // The C++ standard bans deleting a pointer to a non-object type, which
1411 // effectively bans deletion of "void*". However, most compilers support
1412 // this, so we treat it as a warning unless we're in a SFINAE context.
1413 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1414 << Type << Ex->getSourceRange();
1415 } else if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001416 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1417 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001418 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001419 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +00001420 PDiag(diag::warn_delete_incomplete)
1421 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001422 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +00001423
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001424 // C++ [expr.delete]p2:
1425 // [Note: a pointer to a const type can be the operand of a
1426 // delete-expression; it is not necessary to cast away the constness
1427 // (5.2.11) of the pointer expression before it is used as the operand
1428 // of the delete-expression. ]
1429 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
1430 CastExpr::CK_NoOp);
1431
1432 // Update the operand.
1433 Operand.take();
1434 Operand = ExprArg(*this, Ex);
1435
Anders Carlssond67c4c32009-08-16 20:29:29 +00001436 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1437 ArrayForm ? OO_Array_Delete : OO_Delete);
1438
Anders Carlsson78f74552009-11-15 18:45:20 +00001439 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
1440 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1441
1442 if (!UseGlobal &&
1443 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001444 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001445
Anders Carlsson78f74552009-11-15 18:45:20 +00001446 if (!RD->hasTrivialDestructor())
Douglas Gregordb89f282010-07-01 22:47:18 +00001447 if (const CXXDestructorDecl *Dtor = LookupDestructor(RD))
Mike Stump1eb44332009-09-09 15:08:12 +00001448 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001449 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +00001450 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001451
Anders Carlssond67c4c32009-08-16 20:29:29 +00001452 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001453 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001454 DeclareGlobalNewDelete();
1455 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001456 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +00001457 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001458 OperatorDelete))
1459 return ExprError();
1460 }
Mike Stump1eb44332009-09-09 15:08:12 +00001461
John McCall9c82afc2010-04-20 02:18:25 +00001462 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1463
Sebastian Redl28507842009-02-26 14:39:58 +00001464 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001465 }
1466
Sebastian Redlf53597f2009-03-15 17:47:39 +00001467 Operand.release();
1468 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001469 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001470}
1471
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001472/// \brief Check the use of the given variable as a C++ condition in an if,
1473/// while, do-while, or switch statement.
Douglas Gregor586596f2010-05-06 17:25:47 +00001474Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
1475 SourceLocation StmtLoc,
1476 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001477 QualType T = ConditionVar->getType();
1478
1479 // C++ [stmt.select]p2:
1480 // The declarator shall not specify a function or an array.
1481 if (T->isFunctionType())
1482 return ExprError(Diag(ConditionVar->getLocation(),
1483 diag::err_invalid_use_of_function_type)
1484 << ConditionVar->getSourceRange());
1485 else if (T->isArrayType())
1486 return ExprError(Diag(ConditionVar->getLocation(),
1487 diag::err_invalid_use_of_array_type)
1488 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001489
Douglas Gregor586596f2010-05-06 17:25:47 +00001490 Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1491 ConditionVar->getLocation(),
1492 ConditionVar->getType().getNonReferenceType());
1493 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc)) {
1494 Condition->Destroy(Context);
1495 return ExprError();
1496 }
1497
1498 return Owned(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001499}
1500
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001501/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1502bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1503 // C++ 6.4p4:
1504 // The value of a condition that is an initialized declaration in a statement
1505 // other than a switch statement is the value of the declared variable
1506 // implicitly converted to type bool. If that conversion is ill-formed, the
1507 // program is ill-formed.
1508 // The value of a condition that is an expression is the value of the
1509 // expression, implicitly converted to bool.
1510 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001511 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001512}
Douglas Gregor77a52232008-09-12 00:47:35 +00001513
1514/// Helper function to determine whether this is the (deprecated) C++
1515/// conversion from a string literal to a pointer to non-const char or
1516/// non-const wchar_t (for narrow and wide string literals,
1517/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001518bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001519Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1520 // Look inside the implicit cast, if it exists.
1521 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1522 From = Cast->getSubExpr();
1523
1524 // A string literal (2.13.4) that is not a wide string literal can
1525 // be converted to an rvalue of type "pointer to char"; a wide
1526 // string literal can be converted to an rvalue of type "pointer
1527 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00001528 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00001529 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001530 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001531 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001532 // This conversion is considered only when there is an
1533 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001534 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001535 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1536 (!StrLit->isWide() &&
1537 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1538 ToPointeeType->getKind() == BuiltinType::Char_S))))
1539 return true;
1540 }
1541
1542 return false;
1543}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001544
Douglas Gregorba70ab62010-04-16 22:17:36 +00001545static Sema::OwningExprResult BuildCXXCastArgument(Sema &S,
1546 SourceLocation CastLoc,
1547 QualType Ty,
1548 CastExpr::CastKind Kind,
1549 CXXMethodDecl *Method,
1550 Sema::ExprArg Arg) {
1551 Expr *From = Arg.takeAs<Expr>();
1552
1553 switch (Kind) {
1554 default: assert(0 && "Unhandled cast kind!");
1555 case CastExpr::CK_ConstructorConversion: {
1556 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
1557
1558 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
1559 Sema::MultiExprArg(S, (void **)&From, 1),
1560 CastLoc, ConstructorArgs))
1561 return S.ExprError();
1562
1563 Sema::OwningExprResult Result =
1564 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
1565 move_arg(ConstructorArgs));
1566 if (Result.isInvalid())
1567 return S.ExprError();
1568
1569 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1570 }
1571
1572 case CastExpr::CK_UserDefinedConversion: {
1573 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1574
1575 // Create an implicit call expr that calls it.
1576 // FIXME: pass the FoundDecl for the user-defined conversion here
1577 CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method);
1578 return S.MaybeBindToTemporary(CE);
1579 }
1580 }
1581}
1582
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001583/// PerformImplicitConversion - Perform an implicit conversion of the
1584/// expression From to the type ToType using the pre-computed implicit
1585/// conversion sequence ICS. Returns true if there was an error, false
1586/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001587/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001588/// used in the error message.
1589bool
1590Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1591 const ImplicitConversionSequence &ICS,
Douglas Gregor68647482009-12-16 03:45:30 +00001592 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall1d318332010-01-12 00:44:57 +00001593 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001594 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001595 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001596 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001597 return true;
1598 break;
1599
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001600 case ImplicitConversionSequence::UserDefinedConversion: {
1601
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001602 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1603 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001604 QualType BeforeToType;
1605 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001606 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001607
1608 // If the user-defined conversion is specified by a conversion function,
1609 // the initial standard conversion sequence converts the source type to
1610 // the implicit object parameter of the conversion function.
1611 BeforeToType = Context.getTagDeclType(Conv->getParent());
1612 } else if (const CXXConstructorDecl *Ctor =
1613 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001614 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001615 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001616 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001617 // If the user-defined conversion is specified by a constructor, the
1618 // initial standard conversion sequence converts the source type to the
1619 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001620 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1621 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001622 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001623 else
1624 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001625 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001626 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001627 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001628 ICS.UserDefined.Before, AA_Converting,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001629 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001630 return true;
1631 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001632
Anders Carlsson0aebc812009-09-09 21:33:21 +00001633 OwningExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00001634 = BuildCXXCastArgument(*this,
1635 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00001636 ToType.getNonReferenceType(),
1637 CastKind, cast<CXXMethodDecl>(FD),
1638 Owned(From));
1639
1640 if (CastArg.isInvalid())
1641 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001642
1643 From = CastArg.takeAs<Expr>();
1644
Eli Friedmand8889622009-11-27 04:41:50 +00001645 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor68647482009-12-16 03:45:30 +00001646 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001647 }
John McCall1d318332010-01-12 00:44:57 +00001648
1649 case ImplicitConversionSequence::AmbiguousConversion:
1650 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1651 PDiag(diag::err_typecheck_ambiguous_condition)
1652 << From->getSourceRange());
1653 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001654
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001655 case ImplicitConversionSequence::EllipsisConversion:
1656 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001657 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001658
1659 case ImplicitConversionSequence::BadConversion:
1660 return true;
1661 }
1662
1663 // Everything went well.
1664 return false;
1665}
1666
1667/// PerformImplicitConversion - Perform an implicit conversion of the
1668/// expression From to the type ToType by following the standard
1669/// conversion sequence SCS. Returns true if there was an error, false
1670/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001671/// expression. Flavor is the context in which we're performing this
1672/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001673bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001674Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001675 const StandardConversionSequence& SCS,
Douglas Gregor68647482009-12-16 03:45:30 +00001676 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001677 // Overall FIXME: we are recomputing too many types here and doing far too
1678 // much extra work. What this means is that we need to keep track of more
1679 // information that is computed when we try the implicit conversion initially,
1680 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001681 QualType FromType = From->getType();
1682
Douglas Gregor225c41e2008-11-03 19:09:14 +00001683 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001684 // FIXME: When can ToType be a reference type?
1685 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001686 if (SCS.Second == ICK_Derived_To_Base) {
1687 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1688 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1689 MultiExprArg(*this, (void **)&From, 1),
1690 /*FIXME:ConstructLoc*/SourceLocation(),
1691 ConstructorArgs))
1692 return true;
1693 OwningExprResult FromResult =
1694 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1695 ToType, SCS.CopyConstructor,
1696 move_arg(ConstructorArgs));
1697 if (FromResult.isInvalid())
1698 return true;
1699 From = FromResult.takeAs<Expr>();
1700 return false;
1701 }
Mike Stump1eb44332009-09-09 15:08:12 +00001702 OwningExprResult FromResult =
1703 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1704 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001705 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001706
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001707 if (FromResult.isInvalid())
1708 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001709
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001710 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001711 return false;
1712 }
1713
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001714 // Resolve overloaded function references.
1715 if (Context.hasSameType(FromType, Context.OverloadTy)) {
1716 DeclAccessPair Found;
1717 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1718 true, Found);
1719 if (!Fn)
1720 return true;
1721
1722 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1723 return true;
1724
1725 From = FixOverloadedFunctionReference(From, Found, Fn);
1726 FromType = From->getType();
1727 }
1728
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001729 // Perform the first implicit conversion.
1730 switch (SCS.First) {
1731 case ICK_Identity:
1732 case ICK_Lvalue_To_Rvalue:
1733 // Nothing to do.
1734 break;
1735
1736 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001737 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001738 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001739 break;
1740
1741 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001742 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001743 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001744 break;
1745
1746 default:
1747 assert(false && "Improper first standard conversion");
1748 break;
1749 }
1750
1751 // Perform the second implicit conversion
1752 switch (SCS.Second) {
1753 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001754 // If both sides are functions (or pointers/references to them), there could
1755 // be incompatible exception declarations.
1756 if (CheckExceptionSpecCompatibility(From, ToType))
1757 return true;
1758 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001759 break;
1760
Douglas Gregor43c79c22009-12-09 00:47:37 +00001761 case ICK_NoReturn_Adjustment:
1762 // If both sides are functions (or pointers/references to them), there could
1763 // be incompatible exception declarations.
1764 if (CheckExceptionSpecCompatibility(From, ToType))
1765 return true;
1766
1767 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1768 CastExpr::CK_NoOp);
1769 break;
1770
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001771 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001772 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001773 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1774 break;
1775
1776 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001777 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001778 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1779 break;
1780
1781 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001782 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001783 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1784 break;
1785
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001786 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001787 if (ToType->isRealFloatingType())
Eli Friedman73c39ab2009-10-20 08:27:19 +00001788 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1789 else
1790 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1791 break;
1792
Douglas Gregorf9201e02009-02-11 23:02:49 +00001793 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001794 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001795 break;
1796
Anders Carlsson61faec12009-09-12 04:46:44 +00001797 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001798 if (SCS.IncompatibleObjC) {
1799 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001800 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001801 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00001802 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00001803 << From->getSourceRange();
1804 }
1805
Anders Carlsson61faec12009-09-12 04:46:44 +00001806
1807 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001808 CXXBaseSpecifierArray BasePath;
1809 if (CheckPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001810 return true;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001811 ImpCastExprToType(From, ToType, Kind, /*isLvalue=*/false, BasePath);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001812 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001813 }
1814
1815 case ICK_Pointer_Member: {
1816 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001817 CXXBaseSpecifierArray BasePath;
1818 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath,
1819 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001820 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001821 if (CheckExceptionSpecCompatibility(From, ToType))
1822 return true;
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001823 ImpCastExprToType(From, ToType, Kind, /*isLvalue=*/false, BasePath);
Anders Carlsson61faec12009-09-12 04:46:44 +00001824 break;
1825 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001826 case ICK_Boolean_Conversion: {
1827 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1828 if (FromType->isMemberPointerType())
1829 Kind = CastExpr::CK_MemberPointerToBoolean;
1830
1831 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001832 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001833 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001834
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001835 case ICK_Derived_To_Base: {
1836 CXXBaseSpecifierArray BasePath;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001837 if (CheckDerivedToBaseConversion(From->getType(),
1838 ToType.getNonReferenceType(),
1839 From->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001840 From->getSourceRange(),
1841 &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001842 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001843 return true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001844
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001845 ImpCastExprToType(From, ToType.getNonReferenceType(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001846 CastExpr::CK_DerivedToBase,
1847 /*isLvalue=*/(From->getType()->isRecordType() &&
1848 From->isLvalue(Context) == Expr::LV_Valid),
1849 BasePath);
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001850 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001851 }
1852
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001853 case ICK_Vector_Conversion:
1854 ImpCastExprToType(From, ToType, CastExpr::CK_BitCast);
1855 break;
1856
1857 case ICK_Vector_Splat:
1858 ImpCastExprToType(From, ToType, CastExpr::CK_VectorSplat);
1859 break;
1860
1861 case ICK_Complex_Real:
1862 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1863 break;
1864
1865 case ICK_Lvalue_To_Rvalue:
1866 case ICK_Array_To_Pointer:
1867 case ICK_Function_To_Pointer:
1868 case ICK_Qualification:
1869 case ICK_Num_Conversion_Kinds:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001870 assert(false && "Improper second standard conversion");
1871 break;
1872 }
1873
1874 switch (SCS.Third) {
1875 case ICK_Identity:
1876 // Nothing to do.
1877 break;
1878
1879 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001880 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1881 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001882 ImpCastExprToType(From, ToType.getNonReferenceType(),
Anders Carlssonf1b48b72010-04-24 16:57:13 +00001883 CastExpr::CK_NoOp, ToType->isLValueReferenceType());
Douglas Gregora9bff302010-02-28 18:30:25 +00001884
1885 if (SCS.DeprecatedStringLiteralToCharPtr)
1886 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
1887 << ToType.getNonReferenceType();
1888
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001889 break;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001890
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001891 default:
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001892 assert(false && "Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001893 break;
1894 }
1895
1896 return false;
1897}
1898
Sebastian Redl64b45f72009-01-05 20:52:13 +00001899Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1900 SourceLocation KWLoc,
1901 SourceLocation LParen,
1902 TypeTy *Ty,
1903 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001904 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001905
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001906 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1907 // all traits except __is_class, __is_enum and __is_union require a the type
1908 // to be complete.
1909 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001910 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001911 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001912 return ExprError();
1913 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001914
1915 // There is no point in eagerly computing the value. The traits are designed
1916 // to be used from type trait templates, so Ty will be a template parameter
1917 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001918 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1919 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001920}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001921
1922QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001923 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001924 const char *OpSpelling = isIndirect ? "->*" : ".*";
1925 // C++ 5.5p2
1926 // The binary operator .* [p3: ->*] binds its second operand, which shall
1927 // be of type "pointer to member of T" (where T is a completely-defined
1928 // class type) [...]
1929 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001930 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001931 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001932 Diag(Loc, diag::err_bad_memptr_rhs)
1933 << OpSpelling << RType << rex->getSourceRange();
1934 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001935 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001936
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001937 QualType Class(MemPtr->getClass(), 0);
1938
Sebastian Redl59fc2692010-04-10 10:14:54 +00001939 if (RequireCompleteType(Loc, Class, diag::err_memptr_rhs_to_incomplete))
1940 return QualType();
1941
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001942 // C++ 5.5p2
1943 // [...] to its first operand, which shall be of class T or of a class of
1944 // which T is an unambiguous and accessible base class. [p3: a pointer to
1945 // such a class]
1946 QualType LType = lex->getType();
1947 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001948 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001949 LType = Ptr->getPointeeType().getNonReferenceType();
1950 else {
1951 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001952 << OpSpelling << 1 << LType
Douglas Gregor849b2432010-03-31 17:46:05 +00001953 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001954 return QualType();
1955 }
1956 }
1957
Douglas Gregora4923eb2009-11-16 21:35:15 +00001958 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00001959 // If we want to check the hierarchy, we need a complete type.
1960 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
1961 << OpSpelling << (int)isIndirect)) {
1962 return QualType();
1963 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001964 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001965 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001966 // FIXME: Would it be useful to print full ambiguity paths, or is that
1967 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001968 if (!IsDerivedFrom(LType, Class, Paths) ||
1969 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1970 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00001971 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001972 return QualType();
1973 }
Eli Friedman3005efe2010-01-16 00:00:48 +00001974 // Cast LHS to type of use.
1975 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
1976 bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001977
1978 CXXBaseSpecifierArray BasePath;
1979 BuildBasePathArray(Paths, BasePath);
1980 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue,
1981 BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001982 }
1983
Douglas Gregored8abf12010-07-08 06:14:04 +00001984 if (isa<CXXScalarValueInitExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00001985 // Diagnose use of pointer-to-member type which when used as
1986 // the functional cast in a pointer-to-member expression.
1987 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1988 return QualType();
1989 }
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001990 // C++ 5.5p2
1991 // The result is an object or a function of the type specified by the
1992 // second operand.
1993 // The cv qualifiers are the union of those in the pointer and the left side,
1994 // in accordance with 5.5p5 and 5.2.5.
1995 // FIXME: This returns a dereferenced member function pointer as a normal
1996 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001997 // calling them. There's also a GCC extension to get a function pointer to the
1998 // thing, which is another complication, because this type - unlike the type
1999 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002000 // argument.
2001 // We probably need a "MemberFunctionClosureType" or something like that.
2002 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00002003 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002004 return Result;
2005}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002006
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002007/// \brief Try to convert a type to another according to C++0x 5.16p3.
2008///
2009/// This is part of the parameter validation for the ? operator. If either
2010/// value operand is a class type, the two operands are attempted to be
2011/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002012/// It returns true if the program is ill-formed and has already been diagnosed
2013/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002014static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
2015 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00002016 bool &HaveConversion,
2017 QualType &ToType) {
2018 HaveConversion = false;
2019 ToType = To->getType();
2020
2021 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
2022 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002023 // C++0x 5.16p3
2024 // The process for determining whether an operand expression E1 of type T1
2025 // can be converted to match an operand expression E2 of type T2 is defined
2026 // as follows:
2027 // -- If E2 is an lvalue:
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002028 bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid);
2029 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002030 // E1 can be converted to match E2 if E1 can be implicitly converted to
2031 // type "lvalue reference to T2", subject to the constraint that in the
2032 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002033 QualType T = Self.Context.getLValueReferenceType(ToType);
2034 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2035
2036 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2037 if (InitSeq.isDirectReferenceBinding()) {
2038 ToType = T;
2039 HaveConversion = true;
2040 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002041 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002042
2043 if (InitSeq.isAmbiguous())
2044 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002045 }
John McCallb1bdc622010-02-25 01:37:24 +00002046
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002047 // -- If E2 is an rvalue, or if the conversion above cannot be done:
2048 // -- if E1 and E2 have class type, and the underlying class types are
2049 // the same or one is a base class of the other:
2050 QualType FTy = From->getType();
2051 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002052 const RecordType *FRec = FTy->getAs<RecordType>();
2053 const RecordType *TRec = TTy->getAs<RecordType>();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002054 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
2055 Self.IsDerivedFrom(FTy, TTy);
2056 if (FRec && TRec &&
2057 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002058 // E1 can be converted to match E2 if the class of T2 is the
2059 // same type as, or a base class of, the class of T1, and
2060 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00002061 if (FRec == TRec || FDerivedFromT) {
2062 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002063 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2064 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2065 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2066 HaveConversion = true;
2067 return false;
2068 }
2069
2070 if (InitSeq.isAmbiguous())
2071 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2072 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002073 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002074
2075 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002076 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002077
2078 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2079 // implicitly converted to the type that expression E2 would have
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002080 // if E2 were converted to an rvalue (or the type it has, if E2 is
2081 // an rvalue).
2082 //
2083 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2084 // to the array-to-pointer or function-to-pointer conversions.
2085 if (!TTy->getAs<TagType>())
2086 TTy = TTy.getUnqualifiedType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002087
2088 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2089 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2090 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
2091 ToType = TTy;
2092 if (InitSeq.isAmbiguous())
2093 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2094
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002095 return false;
2096}
2097
2098/// \brief Try to find a common type for two according to C++0x 5.16p5.
2099///
2100/// This is part of the parameter validation for the ? operator. If either
2101/// value operand is a class type, overload resolution is used to find a
2102/// conversion to a common type.
2103static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2104 SourceLocation Loc) {
2105 Expr *Args[2] = { LHS, RHS };
John McCall5769d612010-02-08 23:07:23 +00002106 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor573d9c32009-10-21 23:19:44 +00002107 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002108
2109 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00002110 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002111 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002112 // We found a match. Perform the conversions on the arguments and move on.
2113 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00002114 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002115 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00002116 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002117 break;
2118 return false;
2119
Douglas Gregor20093b42009-12-09 23:02:17 +00002120 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002121 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2122 << LHS->getType() << RHS->getType()
2123 << LHS->getSourceRange() << RHS->getSourceRange();
2124 return true;
2125
Douglas Gregor20093b42009-12-09 23:02:17 +00002126 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002127 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2128 << LHS->getType() << RHS->getType()
2129 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00002130 // FIXME: Print the possible common types by printing the return types of
2131 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002132 break;
2133
Douglas Gregor20093b42009-12-09 23:02:17 +00002134 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002135 assert(false && "Conditional operator has only built-in overloads");
2136 break;
2137 }
2138 return true;
2139}
2140
Sebastian Redl76458502009-04-17 16:30:52 +00002141/// \brief Perform an "extended" implicit conversion as returned by
2142/// TryClassUnification.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002143static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2144 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2145 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2146 SourceLocation());
2147 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
2148 Sema::OwningExprResult Result = InitSeq.Perform(Self, Entity, Kind,
2149 Sema::MultiExprArg(Self, (void **)&E, 1));
2150 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00002151 return true;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002152
2153 E = Result.takeAs<Expr>();
Sebastian Redl76458502009-04-17 16:30:52 +00002154 return false;
2155}
2156
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002157/// \brief Check the operands of ?: under C++ semantics.
2158///
2159/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2160/// extension. In this case, LHS == Cond. (But they're not aliases.)
2161QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2162 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002163 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2164 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002165
2166 // C++0x 5.16p1
2167 // The first expression is contextually converted to bool.
2168 if (!Cond->isTypeDependent()) {
2169 if (CheckCXXBooleanCondition(Cond))
2170 return QualType();
2171 }
2172
2173 // Either of the arguments dependent?
2174 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2175 return Context.DependentTy;
2176
2177 // C++0x 5.16p2
2178 // If either the second or the third operand has type (cv) void, ...
2179 QualType LTy = LHS->getType();
2180 QualType RTy = RHS->getType();
2181 bool LVoid = LTy->isVoidType();
2182 bool RVoid = RTy->isVoidType();
2183 if (LVoid || RVoid) {
2184 // ... then the [l2r] conversions are performed on the second and third
2185 // operands ...
Douglas Gregora873dfc2010-02-03 00:27:59 +00002186 DefaultFunctionArrayLvalueConversion(LHS);
2187 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002188 LTy = LHS->getType();
2189 RTy = RHS->getType();
2190
2191 // ... and one of the following shall hold:
2192 // -- The second or the third operand (but not both) is a throw-
2193 // expression; the result is of the type of the other and is an rvalue.
2194 bool LThrow = isa<CXXThrowExpr>(LHS);
2195 bool RThrow = isa<CXXThrowExpr>(RHS);
2196 if (LThrow && !RThrow)
2197 return RTy;
2198 if (RThrow && !LThrow)
2199 return LTy;
2200
2201 // -- Both the second and third operands have type void; the result is of
2202 // type void and is an rvalue.
2203 if (LVoid && RVoid)
2204 return Context.VoidTy;
2205
2206 // Neither holds, error.
2207 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2208 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2209 << LHS->getSourceRange() << RHS->getSourceRange();
2210 return QualType();
2211 }
2212
2213 // Neither is void.
2214
2215 // C++0x 5.16p3
2216 // Otherwise, if the second and third operand have different types, and
2217 // either has (cv) class type, and attempt is made to convert each of those
2218 // operands to the other.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002219 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002220 (LTy->isRecordType() || RTy->isRecordType())) {
2221 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2222 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002223 QualType L2RType, R2LType;
2224 bool HaveL2R, HaveR2L;
2225 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002226 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002227 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002228 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002229
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002230 // If both can be converted, [...] the program is ill-formed.
2231 if (HaveL2R && HaveR2L) {
2232 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2233 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2234 return QualType();
2235 }
2236
2237 // If exactly one conversion is possible, that conversion is applied to
2238 // the chosen operand and the converted operands are used in place of the
2239 // original operands for the remainder of this section.
2240 if (HaveL2R) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002241 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002242 return QualType();
2243 LTy = LHS->getType();
2244 } else if (HaveR2L) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002245 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002246 return QualType();
2247 RTy = RHS->getType();
2248 }
2249 }
2250
2251 // C++0x 5.16p4
2252 // If the second and third operands are lvalues and have the same type,
2253 // the result is of that type [...]
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002254 bool Same = Context.hasSameType(LTy, RTy);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002255 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
2256 RHS->isLvalue(Context) == Expr::LV_Valid)
2257 return LTy;
2258
2259 // C++0x 5.16p5
2260 // Otherwise, the result is an rvalue. If the second and third operands
2261 // do not have the same type, and either has (cv) class type, ...
2262 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2263 // ... overload resolution is used to determine the conversions (if any)
2264 // to be applied to the operands. If the overload resolution fails, the
2265 // program is ill-formed.
2266 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2267 return QualType();
2268 }
2269
2270 // C++0x 5.16p6
2271 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2272 // conversions are performed on the second and third operands.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002273 DefaultFunctionArrayLvalueConversion(LHS);
2274 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002275 LTy = LHS->getType();
2276 RTy = RHS->getType();
2277
2278 // After those conversions, one of the following shall hold:
2279 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00002280 // is of that type. If the operands have class type, the result
2281 // is a prvalue temporary of the result type, which is
2282 // copy-initialized from either the second operand or the third
2283 // operand depending on the value of the first operand.
2284 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
2285 if (LTy->isRecordType()) {
2286 // The operands have class type. Make a temporary copy.
2287 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
2288 OwningExprResult LHSCopy = PerformCopyInitialization(Entity,
2289 SourceLocation(),
2290 Owned(LHS));
2291 if (LHSCopy.isInvalid())
2292 return QualType();
2293
2294 OwningExprResult RHSCopy = PerformCopyInitialization(Entity,
2295 SourceLocation(),
2296 Owned(RHS));
2297 if (RHSCopy.isInvalid())
2298 return QualType();
2299
2300 LHS = LHSCopy.takeAs<Expr>();
2301 RHS = RHSCopy.takeAs<Expr>();
2302 }
2303
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002304 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00002305 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002306
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002307 // Extension: conditional operator involving vector types.
2308 if (LTy->isVectorType() || RTy->isVectorType())
2309 return CheckVectorOperands(QuestionLoc, LHS, RHS);
2310
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002311 // -- The second and third operands have arithmetic or enumeration type;
2312 // the usual arithmetic conversions are performed to bring them to a
2313 // common type, and the result is of that type.
2314 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2315 UsualArithmeticConversions(LHS, RHS);
2316 return LHS->getType();
2317 }
2318
2319 // -- The second and third operands have pointer type, or one has pointer
2320 // type and the other is a null pointer constant; pointer conversions
2321 // and qualification conversions are performed to bring them to their
2322 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00002323 // -- The second and third operands have pointer to member type, or one has
2324 // pointer to member type and the other is a null pointer constant;
2325 // pointer to member conversions and qualification conversions are
2326 // performed to bring them to a common type, whose cv-qualification
2327 // shall match the cv-qualification of either the second or the third
2328 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002329 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002330 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002331 isSFINAEContext()? 0 : &NonStandardCompositeType);
2332 if (!Composite.isNull()) {
2333 if (NonStandardCompositeType)
2334 Diag(QuestionLoc,
2335 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2336 << LTy << RTy << Composite
2337 << LHS->getSourceRange() << RHS->getSourceRange();
2338
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002339 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002340 }
Fariborz Jahanian55016362009-12-10 20:46:08 +00002341
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002342 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00002343 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2344 if (!Composite.isNull())
2345 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002346
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002347 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2348 << LHS->getType() << RHS->getType()
2349 << LHS->getSourceRange() << RHS->getSourceRange();
2350 return QualType();
2351}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002352
2353/// \brief Find a merged pointer type and convert the two expressions to it.
2354///
Douglas Gregor20b3e992009-08-24 17:42:35 +00002355/// This finds the composite pointer type (or member pointer type) for @p E1
2356/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2357/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002358/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002359///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002360/// \param Loc The location of the operator requiring these two expressions to
2361/// be converted to the composite pointer type.
2362///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002363/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2364/// a non-standard (but still sane) composite type to which both expressions
2365/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2366/// will be set true.
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002367QualType Sema::FindCompositePointerType(SourceLocation Loc,
2368 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002369 bool *NonStandardCompositeType) {
2370 if (NonStandardCompositeType)
2371 *NonStandardCompositeType = false;
2372
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002373 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2374 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002375
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00002376 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2377 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00002378 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002379
2380 // C++0x 5.9p2
2381 // Pointer conversions and qualification conversions are performed on
2382 // pointer operands to bring them to their composite pointer type. If
2383 // one operand is a null pointer constant, the composite pointer type is
2384 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00002385 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002386 if (T2->isMemberPointerType())
2387 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
2388 else
2389 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002390 return T2;
2391 }
Douglas Gregorce940492009-09-25 04:25:58 +00002392 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002393 if (T1->isMemberPointerType())
2394 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
2395 else
2396 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002397 return T1;
2398 }
Mike Stump1eb44332009-09-09 15:08:12 +00002399
Douglas Gregor20b3e992009-08-24 17:42:35 +00002400 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002401 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2402 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002403 return QualType();
2404
2405 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2406 // the other has type "pointer to cv2 T" and the composite pointer type is
2407 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2408 // Otherwise, the composite pointer type is a pointer type similar to the
2409 // type of one of the operands, with a cv-qualification signature that is
2410 // the union of the cv-qualification signatures of the operand types.
2411 // In practice, the first part here is redundant; it's subsumed by the second.
2412 // What we do here is, we build the two possible composite types, and try the
2413 // conversions in both directions. If only one works, or if the two composite
2414 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00002415 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00002416 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2417 QualifierVector QualifierUnion;
2418 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2419 ContainingClassVector;
2420 ContainingClassVector MemberOfClass;
2421 QualType Composite1 = Context.getCanonicalType(T1),
2422 Composite2 = Context.getCanonicalType(T2);
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002423 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00002424 do {
2425 const PointerType *Ptr1, *Ptr2;
2426 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2427 (Ptr2 = Composite2->getAs<PointerType>())) {
2428 Composite1 = Ptr1->getPointeeType();
2429 Composite2 = Ptr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002430
2431 // If we're allowed to create a non-standard composite type, keep track
2432 // of where we need to fill in additional 'const' qualifiers.
2433 if (NonStandardCompositeType &&
2434 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2435 NeedConstBefore = QualifierUnion.size();
2436
Douglas Gregor20b3e992009-08-24 17:42:35 +00002437 QualifierUnion.push_back(
2438 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2439 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2440 continue;
2441 }
Mike Stump1eb44332009-09-09 15:08:12 +00002442
Douglas Gregor20b3e992009-08-24 17:42:35 +00002443 const MemberPointerType *MemPtr1, *MemPtr2;
2444 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2445 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2446 Composite1 = MemPtr1->getPointeeType();
2447 Composite2 = MemPtr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002448
2449 // If we're allowed to create a non-standard composite type, keep track
2450 // of where we need to fill in additional 'const' qualifiers.
2451 if (NonStandardCompositeType &&
2452 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2453 NeedConstBefore = QualifierUnion.size();
2454
Douglas Gregor20b3e992009-08-24 17:42:35 +00002455 QualifierUnion.push_back(
2456 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2457 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2458 MemPtr2->getClass()));
2459 continue;
2460 }
Mike Stump1eb44332009-09-09 15:08:12 +00002461
Douglas Gregor20b3e992009-08-24 17:42:35 +00002462 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00002463
Douglas Gregor20b3e992009-08-24 17:42:35 +00002464 // Cannot unwrap any more types.
2465 break;
2466 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00002467
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002468 if (NeedConstBefore && NonStandardCompositeType) {
2469 // Extension: Add 'const' to qualifiers that come before the first qualifier
2470 // mismatch, so that our (non-standard!) composite type meets the
2471 // requirements of C++ [conv.qual]p4 bullet 3.
2472 for (unsigned I = 0; I != NeedConstBefore; ++I) {
2473 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
2474 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
2475 *NonStandardCompositeType = true;
2476 }
2477 }
2478 }
2479
Douglas Gregor20b3e992009-08-24 17:42:35 +00002480 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002481 ContainingClassVector::reverse_iterator MOC
2482 = MemberOfClass.rbegin();
2483 for (QualifierVector::reverse_iterator
2484 I = QualifierUnion.rbegin(),
2485 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00002486 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00002487 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002488 if (MOC->first && MOC->second) {
2489 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00002490 Composite1 = Context.getMemberPointerType(
2491 Context.getQualifiedType(Composite1, Quals),
2492 MOC->first);
2493 Composite2 = Context.getMemberPointerType(
2494 Context.getQualifiedType(Composite2, Quals),
2495 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002496 } else {
2497 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00002498 Composite1
2499 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2500 Composite2
2501 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00002502 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002503 }
2504
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002505 // Try to convert to the first composite pointer type.
2506 InitializedEntity Entity1
2507 = InitializedEntity::InitializeTemporary(Composite1);
2508 InitializationKind Kind
2509 = InitializationKind::CreateCopy(Loc, SourceLocation());
2510 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
2511 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00002512
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002513 if (E1ToC1 && E2ToC1) {
2514 // Conversion to Composite1 is viable.
2515 if (!Context.hasSameType(Composite1, Composite2)) {
2516 // Composite2 is a different type from Composite1. Check whether
2517 // Composite2 is also viable.
2518 InitializedEntity Entity2
2519 = InitializedEntity::InitializeTemporary(Composite2);
2520 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2521 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2522 if (E1ToC2 && E2ToC2) {
2523 // Both Composite1 and Composite2 are viable and are different;
2524 // this is an ambiguity.
2525 return QualType();
2526 }
2527 }
2528
2529 // Convert E1 to Composite1
2530 OwningExprResult E1Result
2531 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E1,1));
2532 if (E1Result.isInvalid())
2533 return QualType();
2534 E1 = E1Result.takeAs<Expr>();
2535
2536 // Convert E2 to Composite1
2537 OwningExprResult E2Result
2538 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E2,1));
2539 if (E2Result.isInvalid())
2540 return QualType();
2541 E2 = E2Result.takeAs<Expr>();
2542
2543 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002544 }
2545
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002546 // Check whether Composite2 is viable.
2547 InitializedEntity Entity2
2548 = InitializedEntity::InitializeTemporary(Composite2);
2549 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2550 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2551 if (!E1ToC2 || !E2ToC2)
2552 return QualType();
2553
2554 // Convert E1 to Composite2
2555 OwningExprResult E1Result
2556 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E1, 1));
2557 if (E1Result.isInvalid())
2558 return QualType();
2559 E1 = E1Result.takeAs<Expr>();
2560
2561 // Convert E2 to Composite2
2562 OwningExprResult E2Result
2563 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E2, 1));
2564 if (E2Result.isInvalid())
2565 return QualType();
2566 E2 = E2Result.takeAs<Expr>();
2567
2568 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002569}
Anders Carlsson165a0a02009-05-17 18:41:29 +00002570
Anders Carlssondef11992009-05-30 20:36:53 +00002571Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00002572 if (!Context.getLangOptions().CPlusPlus)
2573 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002574
Douglas Gregor51326552009-12-24 18:51:59 +00002575 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2576
Ted Kremenek6217b802009-07-29 21:53:49 +00002577 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00002578 if (!RT)
2579 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002580
John McCall86ff3082010-02-04 22:26:26 +00002581 // If this is the result of a call expression, our source might
2582 // actually be a reference, in which case we shouldn't bind.
Anders Carlsson283e4d52009-09-14 01:30:44 +00002583 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2584 QualType Ty = CE->getCallee()->getType();
2585 if (const PointerType *PT = Ty->getAs<PointerType>())
2586 Ty = PT->getPointeeType();
Fariborz Jahanianb372b0f2010-02-18 20:31:02 +00002587 else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>())
2588 Ty = BPT->getPointeeType();
2589
John McCall183700f2009-09-21 23:43:11 +00002590 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00002591 if (FTy->getResultType()->isReferenceType())
2592 return Owned(E);
2593 }
Fariborz Jahaniand4266622010-06-16 18:56:04 +00002594 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
2595 QualType Ty = ME->getType();
2596 if (const PointerType *PT = Ty->getAs<PointerType>())
2597 Ty = PT->getPointeeType();
2598 else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>())
2599 Ty = BPT->getPointeeType();
2600 if (Ty->isReferenceType())
2601 return Owned(E);
2602 }
2603
John McCall86ff3082010-02-04 22:26:26 +00002604
2605 // That should be enough to guarantee that this type is complete.
2606 // If it has a trivial destructor, we can avoid the extra copy.
2607 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2608 if (RD->hasTrivialDestructor())
2609 return Owned(E);
2610
Douglas Gregordb89f282010-07-01 22:47:18 +00002611 CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD));
Anders Carlsson860306e2009-05-30 21:21:49 +00002612 ExprTemporaries.push_back(Temp);
Douglas Gregordb89f282010-07-01 22:47:18 +00002613 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002614 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00002615 CheckDestructorAccess(E->getExprLoc(), Destructor,
2616 PDiag(diag::err_access_dtor_temp)
2617 << E->getType());
2618 }
Anders Carlssondef11992009-05-30 20:36:53 +00002619 // FIXME: Add the temporary to the temporaries vector.
2620 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2621}
2622
Anders Carlsson0ece4912009-12-15 20:51:39 +00002623Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002624 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002625
John McCall323ed742010-05-06 08:58:33 +00002626 // Check any implicit conversions within the expression.
2627 CheckImplicitConversions(SubExpr);
2628
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002629 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2630 assert(ExprTemporaries.size() >= FirstTemporary);
2631 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002632 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002633
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002634 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002635 &ExprTemporaries[FirstTemporary],
Anders Carlsson0ece4912009-12-15 20:51:39 +00002636 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002637 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2638 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002639
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002640 return E;
2641}
2642
Douglas Gregor90f93822009-12-22 22:17:25 +00002643Sema::OwningExprResult
2644Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2645 if (SubExpr.isInvalid())
2646 return ExprError();
2647
2648 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2649}
2650
Anders Carlsson5ee56e92009-12-16 02:09:40 +00002651FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2652 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2653 assert(ExprTemporaries.size() >= FirstTemporary);
2654
2655 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2656 CXXTemporary **Temporaries =
2657 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2658
2659 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2660
2661 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2662 ExprTemporaries.end());
2663
2664 return E;
2665}
2666
Mike Stump1eb44332009-09-09 15:08:12 +00002667Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002668Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
Douglas Gregord4dca082010-02-24 18:44:31 +00002669 tok::TokenKind OpKind, TypeTy *&ObjectType,
2670 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002671 // Since this might be a postfix expression, get rid of ParenListExprs.
2672 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002673
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002674 Expr *BaseExpr = (Expr*)Base.get();
2675 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002676
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002677 QualType BaseType = BaseExpr->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00002678 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002679 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002680 // If we have a pointer to a dependent type and are using the -> operator,
2681 // the object type is the type that the pointer points to. We might still
2682 // have enough information about that type to do something useful.
2683 if (OpKind == tok::arrow)
2684 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2685 BaseType = Ptr->getPointeeType();
2686
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002687 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregord4dca082010-02-24 18:44:31 +00002688 MayBePseudoDestructor = true;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002689 return move(Base);
2690 }
Mike Stump1eb44332009-09-09 15:08:12 +00002691
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002692 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002693 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002694 // returned, with the original second operand.
2695 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002696 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002697 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002698 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002699 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002700
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002701 while (BaseType->isRecordType()) {
Anders Carlsson15ea3782009-10-13 22:43:21 +00002702 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002703 BaseExpr = (Expr*)Base.get();
2704 if (BaseExpr == NULL)
2705 return ExprError();
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002706 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonde699e52009-10-13 22:55:59 +00002707 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc4e83212009-09-30 01:01:30 +00002708 BaseType = BaseExpr->getType();
2709 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002710 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002711 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002712 for (unsigned i = 0; i < Locations.size(); i++)
2713 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002714 return ExprError();
2715 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002716 }
Mike Stump1eb44332009-09-09 15:08:12 +00002717
Douglas Gregor31658df2009-11-20 19:58:21 +00002718 if (BaseType->isPointerType())
2719 BaseType = BaseType->getPointeeType();
2720 }
Mike Stump1eb44332009-09-09 15:08:12 +00002721
2722 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002723 // vector types or Objective-C interfaces. Just return early and let
2724 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002725 if (!BaseType->isRecordType()) {
2726 // C++ [basic.lookup.classref]p2:
2727 // [...] If the type of the object expression is of pointer to scalar
2728 // type, the unqualified-id is looked up in the context of the complete
2729 // postfix-expression.
Douglas Gregord4dca082010-02-24 18:44:31 +00002730 //
2731 // This also indicates that we should be parsing a
2732 // pseudo-destructor-name.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002733 ObjectType = 0;
Douglas Gregord4dca082010-02-24 18:44:31 +00002734 MayBePseudoDestructor = true;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002735 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002736 }
Mike Stump1eb44332009-09-09 15:08:12 +00002737
Douglas Gregor03c57052009-11-17 05:17:33 +00002738 // The object type must be complete (or dependent).
2739 if (!BaseType->isDependentType() &&
2740 RequireCompleteType(OpLoc, BaseType,
2741 PDiag(diag::err_incomplete_member_access)))
2742 return ExprError();
2743
Douglas Gregorc68afe22009-09-03 21:38:09 +00002744 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002745 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00002746 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00002747 // type C (or of pointer to a class type C), the unqualified-id is looked
2748 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002749 ObjectType = BaseType.getAsOpaquePtr();
Mike Stump1eb44332009-09-09 15:08:12 +00002750 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002751}
2752
Douglas Gregor77549082010-02-24 21:29:12 +00002753Sema::OwningExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
2754 ExprArg MemExpr) {
2755 Expr *E = (Expr *) MemExpr.get();
2756 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
2757 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2758 << isa<CXXPseudoDestructorExpr>(E)
Douglas Gregor849b2432010-03-31 17:46:05 +00002759 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
Douglas Gregor77549082010-02-24 21:29:12 +00002760
2761 return ActOnCallExpr(/*Scope*/ 0,
2762 move(MemExpr),
2763 /*LPLoc*/ ExpectedLParenLoc,
2764 Sema::MultiExprArg(*this, 0, 0),
2765 /*CommaLocs*/ 0,
2766 /*RPLoc*/ ExpectedLParenLoc);
2767}
Douglas Gregord4dca082010-02-24 18:44:31 +00002768
Douglas Gregorb57fb492010-02-24 22:38:50 +00002769Sema::OwningExprResult Sema::BuildPseudoDestructorExpr(ExprArg Base,
2770 SourceLocation OpLoc,
2771 tok::TokenKind OpKind,
2772 const CXXScopeSpec &SS,
Douglas Gregor26d4ac92010-02-24 23:40:28 +00002773 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002774 SourceLocation CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002775 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002776 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002777 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002778 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
Douglas Gregorb57fb492010-02-24 22:38:50 +00002779
2780 // C++ [expr.pseudo]p2:
2781 // The left-hand side of the dot operator shall be of scalar type. The
2782 // left-hand side of the arrow operator shall be of pointer to scalar type.
2783 // This scalar type is the object type.
2784 Expr *BaseE = (Expr *)Base.get();
2785 QualType ObjectType = BaseE->getType();
2786 if (OpKind == tok::arrow) {
2787 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2788 ObjectType = Ptr->getPointeeType();
2789 } else if (!BaseE->isTypeDependent()) {
2790 // The user wrote "p->" when she probably meant "p."; fix it.
2791 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2792 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00002793 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb57fb492010-02-24 22:38:50 +00002794 if (isSFINAEContext())
2795 return ExprError();
2796
2797 OpKind = tok::period;
2798 }
2799 }
2800
2801 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
2802 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2803 << ObjectType << BaseE->getSourceRange();
2804 return ExprError();
2805 }
2806
2807 // C++ [expr.pseudo]p2:
2808 // [...] The cv-unqualified versions of the object type and of the type
2809 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002810 if (DestructedTypeInfo) {
2811 QualType DestructedType = DestructedTypeInfo->getType();
2812 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002813 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002814 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
2815 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
2816 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
2817 << ObjectType << DestructedType << BaseE->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002818 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002819
2820 // Recover by setting the destructed type to the object type.
2821 DestructedType = ObjectType;
2822 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
2823 DestructedTypeStart);
2824 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2825 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00002826 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002827
Douglas Gregorb57fb492010-02-24 22:38:50 +00002828 // C++ [expr.pseudo]p2:
2829 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
2830 // form
2831 //
2832 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
2833 //
2834 // shall designate the same scalar type.
2835 if (ScopeTypeInfo) {
2836 QualType ScopeType = ScopeTypeInfo->getType();
2837 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00002838 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
Douglas Gregorb57fb492010-02-24 22:38:50 +00002839
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002840 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00002841 diag::err_pseudo_dtor_type_mismatch)
2842 << ObjectType << ScopeType << BaseE->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002843 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00002844
2845 ScopeType = QualType();
2846 ScopeTypeInfo = 0;
2847 }
2848 }
2849
2850 OwningExprResult Result
2851 = Owned(new (Context) CXXPseudoDestructorExpr(Context,
2852 Base.takeAs<Expr>(),
2853 OpKind == tok::arrow,
2854 OpLoc,
2855 (NestedNameSpecifier *) SS.getScopeRep(),
2856 SS.getRange(),
2857 ScopeTypeInfo,
2858 CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002859 TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002860 Destructed));
2861
Douglas Gregorb57fb492010-02-24 22:38:50 +00002862 if (HasTrailingLParen)
2863 return move(Result);
2864
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002865 return DiagnoseDtorReference(Destructed.getLocation(), move(Result));
Douglas Gregor77549082010-02-24 21:29:12 +00002866}
2867
2868Sema::OwningExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, ExprArg Base,
2869 SourceLocation OpLoc,
2870 tok::TokenKind OpKind,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002871 CXXScopeSpec &SS,
Douglas Gregor77549082010-02-24 21:29:12 +00002872 UnqualifiedId &FirstTypeName,
2873 SourceLocation CCLoc,
2874 SourceLocation TildeLoc,
2875 UnqualifiedId &SecondTypeName,
2876 bool HasTrailingLParen) {
2877 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2878 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2879 "Invalid first type name in pseudo-destructor");
2880 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2881 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2882 "Invalid second type name in pseudo-destructor");
2883
2884 Expr *BaseE = (Expr *)Base.get();
Douglas Gregor77549082010-02-24 21:29:12 +00002885
2886 // C++ [expr.pseudo]p2:
2887 // The left-hand side of the dot operator shall be of scalar type. The
2888 // left-hand side of the arrow operator shall be of pointer to scalar type.
2889 // This scalar type is the object type.
2890 QualType ObjectType = BaseE->getType();
2891 if (OpKind == tok::arrow) {
2892 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2893 ObjectType = Ptr->getPointeeType();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002894 } else if (!ObjectType->isDependentType()) {
Douglas Gregor77549082010-02-24 21:29:12 +00002895 // The user wrote "p->" when she probably meant "p."; fix it.
2896 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002897 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00002898 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor77549082010-02-24 21:29:12 +00002899 if (isSFINAEContext())
2900 return ExprError();
2901
2902 OpKind = tok::period;
2903 }
2904 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002905
2906 // Compute the object type that we should use for name lookup purposes. Only
2907 // record types and dependent types matter.
2908 void *ObjectTypePtrForLookup = 0;
2909 if (!SS.isSet()) {
Gabor Greif170e5082010-06-17 11:29:31 +00002910 ObjectTypePtrForLookup = const_cast<RecordType*>(
2911 ObjectType->getAs<RecordType>());
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002912 if (!ObjectTypePtrForLookup && ObjectType->isDependentType())
2913 ObjectTypePtrForLookup = Context.DependentTy.getAsOpaquePtr();
2914 }
Douglas Gregor77549082010-02-24 21:29:12 +00002915
Douglas Gregorb57fb492010-02-24 22:38:50 +00002916 // Convert the name of the type being destructed (following the ~) into a
2917 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00002918 QualType DestructedType;
2919 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002920 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00002921 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2922 TypeTy *T = getTypeName(*SecondTypeName.Identifier,
2923 SecondTypeName.StartLocation,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002924 S, &SS, true, ObjectTypePtrForLookup);
2925 if (!T &&
2926 ((SS.isSet() && !computeDeclContext(SS, false)) ||
2927 (!SS.isSet() && ObjectType->isDependentType()))) {
2928 // The name of the type being destroyed is a dependent name, and we
2929 // couldn't find anything useful in scope. Just store the identifier and
2930 // it's location, and we'll perform (qualified) name lookup again at
2931 // template instantiation time.
2932 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
2933 SecondTypeName.StartLocation);
2934 } else if (!T) {
Douglas Gregor77549082010-02-24 21:29:12 +00002935 Diag(SecondTypeName.StartLocation,
2936 diag::err_pseudo_dtor_destructor_non_type)
2937 << SecondTypeName.Identifier << ObjectType;
2938 if (isSFINAEContext())
2939 return ExprError();
2940
2941 // Recover by assuming we had the right type all along.
2942 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002943 } else
Douglas Gregor77549082010-02-24 21:29:12 +00002944 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002945 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00002946 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00002947 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002948 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2949 TemplateId->getTemplateArgs(),
2950 TemplateId->NumArgs);
2951 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2952 TemplateId->TemplateNameLoc,
2953 TemplateId->LAngleLoc,
2954 TemplateArgsPtr,
2955 TemplateId->RAngleLoc);
2956 if (T.isInvalid() || !T.get()) {
2957 // Recover by assuming we had the right type all along.
2958 DestructedType = ObjectType;
2959 } else
2960 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002961 }
2962
Douglas Gregorb57fb492010-02-24 22:38:50 +00002963 // If we've performed some kind of recovery, (re-)build the type source
2964 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002965 if (!DestructedType.isNull()) {
2966 if (!DestructedTypeInfo)
2967 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002968 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002969 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2970 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00002971
2972 // Convert the name of the scope type (the type prior to '::') into a type.
2973 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00002974 QualType ScopeType;
2975 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2976 FirstTypeName.Identifier) {
2977 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2978 TypeTy *T = getTypeName(*FirstTypeName.Identifier,
2979 FirstTypeName.StartLocation,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002980 S, &SS, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00002981 if (!T) {
2982 Diag(FirstTypeName.StartLocation,
2983 diag::err_pseudo_dtor_destructor_non_type)
2984 << FirstTypeName.Identifier << ObjectType;
Douglas Gregor77549082010-02-24 21:29:12 +00002985
Douglas Gregorb57fb492010-02-24 22:38:50 +00002986 if (isSFINAEContext())
2987 return ExprError();
2988
2989 // Just drop this type. It's unnecessary anyway.
2990 ScopeType = QualType();
2991 } else
2992 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002993 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00002994 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00002995 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002996 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2997 TemplateId->getTemplateArgs(),
2998 TemplateId->NumArgs);
2999 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
3000 TemplateId->TemplateNameLoc,
3001 TemplateId->LAngleLoc,
3002 TemplateArgsPtr,
3003 TemplateId->RAngleLoc);
3004 if (T.isInvalid() || !T.get()) {
3005 // Recover by dropping this type.
3006 ScopeType = QualType();
3007 } else
3008 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003009 }
3010 }
Douglas Gregorb4a418f2010-02-24 23:02:30 +00003011
3012 if (!ScopeType.isNull() && !ScopeTypeInfo)
3013 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
3014 FirstTypeName.StartLocation);
3015
3016
Douglas Gregorb57fb492010-02-24 22:38:50 +00003017 return BuildPseudoDestructorExpr(move(Base), OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00003018 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003019 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00003020}
3021
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003022CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
John McCall6bb80172010-03-30 21:47:33 +00003023 NamedDecl *FoundDecl,
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003024 CXXMethodDecl *Method) {
John McCall6bb80172010-03-30 21:47:33 +00003025 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
3026 FoundDecl, Method))
Eli Friedman772fffa2009-12-09 04:53:56 +00003027 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
3028
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003029 MemberExpr *ME =
3030 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
3031 SourceLocation(), Method->getType());
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003032 QualType ResultType = Method->getCallResultType();
Douglas Gregor7edfb692009-11-23 12:27:39 +00003033 MarkDeclarationReferenced(Exp->getLocStart(), Method);
3034 CXXMemberCallExpr *CE =
3035 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
3036 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003037 return CE;
3038}
3039
Anders Carlsson165a0a02009-05-17 18:41:29 +00003040Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
3041 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003042 if (FullExpr)
Anders Carlsson0ece4912009-12-15 20:51:39 +00003043 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Douglas Gregoreecf38f2010-05-06 21:39:56 +00003044 else
3045 return ExprError();
3046
Anders Carlsson165a0a02009-05-17 18:41:29 +00003047 return Owned(FullExpr);
3048}