blob: 2a55894f22a40760173051c9169c9732f9f76168 [file] [log] [blame]
Chris Lattner29375652006-12-04 18:06:35 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner29375652006-12-04 18:06:35 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000015#include "SemaInit.h"
John McCall5cebab12009-11-18 07:57:50 +000016#include "Lookup.h"
Steve Naroffaac94152007-08-25 14:02:58 +000017#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000019#include "clang/AST/ExprCXX.h"
Douglas Gregorb1dd23f2010-02-24 22:38:50 +000020#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000021#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlfaf68082008-12-03 20:26:15 +000022#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000023#include "clang/Lex/Preprocessor.h"
24#include "clang/Parse/DeclSpec.h"
Douglas Gregore610ada2010-02-24 18:44:31 +000025#include "clang/Parse/Template.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
Chris Lattner29375652006-12-04 18:06:35 +000027using namespace clang;
28
Douglas Gregorfe17d252010-02-16 19:09:40 +000029Action::TypeTy *Sema::getDestructorName(SourceLocation TildeLoc,
30 IdentifierInfo &II,
31 SourceLocation NameLoc,
32 Scope *S, const CXXScopeSpec &SS,
33 TypeTy *ObjectTypePtr,
34 bool EnteringContext) {
35 // Determine where to perform name lookup.
36
37 // FIXME: This area of the standard is very messy, and the current
38 // wording is rather unclear about which scopes we search for the
39 // destructor name; see core issues 399 and 555. Issue 399 in
40 // particular shows where the current description of destructor name
41 // lookup is completely out of line with existing practice, e.g.,
42 // this appears to be ill-formed:
43 //
44 // namespace N {
45 // template <typename T> struct S {
46 // ~S();
47 // };
48 // }
49 //
50 // void f(N::S<int>* s) {
51 // s->N::S<int>::~S();
52 // }
53 //
Douglas Gregor46841e12010-02-23 00:15:22 +000054 // See also PR6358 and PR6359.
Douglas Gregorfe17d252010-02-16 19:09:40 +000055 QualType SearchType;
56 DeclContext *LookupCtx = 0;
57 bool isDependent = false;
58 bool LookInScope = false;
59
60 // If we have an object type, it's because we are in a
61 // pseudo-destructor-expression or a member access expression, and
62 // we know what type we're looking for.
63 if (ObjectTypePtr)
64 SearchType = GetTypeFromParser(ObjectTypePtr);
65
66 if (SS.isSet()) {
Douglas Gregor46841e12010-02-23 00:15:22 +000067 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
68
69 bool AlreadySearched = false;
70 bool LookAtPrefix = true;
71 if (!getLangOptions().CPlusPlus0x) {
72 // C++ [basic.lookup.qual]p6:
73 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
74 // the type-names are looked up as types in the scope designated by the
75 // nested-name-specifier. In a qualified-id of the form:
76 //
77 // ::[opt] nested-name-specifier ̃ class-name
78 //
79 // where the nested-name-specifier designates a namespace scope, and in
80 // a qualified-id of the form:
81 //
82 // ::opt nested-name-specifier class-name :: ̃ class-name
83 //
84 // the class-names are looked up as types in the scope designated by
85 // the nested-name-specifier.
86 //
87 // Here, we check the first case (completely) and determine whether the
88 // code below is permitted to look at the prefix of the
89 // nested-name-specifier (as we do in C++0x).
90 DeclContext *DC = computeDeclContext(SS, EnteringContext);
91 if (DC && DC->isFileContext()) {
92 AlreadySearched = true;
93 LookupCtx = DC;
94 isDependent = false;
95 } else if (DC && isa<CXXRecordDecl>(DC))
96 LookAtPrefix = false;
97 }
98
99 // C++0x [basic.lookup.qual]p6:
Douglas Gregorfe17d252010-02-16 19:09:40 +0000100 // If a pseudo-destructor-name (5.2.4) contains a
101 // nested-name-specifier, the type-names are looked up as types
102 // in the scope designated by the nested-name-specifier. Similarly, in
Chandler Carruth8f254812010-02-21 10:19:54 +0000103 // a qualified-id of the form:
Douglas Gregorfe17d252010-02-16 19:09:40 +0000104 //
105 // :: [opt] nested-name-specifier[opt] class-name :: ~class-name
106 //
107 // the second class-name is looked up in the same scope as the first.
108 //
Douglas Gregor46841e12010-02-23 00:15:22 +0000109 // To implement this, we look at the prefix of the
110 // nested-name-specifier we were given, and determine the lookup
111 // context from that.
112 //
113 // We also fold in the second case from the C++03 rules quoted further
114 // above.
115 NestedNameSpecifier *Prefix = 0;
116 if (AlreadySearched) {
117 // Nothing left to do.
118 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
119 CXXScopeSpec PrefixSS;
120 PrefixSS.setScopeRep(Prefix);
121 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
122 isDependent = isDependentScopeSpecifier(PrefixSS);
123 } else if (getLangOptions().CPlusPlus0x &&
124 (LookupCtx = computeDeclContext(SS, EnteringContext))) {
125 if (!LookupCtx->isTranslationUnit())
126 LookupCtx = LookupCtx->getParent();
127 isDependent = LookupCtx && LookupCtx->isDependentContext();
128 } else if (ObjectTypePtr) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000129 LookupCtx = computeDeclContext(SearchType);
130 isDependent = SearchType->isDependentType();
131 } else {
132 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor46841e12010-02-23 00:15:22 +0000133 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000134 }
Douglas Gregor46841e12010-02-23 00:15:22 +0000135
Douglas Gregorcd3f49f2010-02-25 04:46:04 +0000136 LookInScope = false;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000137 } else if (ObjectTypePtr) {
138 // C++ [basic.lookup.classref]p3:
139 // If the unqualified-id is ~type-name, the type-name is looked up
140 // in the context of the entire postfix-expression. If the type T
141 // of the object expression is of a class type C, the type-name is
142 // also looked up in the scope of class C. At least one of the
143 // lookups shall find a name that refers to (possibly
144 // cv-qualified) T.
145 LookupCtx = computeDeclContext(SearchType);
146 isDependent = SearchType->isDependentType();
147 assert((isDependent || !SearchType->isIncompleteType()) &&
148 "Caller should have completed object type");
149
150 LookInScope = true;
151 } else {
152 // Perform lookup into the current scope (only).
153 LookInScope = true;
154 }
155
156 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
157 for (unsigned Step = 0; Step != 2; ++Step) {
158 // Look for the name first in the computed lookup context (if we
159 // have one) and, if that fails to find a match, in the sope (if
160 // we're allowed to look there).
161 Found.clear();
162 if (Step == 0 && LookupCtx)
163 LookupQualifiedName(Found, LookupCtx);
Douglas Gregor678f90d2010-02-25 01:56:36 +0000164 else if (Step == 1 && LookInScope && S)
Douglas Gregorfe17d252010-02-16 19:09:40 +0000165 LookupName(Found, S);
166 else
167 continue;
168
169 // FIXME: Should we be suppressing ambiguities here?
170 if (Found.isAmbiguous())
171 return 0;
172
173 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
174 QualType T = Context.getTypeDeclType(Type);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000175
176 if (SearchType.isNull() || SearchType->isDependentType() ||
177 Context.hasSameUnqualifiedType(T, SearchType)) {
178 // We found our type!
179
180 return T.getAsOpaquePtr();
181 }
182 }
183
184 // If the name that we found is a class template name, and it is
185 // the same name as the template name in the last part of the
186 // nested-name-specifier (if present) or the object type, then
187 // this is the destructor for that class.
188 // FIXME: This is a workaround until we get real drafting for core
189 // issue 399, for which there isn't even an obvious direction.
190 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
191 QualType MemberOfType;
192 if (SS.isSet()) {
193 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
194 // Figure out the type of the context, if it has one.
John McCalle78aac42010-03-10 03:28:59 +0000195 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
196 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000197 }
198 }
199 if (MemberOfType.isNull())
200 MemberOfType = SearchType;
201
202 if (MemberOfType.isNull())
203 continue;
204
205 // We're referring into a class template specialization. If the
206 // class template we found is the same as the template being
207 // specialized, we found what we are looking for.
208 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
209 if (ClassTemplateSpecializationDecl *Spec
210 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
211 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
212 Template->getCanonicalDecl())
213 return MemberOfType.getAsOpaquePtr();
214 }
215
216 continue;
217 }
218
219 // We're referring to an unresolved class template
220 // specialization. Determine whether we class template we found
221 // is the same as the template being specialized or, if we don't
222 // know which template is being specialized, that it at least
223 // has the same name.
224 if (const TemplateSpecializationType *SpecType
225 = MemberOfType->getAs<TemplateSpecializationType>()) {
226 TemplateName SpecName = SpecType->getTemplateName();
227
228 // The class template we found is the same template being
229 // specialized.
230 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
231 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
232 return MemberOfType.getAsOpaquePtr();
233
234 continue;
235 }
236
237 // The class template we found has the same name as the
238 // (dependent) template name being specialized.
239 if (DependentTemplateName *DepTemplate
240 = SpecName.getAsDependentTemplateName()) {
241 if (DepTemplate->isIdentifier() &&
242 DepTemplate->getIdentifier() == Template->getIdentifier())
243 return MemberOfType.getAsOpaquePtr();
244
245 continue;
246 }
247 }
248 }
249 }
250
251 if (isDependent) {
252 // We didn't find our type, but that's okay: it's dependent
253 // anyway.
254 NestedNameSpecifier *NNS = 0;
255 SourceRange Range;
256 if (SS.isSet()) {
257 NNS = (NestedNameSpecifier *)SS.getScopeRep();
258 Range = SourceRange(SS.getRange().getBegin(), NameLoc);
259 } else {
260 NNS = NestedNameSpecifier::Create(Context, &II);
261 Range = SourceRange(NameLoc);
262 }
263
264 return CheckTypenameType(NNS, II, Range).getAsOpaquePtr();
265 }
266
267 if (ObjectTypePtr)
268 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
269 << &II;
270 else
271 Diag(NameLoc, diag::err_destructor_class_name);
272
273 return 0;
274}
275
Sebastian Redlc4704762008-11-11 11:37:55 +0000276/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000277Action::OwningExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000278Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
279 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor87f54062009-09-15 22:30:29 +0000280 if (!StdNamespace)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000281 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000282
Douglas Gregorf45f6822009-12-23 20:51:04 +0000283 if (isType) {
284 // C++ [expr.typeid]p4:
285 // The top-level cv-qualifiers of the lvalue expression or the type-id
286 // that is the operand of typeid are always ignored.
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000287 // FIXME: Preserve type source info.
Douglas Gregorf45f6822009-12-23 20:51:04 +0000288 // FIXME: Preserve the type before we stripped the cv-qualifiers?
Douglas Gregor721fb2b2009-12-23 21:06:06 +0000289 QualType T = GetTypeFromParser(TyOrExpr);
290 if (T.isNull())
291 return ExprError();
292
293 // C++ [expr.typeid]p4:
294 // If the type of the type-id is a class type or a reference to a class
295 // type, the class shall be completely-defined.
296 QualType CheckT = T;
297 if (const ReferenceType *RefType = CheckT->getAs<ReferenceType>())
298 CheckT = RefType->getPointeeType();
299
300 if (CheckT->getAs<RecordType>() &&
301 RequireCompleteType(OpLoc, CheckT, diag::err_incomplete_typeid))
302 return ExprError();
303
304 TyOrExpr = T.getUnqualifiedType().getAsOpaquePtr();
Douglas Gregorf45f6822009-12-23 20:51:04 +0000305 }
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000306
Chris Lattnerec7f7732008-11-20 05:51:55 +0000307 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCall27b18f82009-11-17 02:14:36 +0000308 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
309 LookupQualifiedName(R, StdNamespace);
John McCall67c00872009-12-02 08:25:40 +0000310 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
Chris Lattnerec7f7732008-11-20 05:51:55 +0000311 if (!TypeInfoRecordDecl)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000312 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc4704762008-11-11 11:37:55 +0000313
314 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
315
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000316 if (!isType) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000317 bool isUnevaluatedOperand = true;
318 Expr *E = static_cast<Expr *>(TyOrExpr);
Douglas Gregorf45f6822009-12-23 20:51:04 +0000319 if (E && !E->isTypeDependent()) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000320 QualType T = E->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000321 if (const RecordType *RecordT = T->getAs<RecordType>()) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000322 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
Douglas Gregorf45f6822009-12-23 20:51:04 +0000323 // C++ [expr.typeid]p3:
John McCall67da35c2010-02-04 22:26:26 +0000324 // [...] If the type of the expression is a class type, the class
325 // shall be completely-defined.
326 if (RequireCompleteType(OpLoc, T, diag::err_incomplete_typeid))
327 return ExprError();
328
329 // C++ [expr.typeid]p3:
Douglas Gregorf45f6822009-12-23 20:51:04 +0000330 // When typeid is applied to an expression other than an lvalue of a
331 // polymorphic class type [...] [the] expression is an unevaluated
332 // operand. [...]
333 if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid)
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000334 isUnevaluatedOperand = false;
Douglas Gregorf45f6822009-12-23 20:51:04 +0000335 }
336
337 // C++ [expr.typeid]p4:
338 // [...] If the type of the type-id is a reference to a possibly
339 // cv-qualified type, the result of the typeid expression refers to a
340 // std::type_info object representing the cv-unqualified referenced
341 // type.
342 if (T.hasQualifiers()) {
343 ImpCastExprToType(E, T.getUnqualifiedType(), CastExpr::CK_NoOp,
344 E->isLvalue(Context));
345 TyOrExpr = E;
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000346 }
347 }
Mike Stump11289f42009-09-09 15:08:12 +0000348
Douglas Gregorff790f12009-11-26 00:44:06 +0000349 // If this is an unevaluated operand, clear out the set of
350 // declaration references we have been computing and eliminate any
351 // temporaries introduced in its computation.
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000352 if (isUnevaluatedOperand)
Douglas Gregorff790f12009-11-26 00:44:06 +0000353 ExprEvalContexts.back().Context = Unevaluated;
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000354 }
Mike Stump11289f42009-09-09 15:08:12 +0000355
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000356 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
357 TypeInfoType.withConst(),
358 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc4704762008-11-11 11:37:55 +0000359}
360
Steve Naroff66356bd2007-09-16 14:56:35 +0000361/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000362Action::OwningExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000363Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000364 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000365 "Unknown C++ Boolean value!");
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000366 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
367 Context.BoolTy, OpLoc));
Bill Wendling4073ed52007-02-13 01:51:42 +0000368}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000369
Sebastian Redl576fd422009-05-10 18:38:11 +0000370/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
371Action::OwningExprResult
372Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
373 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
374}
375
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000376/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000377Action::OwningExprResult
378Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000379 Expr *Ex = E.takeAs<Expr>();
380 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
381 return ExprError();
382 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
383}
384
385/// CheckCXXThrowOperand - Validate the operand of a throw.
386bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
387 // C++ [except.throw]p3:
Douglas Gregor247894b2009-12-23 22:04:40 +0000388 // A throw-expression initializes a temporary object, called the exception
389 // object, the type of which is determined by removing any top-level
390 // cv-qualifiers from the static type of the operand of throw and adjusting
391 // the type from "array of T" or "function returning T" to "pointer to T"
392 // or "pointer to function returning T", [...]
393 if (E->getType().hasQualifiers())
394 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp,
395 E->isLvalue(Context) == Expr::LV_Valid);
396
Sebastian Redl4de47b42009-04-27 20:27:31 +0000397 DefaultFunctionArrayConversion(E);
398
399 // If the type of the exception would be an incomplete type or a pointer
400 // to an incomplete type other than (cv) void the program is ill-formed.
401 QualType Ty = E->getType();
402 int isPointer = 0;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000403 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000404 Ty = Ptr->getPointeeType();
405 isPointer = 1;
406 }
407 if (!isPointer || !Ty->isVoidType()) {
408 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlsson029fc692009-08-26 22:59:12 +0000409 PDiag(isPointer ? diag::err_throw_incomplete_ptr
410 : diag::err_throw_incomplete)
411 << E->getSourceRange()))
Sebastian Redl4de47b42009-04-27 20:27:31 +0000412 return true;
Rafael Espindola70e040d2010-03-02 21:28:26 +0000413
414 // FIXME: This is just a hack to mark the copy constructor referenced.
415 // This should go away when the next FIXME is fixed.
416 const RecordType *RT = Ty->getAs<RecordType>();
417 if (!RT)
418 return false;
419
420 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
421 if (RD->hasTrivialCopyConstructor())
422 return false;
423 CXXConstructorDecl *CopyCtor = RD->getCopyConstructor(Context, 0);
424 MarkDeclarationReferenced(ThrowLoc, CopyCtor);
Sebastian Redl4de47b42009-04-27 20:27:31 +0000425 }
426
427 // FIXME: Construct a temporary here.
428 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000429}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000430
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000431Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000432 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
433 /// is a non-lvalue expression whose value is the address of the object for
434 /// which the function is called.
435
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000436 if (!isa<FunctionDecl>(CurContext))
437 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000438
439 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
440 if (MD->isInstance())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000441 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregorb15af892010-01-07 23:12:05 +0000442 MD->getThisType(Context),
443 /*isImplicit=*/false));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000444
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000445 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000446}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000447
448/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
449/// Can be interpreted either as function-style casting ("int(x)")
450/// or class type construction ("ClassType(x,y,z)")
451/// or creation of a value-initialized type ("int()").
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000452Action::OwningExprResult
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000453Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
454 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000455 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000456 SourceLocation *CommaLocs,
457 SourceLocation RParenLoc) {
Douglas Gregor7df89f52010-02-05 19:11:37 +0000458 if (!TypeRep)
459 return ExprError();
460
John McCall97513962010-01-15 18:39:57 +0000461 TypeSourceInfo *TInfo;
462 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
463 if (!TInfo)
464 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000465 unsigned NumExprs = exprs.size();
466 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000467 SourceLocation TyBeginLoc = TypeRange.getBegin();
468 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
469
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000470 if (Ty->isDependentType() ||
Douglas Gregor0950e412009-03-13 21:01:28 +0000471 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000472 exprs.release();
Mike Stump11289f42009-09-09 15:08:12 +0000473
474 return Owned(CXXUnresolvedConstructExpr::Create(Context,
475 TypeRange.getBegin(), Ty,
Douglas Gregorce934142009-05-20 18:46:25 +0000476 LParenLoc,
477 Exprs, NumExprs,
478 RParenLoc));
Douglas Gregor0950e412009-03-13 21:01:28 +0000479 }
480
Anders Carlsson55243162009-08-27 03:53:50 +0000481 if (Ty->isArrayType())
482 return ExprError(Diag(TyBeginLoc,
483 diag::err_value_init_for_array_type) << FullRange);
484 if (!Ty->isVoidType() &&
485 RequireCompleteType(TyBeginLoc, Ty,
486 PDiag(diag::err_invalid_incomplete_type_use)
487 << FullRange))
488 return ExprError();
Fariborz Jahanian9a14b842009-10-23 21:01:39 +0000489
Anders Carlsson55243162009-08-27 03:53:50 +0000490 if (RequireNonAbstractType(TyBeginLoc, Ty,
491 diag::err_allocation_of_abstract_type))
492 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000493
494
Douglas Gregordd04d332009-01-16 18:33:17 +0000495 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000496 // If the expression list is a single expression, the type conversion
497 // expression is equivalent (in definedness, and if defined in meaning) to the
498 // corresponding cast expression.
499 //
500 if (NumExprs == 1) {
Anders Carlssonf10e4142009-08-07 22:21:05 +0000501 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlssone9766d52009-09-09 21:33:21 +0000502 CXXMethodDecl *Method = 0;
503 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
504 /*FunctionalStyle=*/true))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000505 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +0000506
507 exprs.release();
508 if (Method) {
509 OwningExprResult CastArg
510 = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(),
511 Kind, Method, Owned(Exprs[0]));
512 if (CastArg.isInvalid())
513 return ExprError();
514
515 Exprs[0] = CastArg.takeAs<Expr>();
Fariborz Jahanian8b899e42009-08-28 15:11:24 +0000516 }
Anders Carlssone9766d52009-09-09 21:33:21 +0000517
518 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
John McCall97513962010-01-15 18:39:57 +0000519 TInfo, TyBeginLoc, Kind,
Anders Carlssone9766d52009-09-09 21:33:21 +0000520 Exprs[0], RParenLoc));
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000521 }
522
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000523 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregordd04d332009-01-16 18:33:17 +0000524 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000525
Mike Stump11289f42009-09-09 15:08:12 +0000526 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlsson574315a2009-08-27 05:08:22 +0000527 !Record->hasTrivialDestructor()) {
Eli Friedmana6824272010-01-31 20:58:15 +0000528 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
529 InitializationKind Kind
530 = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
531 LParenLoc, RParenLoc)
532 : InitializationKind::CreateValue(TypeRange.getBegin(),
533 LParenLoc, RParenLoc);
534 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
535 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
536 move(exprs));
Douglas Gregordd04d332009-01-16 18:33:17 +0000537
Eli Friedmana6824272010-01-31 20:58:15 +0000538 // FIXME: Improve AST representation?
539 return move(Result);
Douglas Gregordd04d332009-01-16 18:33:17 +0000540 }
541
542 // Fall through to value-initialize an object of class type that
543 // doesn't have a user-declared default constructor.
544 }
545
546 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000547 // If the expression list specifies more than a single value, the type shall
548 // be a class with a suitably declared constructor.
549 //
550 if (NumExprs > 1)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000551 return ExprError(Diag(CommaLocs[0],
552 diag::err_builtin_func_cast_more_than_one_arg)
553 << FullRange);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000554
555 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregordd04d332009-01-16 18:33:17 +0000556 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000557 // The expression T(), where T is a simple-type-specifier for a non-array
558 // complete object type or the (possibly cv-qualified) void type, creates an
559 // rvalue of the specified type, which is value-initialized.
560 //
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000561 exprs.release();
562 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000563}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000564
565
Sebastian Redlbd150f42008-11-21 19:14:01 +0000566/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
567/// @code new (memory) int[size][4] @endcode
568/// or
569/// @code ::new Foo(23, "hello") @endcode
570/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000571Action::OwningExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +0000572Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000573 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redlbd150f42008-11-21 19:14:01 +0000574 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redl351bb782008-12-02 14:43:59 +0000575 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000576 MultiExprArg ConstructorArgs,
Mike Stump11289f42009-09-09 15:08:12 +0000577 SourceLocation ConstructorRParen) {
Sebastian Redl351bb782008-12-02 14:43:59 +0000578 Expr *ArraySize = 0;
Sebastian Redl351bb782008-12-02 14:43:59 +0000579 // If the specified type is an array, unwrap it and save the expression.
580 if (D.getNumTypeObjects() > 0 &&
581 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
582 DeclaratorChunk &Chunk = D.getTypeObject(0);
583 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000584 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
585 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000586 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000587 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
588 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000589
590 if (ParenTypeId) {
591 // Can't have dynamic array size when the type-id is in parentheses.
592 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
593 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
594 !NumElts->isIntegerConstantExpr(Context)) {
595 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
596 << NumElts->getSourceRange();
597 return ExprError();
598 }
599 }
600
Sebastian Redl351bb782008-12-02 14:43:59 +0000601 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000602 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +0000603 }
604
Douglas Gregor73341c42009-09-11 00:18:58 +0000605 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000606 if (ArraySize) {
607 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +0000608 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
609 break;
610
611 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
612 if (Expr *NumElts = (Expr *)Array.NumElts) {
613 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
614 !NumElts->isIntegerConstantExpr(Context)) {
615 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
616 << NumElts->getSourceRange();
617 return ExprError();
618 }
619 }
620 }
621 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000622
John McCallbcd03502009-12-07 02:54:59 +0000623 //FIXME: Store TypeSourceInfo in CXXNew expression.
624 TypeSourceInfo *TInfo = 0;
625 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000626 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000627 return ExprError();
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000628
Mike Stump11289f42009-09-09 15:08:12 +0000629 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000630 PlacementLParen,
Mike Stump11289f42009-09-09 15:08:12 +0000631 move(PlacementArgs),
Douglas Gregord0fefba2009-05-21 00:00:09 +0000632 PlacementRParen,
633 ParenTypeId,
Mike Stump11289f42009-09-09 15:08:12 +0000634 AllocType,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000635 D.getSourceRange().getBegin(),
636 D.getSourceRange(),
637 Owned(ArraySize),
638 ConstructorLParen,
639 move(ConstructorArgs),
640 ConstructorRParen);
641}
642
Mike Stump11289f42009-09-09 15:08:12 +0000643Sema::OwningExprResult
Douglas Gregord0fefba2009-05-21 00:00:09 +0000644Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
645 SourceLocation PlacementLParen,
646 MultiExprArg PlacementArgs,
647 SourceLocation PlacementRParen,
Mike Stump11289f42009-09-09 15:08:12 +0000648 bool ParenTypeId,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000649 QualType AllocType,
650 SourceLocation TypeLoc,
651 SourceRange TypeRange,
652 ExprArg ArraySizeE,
653 SourceLocation ConstructorLParen,
654 MultiExprArg ConstructorArgs,
655 SourceLocation ConstructorRParen) {
656 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000657 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +0000658
Douglas Gregord0fefba2009-05-21 00:00:09 +0000659 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redlbd150f42008-11-21 19:14:01 +0000660
661 // That every array dimension except the first is constant was already
662 // checked by the type check above.
Sebastian Redl351bb782008-12-02 14:43:59 +0000663
Sebastian Redlbd150f42008-11-21 19:14:01 +0000664 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
665 // or enumeration type with a non-negative value."
Douglas Gregord0fefba2009-05-21 00:00:09 +0000666 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000667 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redl351bb782008-12-02 14:43:59 +0000668 QualType SizeType = ArraySize->getType();
669 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000670 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
671 diag::err_array_size_not_integral)
672 << SizeType << ArraySize->getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000673 // Let's see if this is a constant < 0. If so, we reject it out of hand.
674 // We don't care about special rules, so we tell the machinery it's not
675 // evaluated - it gives us a result in more cases.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000676 if (!ArraySize->isValueDependent()) {
677 llvm::APSInt Value;
678 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
679 if (Value < llvm::APSInt(
Anders Carlsson8ab20bb2009-09-23 00:37:25 +0000680 llvm::APInt::getNullValue(Value.getBitWidth()),
681 Value.isUnsigned()))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000682 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
683 diag::err_typecheck_negative_array_size)
684 << ArraySize->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000685 }
Sebastian Redl351bb782008-12-02 14:43:59 +0000686 }
Anders Carlsson8ab20bb2009-09-23 00:37:25 +0000687
Eli Friedman06ed2a52009-10-20 08:27:19 +0000688 ImpCastExprToType(ArraySize, Context.getSizeType(),
689 CastExpr::CK_IntegralCast);
Sebastian Redl351bb782008-12-02 14:43:59 +0000690 }
Sebastian Redlbd150f42008-11-21 19:14:01 +0000691
Sebastian Redlbd150f42008-11-21 19:14:01 +0000692 FunctionDecl *OperatorNew = 0;
693 FunctionDecl *OperatorDelete = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000694 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
695 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000696
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000697 if (!AllocType->isDependentType() &&
698 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
699 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000700 SourceRange(PlacementLParen, PlacementRParen),
701 UseGlobal, AllocType, ArraySize, PlaceArgs,
702 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000703 return ExprError();
Fariborz Jahanian835026e2009-11-24 18:29:37 +0000704 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000705 if (OperatorNew) {
706 // Add default arguments, if any.
707 const FunctionProtoType *Proto =
708 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +0000709 VariadicCallType CallType =
710 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Fariborz Jahanian835026e2009-11-24 18:29:37 +0000711 bool Invalid = GatherArgumentsForCall(PlacementLParen, OperatorNew,
712 Proto, 1, PlaceArgs, NumPlaceArgs,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +0000713 AllPlaceArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +0000714 if (Invalid)
715 return ExprError();
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000716
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000717 NumPlaceArgs = AllPlaceArgs.size();
718 if (NumPlaceArgs > 0)
719 PlaceArgs = &AllPlaceArgs[0];
720 }
721
Sebastian Redlbd150f42008-11-21 19:14:01 +0000722 bool Init = ConstructorLParen.isValid();
723 // --- Choosing a constructor ---
Sebastian Redlbd150f42008-11-21 19:14:01 +0000724 CXXConstructorDecl *Constructor = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000725 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
726 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmanfd8d4e12009-11-08 22:15:39 +0000727 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
728
Douglas Gregor85dabae2009-12-16 01:38:02 +0000729 if (!AllocType->isDependentType() &&
730 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
731 // C++0x [expr.new]p15:
732 // A new-expression that creates an object of type T initializes that
733 // object as follows:
734 InitializationKind Kind
735 // - If the new-initializer is omitted, the object is default-
736 // initialized (8.5); if no initialization is performed,
737 // the object has indeterminate value
738 = !Init? InitializationKind::CreateDefault(TypeLoc)
739 // - Otherwise, the new-initializer is interpreted according to the
740 // initialization rules of 8.5 for direct-initialization.
741 : InitializationKind::CreateDirect(TypeLoc,
742 ConstructorLParen,
743 ConstructorRParen);
744
Douglas Gregor85dabae2009-12-16 01:38:02 +0000745 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +0000746 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000747 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000748 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
749 move(ConstructorArgs));
750 if (FullInit.isInvalid())
751 return ExprError();
752
753 // FullInit is our initializer; walk through it to determine if it's a
754 // constructor call, which CXXNewExpr handles directly.
755 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
756 if (CXXBindTemporaryExpr *Binder
757 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
758 FullInitExpr = Binder->getSubExpr();
759 if (CXXConstructExpr *Construct
760 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
761 Constructor = Construct->getConstructor();
762 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
763 AEnd = Construct->arg_end();
764 A != AEnd; ++A)
765 ConvertedConstructorArgs.push_back(A->Retain());
766 } else {
767 // Take the converted initializer.
768 ConvertedConstructorArgs.push_back(FullInit.release());
769 }
770 } else {
771 // No initialization required.
772 }
773
774 // Take the converted arguments and use them for the new expression.
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000775 NumConsArgs = ConvertedConstructorArgs.size();
776 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redlbd150f42008-11-21 19:14:01 +0000777 }
Douglas Gregor85dabae2009-12-16 01:38:02 +0000778
Douglas Gregor6642ca22010-02-26 05:06:18 +0000779 // Mark the new and delete operators as referenced.
780 if (OperatorNew)
781 MarkDeclarationReferenced(StartLoc, OperatorNew);
782 if (OperatorDelete)
783 MarkDeclarationReferenced(StartLoc, OperatorDelete);
784
Sebastian Redlbd150f42008-11-21 19:14:01 +0000785 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor4bbd1ac2009-10-17 21:40:42 +0000786
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000787 PlacementArgs.release();
788 ConstructorArgs.release();
Douglas Gregord0fefba2009-05-21 00:00:09 +0000789 ArraySizeE.release();
Ted Kremenek9d6eb402010-02-11 22:51:03 +0000790 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
791 PlaceArgs, NumPlaceArgs, ParenTypeId,
792 ArraySize, Constructor, Init,
793 ConsArgs, NumConsArgs, OperatorDelete,
794 ResultType, StartLoc,
795 Init ? ConstructorRParen :
796 SourceLocation()));
Sebastian Redlbd150f42008-11-21 19:14:01 +0000797}
798
799/// CheckAllocatedType - Checks that a type is suitable as the allocated type
800/// in a new-expression.
801/// dimension off and stores the size expression in ArraySize.
Douglas Gregord0fefba2009-05-21 00:00:09 +0000802bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000803 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +0000804 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
805 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +0000806 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +0000807 return Diag(Loc, diag::err_bad_new_type)
808 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +0000809 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +0000810 return Diag(Loc, diag::err_bad_new_type)
811 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +0000812 else if (!AllocType->isDependentType() &&
Douglas Gregord0fefba2009-05-21 00:00:09 +0000813 RequireCompleteType(Loc, AllocType,
Anders Carlssond624e162009-08-26 23:45:07 +0000814 PDiag(diag::err_new_incomplete_type)
815 << R))
Sebastian Redlbd150f42008-11-21 19:14:01 +0000816 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +0000817 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +0000818 diag::err_allocation_of_abstract_type))
819 return true;
Sebastian Redlbd150f42008-11-21 19:14:01 +0000820
Sebastian Redlbd150f42008-11-21 19:14:01 +0000821 return false;
822}
823
Douglas Gregor6642ca22010-02-26 05:06:18 +0000824/// \brief Determine whether the given function is a non-placement
825/// deallocation function.
826static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
827 if (FD->isInvalidDecl())
828 return false;
829
830 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
831 return Method->isUsualDeallocationFunction();
832
833 return ((FD->getOverloadedOperator() == OO_Delete ||
834 FD->getOverloadedOperator() == OO_Array_Delete) &&
835 FD->getNumParams() == 1);
836}
837
Sebastian Redlfaf68082008-12-03 20:26:15 +0000838/// FindAllocationFunctions - Finds the overloads of operator new and delete
839/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000840bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
841 bool UseGlobal, QualType AllocType,
842 bool IsArray, Expr **PlaceArgs,
843 unsigned NumPlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +0000844 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +0000845 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-12-03 20:26:15 +0000846 // --- Choosing an allocation function ---
847 // C++ 5.3.4p8 - 14 & 18
848 // 1) If UseGlobal is true, only look in the global scope. Else, also look
849 // in the scope of the allocated class.
850 // 2) If an array size is given, look for operator new[], else look for
851 // operator new.
852 // 3) The first argument is always size_t. Append the arguments from the
853 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +0000854
855 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
856 // We don't care about the actual value of this argument.
857 // FIXME: Should the Sema create the expression and embed it in the syntax
858 // tree? Or should the consumer just recalculate the value?
Anders Carlssona471db02009-08-16 20:29:29 +0000859 IntegerLiteral Size(llvm::APInt::getNullValue(
860 Context.Target.getPointerWidth(0)),
861 Context.getSizeType(),
862 SourceLocation());
863 AllocArgs[0] = &Size;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000864 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
865
Douglas Gregor6642ca22010-02-26 05:06:18 +0000866 // C++ [expr.new]p8:
867 // If the allocated type is a non-array type, the allocation
868 // function’s name is operator new and the deallocation function’s
869 // name is operator delete. If the allocated type is an array
870 // type, the allocation function’s name is operator new[] and the
871 // deallocation function’s name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +0000872 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
873 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +0000874 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
875 IsArray ? OO_Array_Delete : OO_Delete);
876
Sebastian Redlfaf68082008-12-03 20:26:15 +0000877 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump11289f42009-09-09 15:08:12 +0000878 CXXRecordDecl *Record
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000879 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000880 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +0000881 AllocArgs.size(), Record, /*AllowMissing=*/true,
882 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +0000883 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000884 }
885 if (!OperatorNew) {
886 // Didn't find a member overload. Look for a global one.
887 DeclareGlobalNewDelete();
Sebastian Redl33a31012008-12-04 22:20:51 +0000888 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000889 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +0000890 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
891 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +0000892 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000893 }
894
Anders Carlsson6f9dabf2009-05-31 20:26:12 +0000895 // FindAllocationOverload can change the passed in arguments, so we need to
896 // copy them back.
897 if (NumPlaceArgs > 0)
898 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump11289f42009-09-09 15:08:12 +0000899
Douglas Gregor6642ca22010-02-26 05:06:18 +0000900 // C++ [expr.new]p19:
901 //
902 // If the new-expression begins with a unary :: operator, the
903 // deallocation function’s name is looked up in the global
904 // scope. Otherwise, if the allocated type is a class type T or an
905 // array thereof, the deallocation function’s name is looked up in
906 // the scope of T. If this lookup fails to find the name, or if
907 // the allocated type is not a class type or array thereof, the
908 // deallocation function’s name is looked up in the global scope.
909 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
910 if (AllocType->isRecordType() && !UseGlobal) {
911 CXXRecordDecl *RD
912 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
913 LookupQualifiedName(FoundDelete, RD);
914 }
John McCallfb6f5262010-03-18 08:19:33 +0000915 if (FoundDelete.isAmbiguous())
916 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +0000917
918 if (FoundDelete.empty()) {
919 DeclareGlobalNewDelete();
920 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
921 }
922
923 FoundDelete.suppressDiagnostics();
John McCallfb6f5262010-03-18 08:19:33 +0000924 UnresolvedSet<4> Matches;
925 if (NumPlaceArgs > 0) {
Douglas Gregor6642ca22010-02-26 05:06:18 +0000926 // C++ [expr.new]p20:
927 // A declaration of a placement deallocation function matches the
928 // declaration of a placement allocation function if it has the
929 // same number of parameters and, after parameter transformations
930 // (8.3.5), all parameter types except the first are
931 // identical. [...]
932 //
933 // To perform this comparison, we compute the function type that
934 // the deallocation function should have, and use that type both
935 // for template argument deduction and for comparison purposes.
936 QualType ExpectedFunctionType;
937 {
938 const FunctionProtoType *Proto
939 = OperatorNew->getType()->getAs<FunctionProtoType>();
940 llvm::SmallVector<QualType, 4> ArgTypes;
941 ArgTypes.push_back(Context.VoidPtrTy);
942 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
943 ArgTypes.push_back(Proto->getArgType(I));
944
945 ExpectedFunctionType
946 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
947 ArgTypes.size(),
948 Proto->isVariadic(),
949 0, false, false, 0, 0, false, CC_Default);
950 }
951
952 for (LookupResult::iterator D = FoundDelete.begin(),
953 DEnd = FoundDelete.end();
954 D != DEnd; ++D) {
955 FunctionDecl *Fn = 0;
956 if (FunctionTemplateDecl *FnTmpl
957 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
958 // Perform template argument deduction to try to match the
959 // expected function type.
960 TemplateDeductionInfo Info(Context, StartLoc);
961 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
962 continue;
963 } else
964 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
965
966 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCallfb6f5262010-03-18 08:19:33 +0000967 Matches.addDecl(Fn, D.getAccess());
Douglas Gregor6642ca22010-02-26 05:06:18 +0000968 }
969 } else {
970 // C++ [expr.new]p20:
971 // [...] Any non-placement deallocation function matches a
972 // non-placement allocation function. [...]
973 for (LookupResult::iterator D = FoundDelete.begin(),
974 DEnd = FoundDelete.end();
975 D != DEnd; ++D) {
976 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
977 if (isNonPlacementDeallocationFunction(Fn))
John McCallfb6f5262010-03-18 08:19:33 +0000978 Matches.addDecl(D.getDecl(), D.getAccess());
Douglas Gregor6642ca22010-02-26 05:06:18 +0000979 }
980 }
981
982 // C++ [expr.new]p20:
983 // [...] If the lookup finds a single matching deallocation
984 // function, that function will be called; otherwise, no
985 // deallocation function will be called.
986 if (Matches.size() == 1) {
Douglas Gregor6642ca22010-02-26 05:06:18 +0000987 OperatorDelete = cast<FunctionDecl>(Matches[0]->getUnderlyingDecl());
988
989 // C++0x [expr.new]p20:
990 // If the lookup finds the two-parameter form of a usual
991 // deallocation function (3.7.4.2) and that function, considered
992 // as a placement deallocation function, would have been
993 // selected as a match for the allocation function, the program
994 // is ill-formed.
995 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
996 isNonPlacementDeallocationFunction(OperatorDelete)) {
997 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
998 << SourceRange(PlaceArgs[0]->getLocStart(),
999 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1000 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1001 << DeleteName;
John McCallfb6f5262010-03-18 08:19:33 +00001002 } else {
1003 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
1004 Matches[0].getDecl(), Matches[0].getAccess());
Douglas Gregor6642ca22010-02-26 05:06:18 +00001005 }
1006 }
1007
Sebastian Redlfaf68082008-12-03 20:26:15 +00001008 return false;
1009}
1010
Sebastian Redl33a31012008-12-04 22:20:51 +00001011/// FindAllocationOverload - Find an fitting overload for the allocation
1012/// function in the specified scope.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001013bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1014 DeclarationName Name, Expr** Args,
1015 unsigned NumArgs, DeclContext *Ctx,
Mike Stump11289f42009-09-09 15:08:12 +00001016 bool AllowMissing, FunctionDecl *&Operator) {
John McCall27b18f82009-11-17 02:14:36 +00001017 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1018 LookupQualifiedName(R, Ctx);
John McCall9f3059a2009-10-09 21:13:30 +00001019 if (R.empty()) {
Sebastian Redl33a31012008-12-04 22:20:51 +00001020 if (AllowMissing)
1021 return false;
Sebastian Redl33a31012008-12-04 22:20:51 +00001022 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00001023 << Name << Range;
Sebastian Redl33a31012008-12-04 22:20:51 +00001024 }
1025
John McCallfb6f5262010-03-18 08:19:33 +00001026 if (R.isAmbiguous())
1027 return true;
1028
1029 R.suppressDiagnostics();
John McCall9f3059a2009-10-09 21:13:30 +00001030
John McCallbc077cf2010-02-08 23:07:23 +00001031 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor80a6cc52009-09-30 00:03:47 +00001032 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1033 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor55297ac2008-12-23 00:26:44 +00001034 // Even member operator new/delete are implicitly treated as
1035 // static, so don't use AddMemberCandidate.
Chandler Carruth93538422010-02-03 11:02:14 +00001036
1037 if (FunctionTemplateDecl *FnTemplate =
1038 dyn_cast<FunctionTemplateDecl>((*Alloc)->getUnderlyingDecl())) {
1039 AddTemplateOverloadCandidate(FnTemplate, Alloc.getAccess(),
1040 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1041 Candidates,
1042 /*SuppressUserConversions=*/false);
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001043 continue;
Chandler Carruth93538422010-02-03 11:02:14 +00001044 }
1045
1046 FunctionDecl *Fn = cast<FunctionDecl>((*Alloc)->getUnderlyingDecl());
1047 AddOverloadCandidate(Fn, Alloc.getAccess(), Args, NumArgs, Candidates,
1048 /*SuppressUserConversions=*/false);
Sebastian Redl33a31012008-12-04 22:20:51 +00001049 }
1050
1051 // Do the resolution.
1052 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001053 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl33a31012008-12-04 22:20:51 +00001054 case OR_Success: {
1055 // Got one!
1056 FunctionDecl *FnDecl = Best->Function;
1057 // The first argument is size_t, and the first parameter must be size_t,
1058 // too. This is checked on declaration and can be assumed. (It can't be
1059 // asserted on, though, since invalid decls are left in there.)
John McCallfb6f5262010-03-18 08:19:33 +00001060 // Watch out for variadic allocator function.
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001061 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1062 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Anders Carlsson24187122009-05-31 19:49:47 +00001063 if (PerformCopyInitialization(Args[i],
Sebastian Redl33a31012008-12-04 22:20:51 +00001064 FnDecl->getParamDecl(i)->getType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001065 AA_Passing))
Sebastian Redl33a31012008-12-04 22:20:51 +00001066 return true;
1067 }
1068 Operator = FnDecl;
John McCallfb6f5262010-03-18 08:19:33 +00001069 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(),
1070 FnDecl, Best->getAccess());
Sebastian Redl33a31012008-12-04 22:20:51 +00001071 return false;
1072 }
1073
1074 case OR_No_Viable_Function:
Sebastian Redl33a31012008-12-04 22:20:51 +00001075 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00001076 << Name << Range;
John McCallad907772010-01-12 07:18:19 +00001077 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl33a31012008-12-04 22:20:51 +00001078 return true;
1079
1080 case OR_Ambiguous:
Sebastian Redl33a31012008-12-04 22:20:51 +00001081 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001082 << Name << Range;
John McCallad907772010-01-12 07:18:19 +00001083 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl33a31012008-12-04 22:20:51 +00001084 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001085
1086 case OR_Deleted:
1087 Diag(StartLoc, diag::err_ovl_deleted_call)
1088 << Best->Function->isDeleted()
1089 << Name << Range;
John McCallad907772010-01-12 07:18:19 +00001090 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001091 return true;
Sebastian Redl33a31012008-12-04 22:20:51 +00001092 }
1093 assert(false && "Unreachable, bad result from BestViableFunction");
1094 return true;
1095}
1096
1097
Sebastian Redlfaf68082008-12-03 20:26:15 +00001098/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1099/// delete. These are:
1100/// @code
1101/// void* operator new(std::size_t) throw(std::bad_alloc);
1102/// void* operator new[](std::size_t) throw(std::bad_alloc);
1103/// void operator delete(void *) throw();
1104/// void operator delete[](void *) throw();
1105/// @endcode
1106/// Note that the placement and nothrow forms of new are *not* implicitly
1107/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00001108void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001109 if (GlobalNewDeleteDeclared)
1110 return;
Douglas Gregor87f54062009-09-15 22:30:29 +00001111
1112 // C++ [basic.std.dynamic]p2:
1113 // [...] The following allocation and deallocation functions (18.4) are
1114 // implicitly declared in global scope in each translation unit of a
1115 // program
1116 //
1117 // void* operator new(std::size_t) throw(std::bad_alloc);
1118 // void* operator new[](std::size_t) throw(std::bad_alloc);
1119 // void operator delete(void*) throw();
1120 // void operator delete[](void*) throw();
1121 //
1122 // These implicit declarations introduce only the function names operator
1123 // new, operator new[], operator delete, operator delete[].
1124 //
1125 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1126 // "std" or "bad_alloc" as necessary to form the exception specification.
1127 // However, we do not make these implicit declarations visible to name
1128 // lookup.
1129 if (!StdNamespace) {
1130 // The "std" namespace has not yet been defined, so build one implicitly.
1131 StdNamespace = NamespaceDecl::Create(Context,
1132 Context.getTranslationUnitDecl(),
1133 SourceLocation(),
1134 &PP.getIdentifierTable().get("std"));
1135 StdNamespace->setImplicit(true);
1136 }
1137
1138 if (!StdBadAlloc) {
1139 // The "std::bad_alloc" class has not yet been declared, so build it
1140 // implicitly.
1141 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
1142 StdNamespace,
1143 SourceLocation(),
1144 &PP.getIdentifierTable().get("bad_alloc"),
1145 SourceLocation(), 0);
1146 StdBadAlloc->setImplicit(true);
1147 }
1148
Sebastian Redlfaf68082008-12-03 20:26:15 +00001149 GlobalNewDeleteDeclared = true;
1150
1151 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1152 QualType SizeT = Context.getSizeType();
Nuno Lopes13c88c72009-12-16 16:59:22 +00001153 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001154
Sebastian Redlfaf68082008-12-03 20:26:15 +00001155 DeclareGlobalAllocationFunction(
1156 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001157 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001158 DeclareGlobalAllocationFunction(
1159 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001160 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001161 DeclareGlobalAllocationFunction(
1162 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1163 Context.VoidTy, VoidPtr);
1164 DeclareGlobalAllocationFunction(
1165 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1166 Context.VoidTy, VoidPtr);
1167}
1168
1169/// DeclareGlobalAllocationFunction - Declares a single implicit global
1170/// allocation function if it doesn't already exist.
1171void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopes13c88c72009-12-16 16:59:22 +00001172 QualType Return, QualType Argument,
1173 bool AddMallocAttr) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001174 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1175
1176 // Check if this function is already declared.
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001177 {
Douglas Gregor17eb26b2008-12-23 22:05:29 +00001178 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001179 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001180 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth93538422010-02-03 11:02:14 +00001181 // Only look at non-template functions, as it is the predefined,
1182 // non-templated allocation function we are trying to declare here.
1183 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1184 QualType InitialParamType =
Douglas Gregor684d7bd2009-12-22 23:42:49 +00001185 Context.getCanonicalType(
Chandler Carruth93538422010-02-03 11:02:14 +00001186 Func->getParamDecl(0)->getType().getUnqualifiedType());
1187 // FIXME: Do we need to check for default arguments here?
1188 if (Func->getNumParams() == 1 && InitialParamType == Argument)
1189 return;
1190 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00001191 }
1192 }
1193
Douglas Gregor87f54062009-09-15 22:30:29 +00001194 QualType BadAllocType;
1195 bool HasBadAllocExceptionSpec
1196 = (Name.getCXXOverloadedOperator() == OO_New ||
1197 Name.getCXXOverloadedOperator() == OO_Array_New);
1198 if (HasBadAllocExceptionSpec) {
1199 assert(StdBadAlloc && "Must have std::bad_alloc declared");
1200 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
1201 }
1202
1203 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1204 true, false,
1205 HasBadAllocExceptionSpec? 1 : 0,
Douglas Gregor36c569f2010-02-21 22:15:06 +00001206 &BadAllocType, false, CC_Default);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001207 FunctionDecl *Alloc =
1208 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCallbcd03502009-12-07 02:54:59 +00001209 FnType, /*TInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001210 Alloc->setImplicit();
Nuno Lopes13c88c72009-12-16 16:59:22 +00001211
1212 if (AddMallocAttr)
1213 Alloc->addAttr(::new (Context) MallocAttr());
1214
Sebastian Redlfaf68082008-12-03 20:26:15 +00001215 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCallbcd03502009-12-07 02:54:59 +00001216 0, Argument, /*TInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00001217 VarDecl::None, 0);
Douglas Gregord5058122010-02-11 01:19:42 +00001218 Alloc->setParams(&Param, 1);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001219
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001220 // FIXME: Also add this declaration to the IdentifierResolver, but
1221 // make sure it is at the end of the chain to coincide with the
1222 // global scope.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001223 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001224}
1225
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001226bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1227 DeclarationName Name,
Anders Carlssonf98849e2009-12-02 17:15:43 +00001228 FunctionDecl* &Operator) {
John McCall27b18f82009-11-17 02:14:36 +00001229 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001230 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00001231 LookupQualifiedName(Found, RD);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001232
John McCall27b18f82009-11-17 02:14:36 +00001233 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001234 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001235
1236 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1237 F != FEnd; ++F) {
1238 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
1239 if (Delete->isUsualDeallocationFunction()) {
1240 Operator = Delete;
1241 return false;
1242 }
1243 }
1244
1245 // We did find operator delete/operator delete[] declarations, but
1246 // none of them were suitable.
1247 if (!Found.empty()) {
1248 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1249 << Name << RD;
1250
1251 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1252 F != FEnd; ++F) {
1253 Diag((*F)->getLocation(),
1254 diag::note_delete_member_function_declared_here)
1255 << Name;
1256 }
1257
1258 return true;
1259 }
1260
1261 // Look for a global declaration.
1262 DeclareGlobalNewDelete();
1263 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1264
1265 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1266 Expr* DeallocArgs[1];
1267 DeallocArgs[0] = &Null;
1268 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1269 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1270 Operator))
1271 return true;
1272
1273 assert(Operator && "Did not find a deallocation function!");
1274 return false;
1275}
1276
Sebastian Redlbd150f42008-11-21 19:14:01 +00001277/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1278/// @code ::delete ptr; @endcode
1279/// or
1280/// @code delete [] ptr; @endcode
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001281Action::OwningExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001282Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump11289f42009-09-09 15:08:12 +00001283 bool ArrayForm, ExprArg Operand) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001284 // C++ [expr.delete]p1:
1285 // The operand shall have a pointer type, or a class type having a single
1286 // conversion function to a pointer type. The result has type void.
1287 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00001288 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1289
Anders Carlssona471db02009-08-16 20:29:29 +00001290 FunctionDecl *OperatorDelete = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001291
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001292 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001293 if (!Ex->isTypeDependent()) {
1294 QualType Type = Ex->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00001295
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001296 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001297 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
Fariborz Jahanianb54ccb22009-09-11 21:44:33 +00001298 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCallad371252010-01-20 00:46:10 +00001299 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001300
John McCallad371252010-01-20 00:46:10 +00001301 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001302 E = Conversions->end(); I != E; ++I) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001303 // Skip over templated conversion functions; they aren't considered.
John McCalld14a8642009-11-21 08:51:07 +00001304 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001305 continue;
1306
John McCalld14a8642009-11-21 08:51:07 +00001307 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001308
1309 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1310 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1311 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001312 ObjectPtrConversions.push_back(Conv);
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001313 }
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001314 if (ObjectPtrConversions.size() == 1) {
1315 // We have a single conversion to a pointer-to-object type. Perform
1316 // that conversion.
1317 Operand.release();
1318 if (!PerformImplicitConversion(Ex,
1319 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001320 AA_Converting)) {
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001321 Operand = Owned(Ex);
1322 Type = Ex->getType();
1323 }
1324 }
1325 else if (ObjectPtrConversions.size() > 1) {
1326 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1327 << Type << Ex->getSourceRange();
1328 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
1329 CXXConversionDecl *Conv = ObjectPtrConversions[i];
John McCallfd0b2f82010-01-06 09:43:14 +00001330 NoteOverloadCandidate(Conv);
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001331 }
1332 return ExprError();
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001333 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001334 }
1335
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001336 if (!Type->isPointerType())
1337 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1338 << Type << Ex->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001339
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001340 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001341 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001342 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1343 << Type << Ex->getSourceRange());
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001344 else if (!Pointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00001345 RequireCompleteType(StartLoc, Pointee,
Anders Carlssond624e162009-08-26 23:45:07 +00001346 PDiag(diag::warn_delete_incomplete)
1347 << Ex->getSourceRange()))
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001348 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001349
Douglas Gregor98496dc2009-09-29 21:38:53 +00001350 // C++ [expr.delete]p2:
1351 // [Note: a pointer to a const type can be the operand of a
1352 // delete-expression; it is not necessary to cast away the constness
1353 // (5.2.11) of the pointer expression before it is used as the operand
1354 // of the delete-expression. ]
1355 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
1356 CastExpr::CK_NoOp);
1357
1358 // Update the operand.
1359 Operand.take();
1360 Operand = ExprArg(*this, Ex);
1361
Anders Carlssona471db02009-08-16 20:29:29 +00001362 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1363 ArrayForm ? OO_Array_Delete : OO_Delete);
1364
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001365 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
1366 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1367
1368 if (!UseGlobal &&
1369 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00001370 return ExprError();
Anders Carlsson654e5c72009-11-14 03:17:38 +00001371
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001372 if (!RD->hasTrivialDestructor())
1373 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump11289f42009-09-09 15:08:12 +00001374 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001375 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssona471db02009-08-16 20:29:29 +00001376 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001377
Anders Carlssona471db02009-08-16 20:29:29 +00001378 if (!OperatorDelete) {
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001379 // Look for a global declaration.
Anders Carlssona471db02009-08-16 20:29:29 +00001380 DeclareGlobalNewDelete();
1381 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001382 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001383 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssona471db02009-08-16 20:29:29 +00001384 OperatorDelete))
1385 return ExprError();
1386 }
Mike Stump11289f42009-09-09 15:08:12 +00001387
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001388 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redlbd150f42008-11-21 19:14:01 +00001389 }
1390
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001391 Operand.release();
1392 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssona471db02009-08-16 20:29:29 +00001393 OperatorDelete, Ex, StartLoc));
Sebastian Redlbd150f42008-11-21 19:14:01 +00001394}
1395
Douglas Gregor633caca2009-11-23 23:44:04 +00001396/// \brief Check the use of the given variable as a C++ condition in an if,
1397/// while, do-while, or switch statement.
1398Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar) {
1399 QualType T = ConditionVar->getType();
1400
1401 // C++ [stmt.select]p2:
1402 // The declarator shall not specify a function or an array.
1403 if (T->isFunctionType())
1404 return ExprError(Diag(ConditionVar->getLocation(),
1405 diag::err_invalid_use_of_function_type)
1406 << ConditionVar->getSourceRange());
1407 else if (T->isArrayType())
1408 return ExprError(Diag(ConditionVar->getLocation(),
1409 diag::err_invalid_use_of_array_type)
1410 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00001411
Douglas Gregor633caca2009-11-23 23:44:04 +00001412 return Owned(DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1413 ConditionVar->getLocation(),
1414 ConditionVar->getType().getNonReferenceType()));
1415}
1416
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001417/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1418bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1419 // C++ 6.4p4:
1420 // The value of a condition that is an initialized declaration in a statement
1421 // other than a switch statement is the value of the declared variable
1422 // implicitly converted to type bool. If that conversion is ill-formed, the
1423 // program is ill-formed.
1424 // The value of a condition that is an expression is the value of the
1425 // expression, implicitly converted to bool.
1426 //
Douglas Gregor5fb53972009-01-14 15:45:31 +00001427 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001428}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001429
1430/// Helper function to determine whether this is the (deprecated) C++
1431/// conversion from a string literal to a pointer to non-const char or
1432/// non-const wchar_t (for narrow and wide string literals,
1433/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00001434bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001435Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1436 // Look inside the implicit cast, if it exists.
1437 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1438 From = Cast->getSubExpr();
1439
1440 // A string literal (2.13.4) that is not a wide string literal can
1441 // be converted to an rvalue of type "pointer to char"; a wide
1442 // string literal can be converted to an rvalue of type "pointer
1443 // to wchar_t" (C++ 4.2p2).
1444 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001445 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001446 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00001447 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001448 // This conversion is considered only when there is an
1449 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall8ccfcb52009-09-24 19:53:00 +00001450 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001451 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1452 (!StrLit->isWide() &&
1453 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1454 ToPointeeType->getKind() == BuiltinType::Char_S))))
1455 return true;
1456 }
1457
1458 return false;
1459}
Douglas Gregor39c16d42008-10-24 04:54:22 +00001460
1461/// PerformImplicitConversion - Perform an implicit conversion of the
1462/// expression From to the type ToType. Returns true if there was an
1463/// error, false otherwise. The expression From is replaced with the
Douglas Gregor47d3f272008-12-19 17:40:08 +00001464/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor5fb53972009-01-14 15:45:31 +00001465/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redl42e92c42009-04-12 17:16:29 +00001466/// explicit user-defined conversions are permitted. @p Elidable should be true
1467/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
1468/// resolution works differently in that case.
1469bool
Douglas Gregor47d3f272008-12-19 17:40:08 +00001470Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001471 AssignmentAction Action, bool AllowExplicit,
Mike Stump11289f42009-09-09 15:08:12 +00001472 bool Elidable) {
Sebastian Redl42e92c42009-04-12 17:16:29 +00001473 ImplicitConversionSequence ICS;
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001474 return PerformImplicitConversion(From, ToType, Action, AllowExplicit,
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00001475 Elidable, ICS);
1476}
1477
1478bool
1479Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001480 AssignmentAction Action, bool AllowExplicit,
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00001481 bool Elidable,
1482 ImplicitConversionSequence& ICS) {
John McCall65eb8792010-02-25 01:37:24 +00001483 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redl42e92c42009-04-12 17:16:29 +00001484 if (Elidable && getLangOptions().CPlusPlus0x) {
Mike Stump11289f42009-09-09 15:08:12 +00001485 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00001486 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00001487 AllowExplicit,
Anders Carlsson228eea32009-08-28 15:33:32 +00001488 /*ForceRValue=*/true,
1489 /*InOverloadResolution=*/false);
Sebastian Redl42e92c42009-04-12 17:16:29 +00001490 }
John McCall0d1da222010-01-12 00:44:57 +00001491 if (ICS.isBad()) {
Mike Stump11289f42009-09-09 15:08:12 +00001492 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00001493 /*SuppressUserConversions=*/false,
1494 AllowExplicit,
Anders Carlsson228eea32009-08-28 15:33:32 +00001495 /*ForceRValue=*/false,
1496 /*InOverloadResolution=*/false);
Sebastian Redl42e92c42009-04-12 17:16:29 +00001497 }
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001498 return PerformImplicitConversion(From, ToType, ICS, Action);
Douglas Gregor5fb53972009-01-14 15:45:31 +00001499}
1500
1501/// PerformImplicitConversion - Perform an implicit conversion of the
1502/// expression From to the type ToType using the pre-computed implicit
1503/// conversion sequence ICS. Returns true if there was an error, false
1504/// otherwise. The expression From is replaced with the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001505/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001506/// used in the error message.
1507bool
1508Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1509 const ImplicitConversionSequence &ICS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001510 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall0d1da222010-01-12 00:44:57 +00001511 switch (ICS.getKind()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001512 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001513 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redl7c353682009-11-14 21:15:49 +00001514 IgnoreBaseAccess))
Douglas Gregor39c16d42008-10-24 04:54:22 +00001515 return true;
1516 break;
1517
Anders Carlsson110b07b2009-09-15 06:28:28 +00001518 case ImplicitConversionSequence::UserDefinedConversion: {
1519
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00001520 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1521 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlsson110b07b2009-09-15 06:28:28 +00001522 QualType BeforeToType;
1523 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00001524 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlsson110b07b2009-09-15 06:28:28 +00001525
1526 // If the user-defined conversion is specified by a conversion function,
1527 // the initial standard conversion sequence converts the source type to
1528 // the implicit object parameter of the conversion function.
1529 BeforeToType = Context.getTagDeclType(Conv->getParent());
1530 } else if (const CXXConstructorDecl *Ctor =
1531 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlssone9766d52009-09-09 21:33:21 +00001532 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001533 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00001534 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian55824512009-11-06 00:23:08 +00001535 // If the user-defined conversion is specified by a constructor, the
1536 // initial standard conversion sequence converts the source type to the
1537 // type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00001538 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1539 }
Anders Carlsson110b07b2009-09-15 06:28:28 +00001540 }
Anders Carlssone9766d52009-09-09 21:33:21 +00001541 else
1542 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian55824512009-11-06 00:23:08 +00001543 // Whatch out for elipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00001544 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian55824512009-11-06 00:23:08 +00001545 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001546 ICS.UserDefined.Before, AA_Converting,
Sebastian Redl7c353682009-11-14 21:15:49 +00001547 IgnoreBaseAccess))
Fariborz Jahanian55824512009-11-06 00:23:08 +00001548 return true;
1549 }
Anders Carlsson110b07b2009-09-15 06:28:28 +00001550
Anders Carlssone9766d52009-09-09 21:33:21 +00001551 OwningExprResult CastArg
1552 = BuildCXXCastArgument(From->getLocStart(),
1553 ToType.getNonReferenceType(),
1554 CastKind, cast<CXXMethodDecl>(FD),
1555 Owned(From));
1556
1557 if (CastArg.isInvalid())
1558 return true;
Eli Friedmane96f1d32009-11-27 04:41:50 +00001559
1560 From = CastArg.takeAs<Expr>();
1561
Eli Friedmane96f1d32009-11-27 04:41:50 +00001562 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001563 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00001564 }
John McCall0d1da222010-01-12 00:44:57 +00001565
1566 case ImplicitConversionSequence::AmbiguousConversion:
1567 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1568 PDiag(diag::err_typecheck_ambiguous_condition)
1569 << From->getSourceRange());
1570 return true;
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00001571
Douglas Gregor39c16d42008-10-24 04:54:22 +00001572 case ImplicitConversionSequence::EllipsisConversion:
1573 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001574 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001575
1576 case ImplicitConversionSequence::BadConversion:
1577 return true;
1578 }
1579
1580 // Everything went well.
1581 return false;
1582}
1583
1584/// PerformImplicitConversion - Perform an implicit conversion of the
1585/// expression From to the type ToType by following the standard
1586/// conversion sequence SCS. Returns true if there was an error, false
1587/// otherwise. The expression From is replaced with the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00001588/// expression. Flavor is the context in which we're performing this
1589/// conversion, for use in error messages.
Mike Stump11289f42009-09-09 15:08:12 +00001590bool
Douglas Gregor39c16d42008-10-24 04:54:22 +00001591Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001592 const StandardConversionSequence& SCS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001593 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001594 // Overall FIXME: we are recomputing too many types here and doing far too
1595 // much extra work. What this means is that we need to keep track of more
1596 // information that is computed when we try the implicit conversion initially,
1597 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00001598 QualType FromType = From->getType();
1599
Douglas Gregor2fe98832008-11-03 19:09:14 +00001600 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00001601 // FIXME: When can ToType be a reference type?
1602 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00001603 if (SCS.Second == ICK_Derived_To_Base) {
1604 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1605 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1606 MultiExprArg(*this, (void **)&From, 1),
1607 /*FIXME:ConstructLoc*/SourceLocation(),
1608 ConstructorArgs))
1609 return true;
1610 OwningExprResult FromResult =
1611 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1612 ToType, SCS.CopyConstructor,
1613 move_arg(ConstructorArgs));
1614 if (FromResult.isInvalid())
1615 return true;
1616 From = FromResult.takeAs<Expr>();
1617 return false;
1618 }
Mike Stump11289f42009-09-09 15:08:12 +00001619 OwningExprResult FromResult =
1620 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1621 ToType, SCS.CopyConstructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00001622 MultiExprArg(*this, (void**)&From, 1));
Mike Stump11289f42009-09-09 15:08:12 +00001623
Anders Carlsson6eb55572009-08-25 05:12:04 +00001624 if (FromResult.isInvalid())
1625 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001626
Anders Carlsson6eb55572009-08-25 05:12:04 +00001627 From = FromResult.takeAs<Expr>();
Douglas Gregor2fe98832008-11-03 19:09:14 +00001628 return false;
1629 }
1630
Douglas Gregor39c16d42008-10-24 04:54:22 +00001631 // Perform the first implicit conversion.
1632 switch (SCS.First) {
1633 case ICK_Identity:
1634 case ICK_Lvalue_To_Rvalue:
1635 // Nothing to do.
1636 break;
1637
1638 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00001639 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson2c101b32009-08-08 21:04:35 +00001640 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001641 break;
1642
1643 case ICK_Function_To_Pointer:
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001644 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00001645 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1646 if (!Fn)
1647 return true;
1648
Douglas Gregor171c45a2009-02-18 21:56:37 +00001649 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1650 return true;
1651
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00001652 From = FixOverloadedFunctionReference(From, Fn);
Douglas Gregorcd695e52008-11-10 20:40:00 +00001653 FromType = From->getType();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00001654
Sebastian Redlfef1c0d2009-10-17 20:50:27 +00001655 // If there's already an address-of operator in the expression, we have
1656 // the right type already, and the code below would just introduce an
1657 // invalid additional pointer level.
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00001658 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
Sebastian Redlfef1c0d2009-10-17 20:50:27 +00001659 break;
Douglas Gregorcd695e52008-11-10 20:40:00 +00001660 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001661 FromType = Context.getPointerType(FromType);
Anders Carlsson6904f642009-09-01 20:37:18 +00001662 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001663 break;
1664
1665 default:
1666 assert(false && "Improper first standard conversion");
1667 break;
1668 }
1669
1670 // Perform the second implicit conversion
1671 switch (SCS.Second) {
1672 case ICK_Identity:
Sebastian Redl5d431642009-10-10 12:04:10 +00001673 // If both sides are functions (or pointers/references to them), there could
1674 // be incompatible exception declarations.
1675 if (CheckExceptionSpecCompatibility(From, ToType))
1676 return true;
1677 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00001678 break;
1679
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001680 case ICK_NoReturn_Adjustment:
1681 // If both sides are functions (or pointers/references to them), there could
1682 // be incompatible exception declarations.
1683 if (CheckExceptionSpecCompatibility(From, ToType))
1684 return true;
1685
1686 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1687 CastExpr::CK_NoOp);
1688 break;
1689
Douglas Gregor39c16d42008-10-24 04:54:22 +00001690 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001691 case ICK_Integral_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001692 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1693 break;
1694
1695 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001696 case ICK_Floating_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001697 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1698 break;
1699
1700 case ICK_Complex_Promotion:
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001701 case ICK_Complex_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001702 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1703 break;
1704
Douglas Gregor39c16d42008-10-24 04:54:22 +00001705 case ICK_Floating_Integral:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001706 if (ToType->isFloatingType())
1707 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1708 else
1709 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1710 break;
1711
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001712 case ICK_Complex_Real:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001713 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1714 break;
1715
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001716 case ICK_Compatible_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001717 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001718 break;
1719
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001720 case ICK_Pointer_Conversion: {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001721 if (SCS.IncompatibleObjC) {
1722 // Diagnose incompatible Objective-C conversions
Mike Stump11289f42009-09-09 15:08:12 +00001723 Diag(From->getSourceRange().getBegin(),
Douglas Gregor47d3f272008-12-19 17:40:08 +00001724 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001725 << From->getType() << ToType << Action
Douglas Gregor47d3f272008-12-19 17:40:08 +00001726 << From->getSourceRange();
1727 }
1728
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001729
1730 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redl7c353682009-11-14 21:15:49 +00001731 if (CheckPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Douglas Gregor39c16d42008-10-24 04:54:22 +00001732 return true;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001733 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001734 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001735 }
1736
1737 case ICK_Pointer_Member: {
1738 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redl7c353682009-11-14 21:15:49 +00001739 if (CheckMemberPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001740 return true;
Sebastian Redl5d431642009-10-10 12:04:10 +00001741 if (CheckExceptionSpecCompatibility(From, ToType))
1742 return true;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001743 ImpCastExprToType(From, ToType, Kind);
1744 break;
1745 }
Anders Carlsson7fa434c2009-11-23 20:04:44 +00001746 case ICK_Boolean_Conversion: {
1747 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1748 if (FromType->isMemberPointerType())
1749 Kind = CastExpr::CK_MemberPointerToBoolean;
1750
1751 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001752 break;
Anders Carlsson7fa434c2009-11-23 20:04:44 +00001753 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001754
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001755 case ICK_Derived_To_Base:
1756 if (CheckDerivedToBaseConversion(From->getType(),
1757 ToType.getNonReferenceType(),
1758 From->getLocStart(),
Sebastian Redl7c353682009-11-14 21:15:49 +00001759 From->getSourceRange(),
1760 IgnoreBaseAccess))
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001761 return true;
1762 ImpCastExprToType(From, ToType.getNonReferenceType(),
1763 CastExpr::CK_DerivedToBase);
1764 break;
1765
Douglas Gregor39c16d42008-10-24 04:54:22 +00001766 default:
1767 assert(false && "Improper second standard conversion");
1768 break;
1769 }
1770
1771 switch (SCS.Third) {
1772 case ICK_Identity:
1773 // Nothing to do.
1774 break;
1775
1776 case ICK_Qualification:
Mike Stump87c57ac2009-05-16 07:39:55 +00001777 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1778 // references.
Mike Stump11289f42009-09-09 15:08:12 +00001779 ImpCastExprToType(From, ToType.getNonReferenceType(),
Eli Friedman06ed2a52009-10-20 08:27:19 +00001780 CastExpr::CK_NoOp,
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001781 ToType->isLValueReferenceType());
Douglas Gregore489a7d2010-02-28 18:30:25 +00001782
1783 if (SCS.DeprecatedStringLiteralToCharPtr)
1784 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
1785 << ToType.getNonReferenceType();
1786
Douglas Gregor39c16d42008-10-24 04:54:22 +00001787 break;
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001788
Douglas Gregor39c16d42008-10-24 04:54:22 +00001789 default:
1790 assert(false && "Improper second standard conversion");
1791 break;
1792 }
1793
1794 return false;
1795}
1796
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001797Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1798 SourceLocation KWLoc,
1799 SourceLocation LParen,
1800 TypeTy *Ty,
1801 SourceLocation RParen) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001802 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00001803
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001804 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1805 // all traits except __is_class, __is_enum and __is_union require a the type
1806 // to be complete.
1807 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump11289f42009-09-09 15:08:12 +00001808 if (RequireCompleteType(KWLoc, T,
Anders Carlsson029fc692009-08-26 22:59:12 +00001809 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001810 return ExprError();
1811 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001812
1813 // There is no point in eagerly computing the value. The traits are designed
1814 // to be used from type trait templates, so Ty will be a template parameter
1815 // 99% of the time.
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001816 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1817 RParen, Context.BoolTy));
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001818}
Sebastian Redl5822f082009-02-07 20:10:22 +00001819
1820QualType Sema::CheckPointerToMemberOperands(
Mike Stump11289f42009-09-09 15:08:12 +00001821 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl5822f082009-02-07 20:10:22 +00001822 const char *OpSpelling = isIndirect ? "->*" : ".*";
1823 // C++ 5.5p2
1824 // The binary operator .* [p3: ->*] binds its second operand, which shall
1825 // be of type "pointer to member of T" (where T is a completely-defined
1826 // class type) [...]
1827 QualType RType = rex->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001828 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00001829 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00001830 Diag(Loc, diag::err_bad_memptr_rhs)
1831 << OpSpelling << RType << rex->getSourceRange();
1832 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001833 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00001834
Sebastian Redl5822f082009-02-07 20:10:22 +00001835 QualType Class(MemPtr->getClass(), 0);
1836
1837 // C++ 5.5p2
1838 // [...] to its first operand, which shall be of class T or of a class of
1839 // which T is an unambiguous and accessible base class. [p3: a pointer to
1840 // such a class]
1841 QualType LType = lex->getType();
1842 if (isIndirect) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001843 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl5822f082009-02-07 20:10:22 +00001844 LType = Ptr->getPointeeType().getNonReferenceType();
1845 else {
1846 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanian59f64202009-10-26 20:45:27 +00001847 << OpSpelling << 1 << LType
1848 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00001849 return QualType();
1850 }
1851 }
1852
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001853 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001854 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1855 /*DetectVirtual=*/false);
Mike Stump87c57ac2009-05-16 07:39:55 +00001856 // FIXME: Would it be useful to print full ambiguity paths, or is that
1857 // overkill?
Sebastian Redl5822f082009-02-07 20:10:22 +00001858 if (!IsDerivedFrom(LType, Class, Paths) ||
1859 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1860 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman1fcf66b2010-01-16 00:00:48 +00001861 << (int)isIndirect << lex->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00001862 return QualType();
1863 }
Eli Friedman1fcf66b2010-01-16 00:00:48 +00001864 // Cast LHS to type of use.
1865 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
1866 bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid;
1867 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue);
Sebastian Redl5822f082009-02-07 20:10:22 +00001868 }
1869
Fariborz Jahanianfff3fb22009-11-18 22:16:17 +00001870 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00001871 // Diagnose use of pointer-to-member type which when used as
1872 // the functional cast in a pointer-to-member expression.
1873 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1874 return QualType();
1875 }
Sebastian Redl5822f082009-02-07 20:10:22 +00001876 // C++ 5.5p2
1877 // The result is an object or a function of the type specified by the
1878 // second operand.
1879 // The cv qualifiers are the union of those in the pointer and the left side,
1880 // in accordance with 5.5p5 and 5.2.5.
1881 // FIXME: This returns a dereferenced member function pointer as a normal
1882 // function type. However, the only operation valid on such functions is
Mike Stump87c57ac2009-05-16 07:39:55 +00001883 // calling them. There's also a GCC extension to get a function pointer to the
1884 // thing, which is another complication, because this type - unlike the type
1885 // that is the result of this expression - takes the class as the first
Sebastian Redl5822f082009-02-07 20:10:22 +00001886 // argument.
1887 // We probably need a "MemberFunctionClosureType" or something like that.
1888 QualType Result = MemPtr->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00001889 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl5822f082009-02-07 20:10:22 +00001890 return Result;
1891}
Sebastian Redl1a99f442009-04-16 17:51:27 +00001892
1893/// \brief Get the target type of a standard or user-defined conversion.
1894static QualType TargetType(const ImplicitConversionSequence &ICS) {
John McCall0d1da222010-01-12 00:44:57 +00001895 switch (ICS.getKind()) {
1896 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001897 return ICS.Standard.getToType(2);
John McCall0d1da222010-01-12 00:44:57 +00001898 case ImplicitConversionSequence::UserDefinedConversion:
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001899 return ICS.UserDefined.After.getToType(2);
John McCall0d1da222010-01-12 00:44:57 +00001900 case ImplicitConversionSequence::AmbiguousConversion:
1901 return ICS.Ambiguous.getToType();
John McCall65eb8792010-02-25 01:37:24 +00001902
John McCall0d1da222010-01-12 00:44:57 +00001903 case ImplicitConversionSequence::EllipsisConversion:
1904 case ImplicitConversionSequence::BadConversion:
1905 llvm_unreachable("function not valid for ellipsis or bad conversions");
1906 }
1907 return QualType(); // silence warnings
Sebastian Redl1a99f442009-04-16 17:51:27 +00001908}
1909
1910/// \brief Try to convert a type to another according to C++0x 5.16p3.
1911///
1912/// This is part of the parameter validation for the ? operator. If either
1913/// value operand is a class type, the two operands are attempted to be
1914/// converted to each other. This function does the conversion in one direction.
1915/// It emits a diagnostic and returns true only if it finds an ambiguous
1916/// conversion.
1917static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1918 SourceLocation QuestionLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001919 ImplicitConversionSequence &ICS) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00001920 // C++0x 5.16p3
1921 // The process for determining whether an operand expression E1 of type T1
1922 // can be converted to match an operand expression E2 of type T2 is defined
1923 // as follows:
1924 // -- If E2 is an lvalue:
1925 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1926 // E1 can be converted to match E2 if E1 can be implicitly converted to
1927 // type "lvalue reference to T2", subject to the constraint that in the
1928 // conversion the reference must bind directly to E1.
1929 if (!Self.CheckReferenceInit(From,
1930 Self.Context.getLValueReferenceType(To->getType()),
Douglas Gregorc809cc22009-09-23 23:04:10 +00001931 To->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00001932 /*SuppressUserConversions=*/false,
1933 /*AllowExplicit=*/false,
1934 /*ForceRValue=*/false,
1935 &ICS))
Sebastian Redl1a99f442009-04-16 17:51:27 +00001936 {
John McCall0d1da222010-01-12 00:44:57 +00001937 assert((ICS.isStandard() || ICS.isUserDefined()) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00001938 "expected a definite conversion");
1939 bool DirectBinding =
John McCall0d1da222010-01-12 00:44:57 +00001940 ICS.isStandard() ? ICS.Standard.DirectBinding
1941 : ICS.UserDefined.After.DirectBinding;
Sebastian Redl1a99f442009-04-16 17:51:27 +00001942 if (DirectBinding)
1943 return false;
1944 }
1945 }
John McCall65eb8792010-02-25 01:37:24 +00001946
Sebastian Redl1a99f442009-04-16 17:51:27 +00001947 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1948 // -- if E1 and E2 have class type, and the underlying class types are
1949 // the same or one is a base class of the other:
1950 QualType FTy = From->getType();
1951 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001952 const RecordType *FRec = FTy->getAs<RecordType>();
1953 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl1a99f442009-04-16 17:51:27 +00001954 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1955 if (FRec && TRec && (FRec == TRec ||
1956 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1957 // E1 can be converted to match E2 if the class of T2 is the
1958 // same type as, or a base class of, the class of T1, and
1959 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00001960 if (FRec == TRec || FDerivedFromT) {
1961 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
1962 // Could still fail if there's no copy constructor.
1963 // FIXME: Is this a hard error then, or just a conversion failure? The
1964 // standard doesn't say.
1965 ICS = Self.TryCopyInitialization(From, TTy,
1966 /*SuppressUserConversions=*/false,
1967 /*ForceRValue=*/false,
1968 /*InOverloadResolution=*/false);
1969 } else {
1970 ICS.setBad(BadConversionSequence::bad_qualifiers, From, TTy);
1971 }
1972 } else {
1973 // Can't implicitly convert FTy to a derived class TTy.
1974 // TODO: more specific error for this.
1975 ICS.setBad(BadConversionSequence::no_conversion, From, TTy);
Sebastian Redl1a99f442009-04-16 17:51:27 +00001976 }
1977 } else {
1978 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1979 // implicitly converted to the type that expression E2 would have
1980 // if E2 were converted to an rvalue.
1981 // First find the decayed type.
1982 if (TTy->isFunctionType())
1983 TTy = Self.Context.getPointerType(TTy);
Mike Stump11289f42009-09-09 15:08:12 +00001984 else if (TTy->isArrayType())
Sebastian Redl1a99f442009-04-16 17:51:27 +00001985 TTy = Self.Context.getArrayDecayedType(TTy);
1986
1987 // Now try the implicit conversion.
1988 // FIXME: This doesn't detect ambiguities.
Anders Carlssonef4c7212009-08-27 17:24:15 +00001989 ICS = Self.TryImplicitConversion(From, TTy,
1990 /*SuppressUserConversions=*/false,
1991 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00001992 /*ForceRValue=*/false,
1993 /*InOverloadResolution=*/false);
Sebastian Redl1a99f442009-04-16 17:51:27 +00001994 }
1995 return false;
1996}
1997
1998/// \brief Try to find a common type for two according to C++0x 5.16p5.
1999///
2000/// This is part of the parameter validation for the ? operator. If either
2001/// value operand is a class type, overload resolution is used to find a
2002/// conversion to a common type.
2003static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2004 SourceLocation Loc) {
2005 Expr *Args[2] = { LHS, RHS };
John McCallbc077cf2010-02-08 23:07:23 +00002006 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002007 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002008
2009 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00002010 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002011 case OR_Success:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002012 // We found a match. Perform the conversions on the arguments and move on.
2013 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002014 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00002015 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002016 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002017 break;
2018 return false;
2019
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002020 case OR_No_Viable_Function:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002021 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2022 << LHS->getType() << RHS->getType()
2023 << LHS->getSourceRange() << RHS->getSourceRange();
2024 return true;
2025
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002026 case OR_Ambiguous:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002027 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2028 << LHS->getType() << RHS->getType()
2029 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00002030 // FIXME: Print the possible common types by printing the return types of
2031 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00002032 break;
2033
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002034 case OR_Deleted:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002035 assert(false && "Conditional operator has only built-in overloads");
2036 break;
2037 }
2038 return true;
2039}
2040
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002041/// \brief Perform an "extended" implicit conversion as returned by
2042/// TryClassUnification.
2043///
2044/// TryClassUnification generates ICSs that include reference bindings.
2045/// PerformImplicitConversion is not suitable for this; it chokes if the
2046/// second part of a standard conversion is ICK_DerivedToBase. This function
2047/// handles the reference binding specially.
2048static bool ConvertForConditional(Sema &Self, Expr *&E,
Mike Stump11289f42009-09-09 15:08:12 +00002049 const ImplicitConversionSequence &ICS) {
John McCall0d1da222010-01-12 00:44:57 +00002050 if (ICS.isStandard() && ICS.Standard.ReferenceBinding) {
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002051 assert(ICS.Standard.DirectBinding &&
2052 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redlf79d3972009-04-26 11:21:02 +00002053 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
2054 // redoing all the work.
2055 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson271e3a42009-08-27 17:30:43 +00002056 TargetType(ICS)),
Douglas Gregorc809cc22009-09-23 23:04:10 +00002057 /*FIXME:*/E->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002058 /*SuppressUserConversions=*/false,
2059 /*AllowExplicit=*/false,
2060 /*ForceRValue=*/false);
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002061 }
John McCall0d1da222010-01-12 00:44:57 +00002062 if (ICS.isUserDefined() && ICS.UserDefined.After.ReferenceBinding) {
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002063 assert(ICS.UserDefined.After.DirectBinding &&
2064 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redlf79d3972009-04-26 11:21:02 +00002065 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson271e3a42009-08-27 17:30:43 +00002066 TargetType(ICS)),
Douglas Gregorc809cc22009-09-23 23:04:10 +00002067 /*FIXME:*/E->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002068 /*SuppressUserConversions=*/false,
2069 /*AllowExplicit=*/false,
2070 /*ForceRValue=*/false);
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002071 }
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002072 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, Sema::AA_Converting))
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002073 return true;
2074 return false;
2075}
2076
Sebastian Redl1a99f442009-04-16 17:51:27 +00002077/// \brief Check the operands of ?: under C++ semantics.
2078///
2079/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2080/// extension. In this case, LHS == Cond. (But they're not aliases.)
2081QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2082 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00002083 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2084 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00002085
2086 // C++0x 5.16p1
2087 // The first expression is contextually converted to bool.
2088 if (!Cond->isTypeDependent()) {
2089 if (CheckCXXBooleanCondition(Cond))
2090 return QualType();
2091 }
2092
2093 // Either of the arguments dependent?
2094 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2095 return Context.DependentTy;
2096
John McCall71d8d9b2010-03-11 19:43:18 +00002097 CheckSignCompare(LHS, RHS, QuestionLoc);
John McCall1fa36b72009-11-05 09:23:39 +00002098
Sebastian Redl1a99f442009-04-16 17:51:27 +00002099 // C++0x 5.16p2
2100 // If either the second or the third operand has type (cv) void, ...
2101 QualType LTy = LHS->getType();
2102 QualType RTy = RHS->getType();
2103 bool LVoid = LTy->isVoidType();
2104 bool RVoid = RTy->isVoidType();
2105 if (LVoid || RVoid) {
2106 // ... then the [l2r] conversions are performed on the second and third
2107 // operands ...
Douglas Gregorb92a1562010-02-03 00:27:59 +00002108 DefaultFunctionArrayLvalueConversion(LHS);
2109 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002110 LTy = LHS->getType();
2111 RTy = RHS->getType();
2112
2113 // ... and one of the following shall hold:
2114 // -- The second or the third operand (but not both) is a throw-
2115 // expression; the result is of the type of the other and is an rvalue.
2116 bool LThrow = isa<CXXThrowExpr>(LHS);
2117 bool RThrow = isa<CXXThrowExpr>(RHS);
2118 if (LThrow && !RThrow)
2119 return RTy;
2120 if (RThrow && !LThrow)
2121 return LTy;
2122
2123 // -- Both the second and third operands have type void; the result is of
2124 // type void and is an rvalue.
2125 if (LVoid && RVoid)
2126 return Context.VoidTy;
2127
2128 // Neither holds, error.
2129 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2130 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2131 << LHS->getSourceRange() << RHS->getSourceRange();
2132 return QualType();
2133 }
2134
2135 // Neither is void.
2136
2137 // C++0x 5.16p3
2138 // Otherwise, if the second and third operand have different types, and
2139 // either has (cv) class type, and attempt is made to convert each of those
2140 // operands to the other.
2141 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
2142 (LTy->isRecordType() || RTy->isRecordType())) {
2143 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2144 // These return true if a single direction is already ambiguous.
2145 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
2146 return QualType();
2147 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
2148 return QualType();
2149
John McCall0d1da222010-01-12 00:44:57 +00002150 bool HaveL2R = !ICSLeftToRight.isBad();
2151 bool HaveR2L = !ICSRightToLeft.isBad();
Sebastian Redl1a99f442009-04-16 17:51:27 +00002152 // If both can be converted, [...] the program is ill-formed.
2153 if (HaveL2R && HaveR2L) {
2154 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2155 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2156 return QualType();
2157 }
2158
2159 // If exactly one conversion is possible, that conversion is applied to
2160 // the chosen operand and the converted operands are used in place of the
2161 // original operands for the remainder of this section.
2162 if (HaveL2R) {
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002163 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002164 return QualType();
2165 LTy = LHS->getType();
2166 } else if (HaveR2L) {
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002167 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002168 return QualType();
2169 RTy = RHS->getType();
2170 }
2171 }
2172
2173 // C++0x 5.16p4
2174 // If the second and third operands are lvalues and have the same type,
2175 // the result is of that type [...]
2176 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
2177 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
2178 RHS->isLvalue(Context) == Expr::LV_Valid)
2179 return LTy;
2180
2181 // C++0x 5.16p5
2182 // Otherwise, the result is an rvalue. If the second and third operands
2183 // do not have the same type, and either has (cv) class type, ...
2184 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2185 // ... overload resolution is used to determine the conversions (if any)
2186 // to be applied to the operands. If the overload resolution fails, the
2187 // program is ill-formed.
2188 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2189 return QualType();
2190 }
2191
2192 // C++0x 5.16p6
2193 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2194 // conversions are performed on the second and third operands.
Douglas Gregorb92a1562010-02-03 00:27:59 +00002195 DefaultFunctionArrayLvalueConversion(LHS);
2196 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002197 LTy = LHS->getType();
2198 RTy = RHS->getType();
2199
2200 // After those conversions, one of the following shall hold:
2201 // -- The second and third operands have the same type; the result
2202 // is of that type.
2203 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
2204 return LTy;
2205
2206 // -- The second and third operands have arithmetic or enumeration type;
2207 // the usual arithmetic conversions are performed to bring them to a
2208 // common type, and the result is of that type.
2209 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2210 UsualArithmeticConversions(LHS, RHS);
2211 return LHS->getType();
2212 }
2213
2214 // -- The second and third operands have pointer type, or one has pointer
2215 // type and the other is a null pointer constant; pointer conversions
2216 // and qualification conversions are performed to bring them to their
2217 // composite pointer type. The result is of the composite pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00002218 // -- The second and third operands have pointer to member type, or one has
2219 // pointer to member type and the other is a null pointer constant;
2220 // pointer to member conversions and qualification conversions are
2221 // performed to bring them to a common type, whose cv-qualification
2222 // shall match the cv-qualification of either the second or the third
2223 // operand. The result is of the common type.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002224 bool NonStandardCompositeType = false;
2225 QualType Composite = FindCompositePointerType(LHS, RHS,
2226 isSFINAEContext()? 0 : &NonStandardCompositeType);
2227 if (!Composite.isNull()) {
2228 if (NonStandardCompositeType)
2229 Diag(QuestionLoc,
2230 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2231 << LTy << RTy << Composite
2232 << LHS->getSourceRange() << RHS->getSourceRange();
2233
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002234 return Composite;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002235 }
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00002236
2237 // Similarly, attempt to find composite type of twp objective-c pointers.
2238 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2239 if (!Composite.isNull())
2240 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00002241
Sebastian Redl1a99f442009-04-16 17:51:27 +00002242 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2243 << LHS->getType() << RHS->getType()
2244 << LHS->getSourceRange() << RHS->getSourceRange();
2245 return QualType();
2246}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002247
2248/// \brief Find a merged pointer type and convert the two expressions to it.
2249///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002250/// This finds the composite pointer type (or member pointer type) for @p E1
2251/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2252/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002253/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002254///
2255/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2256/// a non-standard (but still sane) composite type to which both expressions
2257/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2258/// will be set true.
2259QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2,
2260 bool *NonStandardCompositeType) {
2261 if (NonStandardCompositeType)
2262 *NonStandardCompositeType = false;
2263
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002264 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2265 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002266
Fariborz Jahanian33e148f2009-12-08 20:04:24 +00002267 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2268 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002269 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002270
2271 // C++0x 5.9p2
2272 // Pointer conversions and qualification conversions are performed on
2273 // pointer operands to bring them to their composite pointer type. If
2274 // one operand is a null pointer constant, the composite pointer type is
2275 // the type of the other operand.
Douglas Gregor56751b52009-09-25 04:25:58 +00002276 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002277 if (T2->isMemberPointerType())
2278 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
2279 else
2280 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002281 return T2;
2282 }
Douglas Gregor56751b52009-09-25 04:25:58 +00002283 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002284 if (T1->isMemberPointerType())
2285 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
2286 else
2287 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002288 return T1;
2289 }
Mike Stump11289f42009-09-09 15:08:12 +00002290
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002291 // Now both have to be pointers or member pointers.
Sebastian Redl658262f2009-11-16 21:03:45 +00002292 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2293 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002294 return QualType();
2295
2296 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2297 // the other has type "pointer to cv2 T" and the composite pointer type is
2298 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2299 // Otherwise, the composite pointer type is a pointer type similar to the
2300 // type of one of the operands, with a cv-qualification signature that is
2301 // the union of the cv-qualification signatures of the operand types.
2302 // In practice, the first part here is redundant; it's subsumed by the second.
2303 // What we do here is, we build the two possible composite types, and try the
2304 // conversions in both directions. If only one works, or if the two composite
2305 // types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00002306 // FIXME: extended qualifiers?
Sebastian Redl658262f2009-11-16 21:03:45 +00002307 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2308 QualifierVector QualifierUnion;
2309 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2310 ContainingClassVector;
2311 ContainingClassVector MemberOfClass;
2312 QualType Composite1 = Context.getCanonicalType(T1),
2313 Composite2 = Context.getCanonicalType(T2);
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002314 unsigned NeedConstBefore = 0;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002315 do {
2316 const PointerType *Ptr1, *Ptr2;
2317 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2318 (Ptr2 = Composite2->getAs<PointerType>())) {
2319 Composite1 = Ptr1->getPointeeType();
2320 Composite2 = Ptr2->getPointeeType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002321
2322 // If we're allowed to create a non-standard composite type, keep track
2323 // of where we need to fill in additional 'const' qualifiers.
2324 if (NonStandardCompositeType &&
2325 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2326 NeedConstBefore = QualifierUnion.size();
2327
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002328 QualifierUnion.push_back(
2329 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2330 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2331 continue;
2332 }
Mike Stump11289f42009-09-09 15:08:12 +00002333
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002334 const MemberPointerType *MemPtr1, *MemPtr2;
2335 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2336 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2337 Composite1 = MemPtr1->getPointeeType();
2338 Composite2 = MemPtr2->getPointeeType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002339
2340 // If we're allowed to create a non-standard composite type, keep track
2341 // of where we need to fill in additional 'const' qualifiers.
2342 if (NonStandardCompositeType &&
2343 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2344 NeedConstBefore = QualifierUnion.size();
2345
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002346 QualifierUnion.push_back(
2347 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2348 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2349 MemPtr2->getClass()));
2350 continue;
2351 }
Mike Stump11289f42009-09-09 15:08:12 +00002352
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002353 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00002354
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002355 // Cannot unwrap any more types.
2356 break;
2357 } while (true);
Mike Stump11289f42009-09-09 15:08:12 +00002358
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002359 if (NeedConstBefore && NonStandardCompositeType) {
2360 // Extension: Add 'const' to qualifiers that come before the first qualifier
2361 // mismatch, so that our (non-standard!) composite type meets the
2362 // requirements of C++ [conv.qual]p4 bullet 3.
2363 for (unsigned I = 0; I != NeedConstBefore; ++I) {
2364 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
2365 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
2366 *NonStandardCompositeType = true;
2367 }
2368 }
2369 }
2370
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002371 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redl658262f2009-11-16 21:03:45 +00002372 ContainingClassVector::reverse_iterator MOC
2373 = MemberOfClass.rbegin();
2374 for (QualifierVector::reverse_iterator
2375 I = QualifierUnion.rbegin(),
2376 E = QualifierUnion.rend();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002377 I != E; (void)++I, ++MOC) {
John McCall8ccfcb52009-09-24 19:53:00 +00002378 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002379 if (MOC->first && MOC->second) {
2380 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00002381 Composite1 = Context.getMemberPointerType(
2382 Context.getQualifiedType(Composite1, Quals),
2383 MOC->first);
2384 Composite2 = Context.getMemberPointerType(
2385 Context.getQualifiedType(Composite2, Quals),
2386 MOC->second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002387 } else {
2388 // Rebuild pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00002389 Composite1
2390 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2391 Composite2
2392 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002393 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002394 }
2395
Mike Stump11289f42009-09-09 15:08:12 +00002396 ImplicitConversionSequence E1ToC1 =
Anders Carlssonef4c7212009-08-27 17:24:15 +00002397 TryImplicitConversion(E1, Composite1,
2398 /*SuppressUserConversions=*/false,
2399 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00002400 /*ForceRValue=*/false,
2401 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002402 ImplicitConversionSequence E2ToC1 =
Anders Carlssonef4c7212009-08-27 17:24:15 +00002403 TryImplicitConversion(E2, Composite1,
2404 /*SuppressUserConversions=*/false,
2405 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00002406 /*ForceRValue=*/false,
2407 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002408
John McCall65eb8792010-02-25 01:37:24 +00002409 bool ToC2Viable = false;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002410 ImplicitConversionSequence E1ToC2, E2ToC2;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002411 if (Context.getCanonicalType(Composite1) !=
2412 Context.getCanonicalType(Composite2)) {
Anders Carlssonef4c7212009-08-27 17:24:15 +00002413 E1ToC2 = TryImplicitConversion(E1, Composite2,
2414 /*SuppressUserConversions=*/false,
2415 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00002416 /*ForceRValue=*/false,
2417 /*InOverloadResolution=*/false);
Anders Carlssonef4c7212009-08-27 17:24:15 +00002418 E2ToC2 = TryImplicitConversion(E2, Composite2,
2419 /*SuppressUserConversions=*/false,
2420 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00002421 /*ForceRValue=*/false,
2422 /*InOverloadResolution=*/false);
John McCall65eb8792010-02-25 01:37:24 +00002423 ToC2Viable = !E1ToC2.isBad() && !E2ToC2.isBad();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002424 }
2425
John McCall0d1da222010-01-12 00:44:57 +00002426 bool ToC1Viable = !E1ToC1.isBad() && !E2ToC1.isBad();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002427 if (ToC1Viable && !ToC2Viable) {
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002428 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, Sema::AA_Converting) &&
2429 !PerformImplicitConversion(E2, Composite1, E2ToC1, Sema::AA_Converting))
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002430 return Composite1;
2431 }
2432 if (ToC2Viable && !ToC1Viable) {
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002433 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, Sema::AA_Converting) &&
2434 !PerformImplicitConversion(E2, Composite2, E2ToC2, Sema::AA_Converting))
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002435 return Composite2;
2436 }
2437 return QualType();
2438}
Anders Carlsson85a307d2009-05-17 18:41:29 +00002439
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002440Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlssonf86a8d12009-08-15 23:41:35 +00002441 if (!Context.getLangOptions().CPlusPlus)
2442 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00002443
Douglas Gregor363b1512009-12-24 18:51:59 +00002444 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2445
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002446 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002447 if (!RT)
2448 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00002449
John McCall67da35c2010-02-04 22:26:26 +00002450 // If this is the result of a call expression, our source might
2451 // actually be a reference, in which case we shouldn't bind.
Anders Carlssonaedb46f2009-09-14 01:30:44 +00002452 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2453 QualType Ty = CE->getCallee()->getType();
2454 if (const PointerType *PT = Ty->getAs<PointerType>())
2455 Ty = PT->getPointeeType();
Fariborz Jahanianffcfecd2010-02-18 20:31:02 +00002456 else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>())
2457 Ty = BPT->getPointeeType();
2458
John McCall9dd450b2009-09-21 23:43:11 +00002459 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlssonaedb46f2009-09-14 01:30:44 +00002460 if (FTy->getResultType()->isReferenceType())
2461 return Owned(E);
2462 }
John McCall67da35c2010-02-04 22:26:26 +00002463
2464 // That should be enough to guarantee that this type is complete.
2465 // If it has a trivial destructor, we can avoid the extra copy.
2466 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2467 if (RD->hasTrivialDestructor())
2468 return Owned(E);
2469
Mike Stump11289f42009-09-09 15:08:12 +00002470 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002471 RD->getDestructor(Context));
Anders Carlssonc78576e2009-05-30 21:21:49 +00002472 ExprTemporaries.push_back(Temp);
Fariborz Jahanian67828442009-08-03 19:13:25 +00002473 if (CXXDestructorDecl *Destructor =
2474 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
2475 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002476 // FIXME: Add the temporary to the temporaries vector.
2477 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2478}
2479
Anders Carlsson6e997b22009-12-15 20:51:39 +00002480Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002481 assert(SubExpr && "sub expression can't be null!");
Mike Stump11289f42009-09-09 15:08:12 +00002482
Douglas Gregor580cd4a2009-12-03 17:10:37 +00002483 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2484 assert(ExprTemporaries.size() >= FirstTemporary);
2485 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002486 return SubExpr;
Mike Stump11289f42009-09-09 15:08:12 +00002487
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002488 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor580cd4a2009-12-03 17:10:37 +00002489 &ExprTemporaries[FirstTemporary],
Anders Carlsson6e997b22009-12-15 20:51:39 +00002490 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor580cd4a2009-12-03 17:10:37 +00002491 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2492 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00002493
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002494 return E;
2495}
2496
Douglas Gregorb6ea6082009-12-22 22:17:25 +00002497Sema::OwningExprResult
2498Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2499 if (SubExpr.isInvalid())
2500 return ExprError();
2501
2502 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2503}
2504
Anders Carlssonafb2dad2009-12-16 02:09:40 +00002505FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2506 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2507 assert(ExprTemporaries.size() >= FirstTemporary);
2508
2509 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2510 CXXTemporary **Temporaries =
2511 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2512
2513 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2514
2515 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2516 ExprTemporaries.end());
2517
2518 return E;
2519}
2520
Mike Stump11289f42009-09-09 15:08:12 +00002521Sema::OwningExprResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002522Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
Douglas Gregore610ada2010-02-24 18:44:31 +00002523 tok::TokenKind OpKind, TypeTy *&ObjectType,
2524 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002525 // Since this might be a postfix expression, get rid of ParenListExprs.
2526 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump11289f42009-09-09 15:08:12 +00002527
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002528 Expr *BaseExpr = (Expr*)Base.get();
2529 assert(BaseExpr && "no record expansion");
Mike Stump11289f42009-09-09 15:08:12 +00002530
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002531 QualType BaseType = BaseExpr->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00002532 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002533 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00002534 // If we have a pointer to a dependent type and are using the -> operator,
2535 // the object type is the type that the pointer points to. We might still
2536 // have enough information about that type to do something useful.
2537 if (OpKind == tok::arrow)
2538 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2539 BaseType = Ptr->getPointeeType();
2540
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002541 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregore610ada2010-02-24 18:44:31 +00002542 MayBePseudoDestructor = true;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002543 return move(Base);
2544 }
Mike Stump11289f42009-09-09 15:08:12 +00002545
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002546 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00002547 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002548 // returned, with the original second operand.
2549 if (OpKind == tok::arrow) {
John McCallc1538c02009-09-30 01:01:30 +00002550 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00002551 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002552 llvm::SmallVector<SourceLocation, 8> Locations;
John McCallbd0465b2009-09-30 01:30:54 +00002553 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc1538c02009-09-30 01:01:30 +00002554
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002555 while (BaseType->isRecordType()) {
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00002556 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002557 BaseExpr = (Expr*)Base.get();
2558 if (BaseExpr == NULL)
2559 return ExprError();
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002560 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonfbd2d492009-10-13 22:55:59 +00002561 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc1538c02009-09-30 01:01:30 +00002562 BaseType = BaseExpr->getType();
2563 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCallbd0465b2009-09-30 01:30:54 +00002564 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00002565 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002566 for (unsigned i = 0; i < Locations.size(); i++)
2567 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00002568 return ExprError();
2569 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002570 }
Mike Stump11289f42009-09-09 15:08:12 +00002571
Douglas Gregore4f764f2009-11-20 19:58:21 +00002572 if (BaseType->isPointerType())
2573 BaseType = BaseType->getPointeeType();
2574 }
Mike Stump11289f42009-09-09 15:08:12 +00002575
2576 // We could end up with various non-record types here, such as extended
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002577 // vector types or Objective-C interfaces. Just return early and let
2578 // ActOnMemberReferenceExpr do the work.
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002579 if (!BaseType->isRecordType()) {
2580 // C++ [basic.lookup.classref]p2:
2581 // [...] If the type of the object expression is of pointer to scalar
2582 // type, the unqualified-id is looked up in the context of the complete
2583 // postfix-expression.
Douglas Gregore610ada2010-02-24 18:44:31 +00002584 //
2585 // This also indicates that we should be parsing a
2586 // pseudo-destructor-name.
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002587 ObjectType = 0;
Douglas Gregore610ada2010-02-24 18:44:31 +00002588 MayBePseudoDestructor = true;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002589 return move(Base);
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002590 }
Mike Stump11289f42009-09-09 15:08:12 +00002591
Douglas Gregor3fad6172009-11-17 05:17:33 +00002592 // The object type must be complete (or dependent).
2593 if (!BaseType->isDependentType() &&
2594 RequireCompleteType(OpLoc, BaseType,
2595 PDiag(diag::err_incomplete_member_access)))
2596 return ExprError();
2597
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002598 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002599 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00002600 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002601 // type C (or of pointer to a class type C), the unqualified-id is looked
2602 // up in the scope of class C. [...]
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002603 ObjectType = BaseType.getAsOpaquePtr();
Mike Stump11289f42009-09-09 15:08:12 +00002604 return move(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002605}
2606
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002607Sema::OwningExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
2608 ExprArg MemExpr) {
2609 Expr *E = (Expr *) MemExpr.get();
2610 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
2611 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2612 << isa<CXXPseudoDestructorExpr>(E)
2613 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
2614
2615 return ActOnCallExpr(/*Scope*/ 0,
2616 move(MemExpr),
2617 /*LPLoc*/ ExpectedLParenLoc,
2618 Sema::MultiExprArg(*this, 0, 0),
2619 /*CommaLocs*/ 0,
2620 /*RPLoc*/ ExpectedLParenLoc);
2621}
Douglas Gregore610ada2010-02-24 18:44:31 +00002622
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002623Sema::OwningExprResult Sema::BuildPseudoDestructorExpr(ExprArg Base,
2624 SourceLocation OpLoc,
2625 tok::TokenKind OpKind,
2626 const CXXScopeSpec &SS,
Douglas Gregor651fe5e2010-02-24 23:40:28 +00002627 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002628 SourceLocation CCLoc,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00002629 SourceLocation TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002630 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002631 bool HasTrailingLParen) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00002632 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002633
2634 // C++ [expr.pseudo]p2:
2635 // The left-hand side of the dot operator shall be of scalar type. The
2636 // left-hand side of the arrow operator shall be of pointer to scalar type.
2637 // This scalar type is the object type.
2638 Expr *BaseE = (Expr *)Base.get();
2639 QualType ObjectType = BaseE->getType();
2640 if (OpKind == tok::arrow) {
2641 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2642 ObjectType = Ptr->getPointeeType();
2643 } else if (!BaseE->isTypeDependent()) {
2644 // The user wrote "p->" when she probably meant "p."; fix it.
2645 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2646 << ObjectType << true
2647 << CodeModificationHint::CreateReplacement(OpLoc, ".");
2648 if (isSFINAEContext())
2649 return ExprError();
2650
2651 OpKind = tok::period;
2652 }
2653 }
2654
2655 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
2656 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2657 << ObjectType << BaseE->getSourceRange();
2658 return ExprError();
2659 }
2660
2661 // C++ [expr.pseudo]p2:
2662 // [...] The cv-unqualified versions of the object type and of the type
2663 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00002664 if (DestructedTypeInfo) {
2665 QualType DestructedType = DestructedTypeInfo->getType();
2666 SourceLocation DestructedTypeStart
2667 = DestructedTypeInfo->getTypeLoc().getSourceRange().getBegin();
2668 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
2669 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
2670 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
2671 << ObjectType << DestructedType << BaseE->getSourceRange()
2672 << DestructedTypeInfo->getTypeLoc().getSourceRange();
2673
2674 // Recover by setting the destructed type to the object type.
2675 DestructedType = ObjectType;
2676 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
2677 DestructedTypeStart);
2678 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2679 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002680 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00002681
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002682 // C++ [expr.pseudo]p2:
2683 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
2684 // form
2685 //
2686 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
2687 //
2688 // shall designate the same scalar type.
2689 if (ScopeTypeInfo) {
2690 QualType ScopeType = ScopeTypeInfo->getType();
2691 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
2692 !Context.hasSameType(ScopeType, ObjectType)) {
2693
2694 Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(),
2695 diag::err_pseudo_dtor_type_mismatch)
2696 << ObjectType << ScopeType << BaseE->getSourceRange()
2697 << ScopeTypeInfo->getTypeLoc().getSourceRange();
2698
2699 ScopeType = QualType();
2700 ScopeTypeInfo = 0;
2701 }
2702 }
2703
2704 OwningExprResult Result
2705 = Owned(new (Context) CXXPseudoDestructorExpr(Context,
2706 Base.takeAs<Expr>(),
2707 OpKind == tok::arrow,
2708 OpLoc,
2709 (NestedNameSpecifier *) SS.getScopeRep(),
2710 SS.getRange(),
2711 ScopeTypeInfo,
2712 CCLoc,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00002713 TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002714 Destructed));
2715
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002716 if (HasTrailingLParen)
2717 return move(Result);
2718
Douglas Gregor678f90d2010-02-25 01:56:36 +00002719 return DiagnoseDtorReference(Destructed.getLocation(), move(Result));
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002720}
2721
2722Sema::OwningExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, ExprArg Base,
2723 SourceLocation OpLoc,
2724 tok::TokenKind OpKind,
2725 const CXXScopeSpec &SS,
2726 UnqualifiedId &FirstTypeName,
2727 SourceLocation CCLoc,
2728 SourceLocation TildeLoc,
2729 UnqualifiedId &SecondTypeName,
2730 bool HasTrailingLParen) {
2731 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2732 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2733 "Invalid first type name in pseudo-destructor");
2734 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2735 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2736 "Invalid second type name in pseudo-destructor");
2737
2738 Expr *BaseE = (Expr *)Base.get();
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002739
2740 // C++ [expr.pseudo]p2:
2741 // The left-hand side of the dot operator shall be of scalar type. The
2742 // left-hand side of the arrow operator shall be of pointer to scalar type.
2743 // This scalar type is the object type.
2744 QualType ObjectType = BaseE->getType();
2745 if (OpKind == tok::arrow) {
2746 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2747 ObjectType = Ptr->getPointeeType();
Douglas Gregor678f90d2010-02-25 01:56:36 +00002748 } else if (!ObjectType->isDependentType()) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002749 // The user wrote "p->" when she probably meant "p."; fix it.
2750 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregor678f90d2010-02-25 01:56:36 +00002751 << ObjectType << true
2752 << CodeModificationHint::CreateReplacement(OpLoc, ".");
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002753 if (isSFINAEContext())
2754 return ExprError();
2755
2756 OpKind = tok::period;
2757 }
2758 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00002759
2760 // Compute the object type that we should use for name lookup purposes. Only
2761 // record types and dependent types matter.
2762 void *ObjectTypePtrForLookup = 0;
2763 if (!SS.isSet()) {
2764 ObjectTypePtrForLookup = (void *)ObjectType->getAs<RecordType>();
2765 if (!ObjectTypePtrForLookup && ObjectType->isDependentType())
2766 ObjectTypePtrForLookup = Context.DependentTy.getAsOpaquePtr();
2767 }
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002768
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002769 // Convert the name of the type being destructed (following the ~) into a
2770 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002771 QualType DestructedType;
2772 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregor678f90d2010-02-25 01:56:36 +00002773 PseudoDestructorTypeStorage Destructed;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002774 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2775 TypeTy *T = getTypeName(*SecondTypeName.Identifier,
2776 SecondTypeName.StartLocation,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002777 S, &SS, true, ObjectTypePtrForLookup);
2778 if (!T &&
2779 ((SS.isSet() && !computeDeclContext(SS, false)) ||
2780 (!SS.isSet() && ObjectType->isDependentType()))) {
2781 // The name of the type being destroyed is a dependent name, and we
2782 // couldn't find anything useful in scope. Just store the identifier and
2783 // it's location, and we'll perform (qualified) name lookup again at
2784 // template instantiation time.
2785 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
2786 SecondTypeName.StartLocation);
2787 } else if (!T) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002788 Diag(SecondTypeName.StartLocation,
2789 diag::err_pseudo_dtor_destructor_non_type)
2790 << SecondTypeName.Identifier << ObjectType;
2791 if (isSFINAEContext())
2792 return ExprError();
2793
2794 // Recover by assuming we had the right type all along.
2795 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002796 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002797 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002798 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002799 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002800 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002801 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2802 TemplateId->getTemplateArgs(),
2803 TemplateId->NumArgs);
2804 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2805 TemplateId->TemplateNameLoc,
2806 TemplateId->LAngleLoc,
2807 TemplateArgsPtr,
2808 TemplateId->RAngleLoc);
2809 if (T.isInvalid() || !T.get()) {
2810 // Recover by assuming we had the right type all along.
2811 DestructedType = ObjectType;
2812 } else
2813 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002814 }
2815
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002816 // If we've performed some kind of recovery, (re-)build the type source
2817 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00002818 if (!DestructedType.isNull()) {
2819 if (!DestructedTypeInfo)
2820 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002821 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00002822 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2823 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002824
2825 // Convert the name of the scope type (the type prior to '::') into a type.
2826 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002827 QualType ScopeType;
2828 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2829 FirstTypeName.Identifier) {
2830 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2831 TypeTy *T = getTypeName(*FirstTypeName.Identifier,
2832 FirstTypeName.StartLocation,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002833 S, &SS, false, ObjectTypePtrForLookup);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002834 if (!T) {
2835 Diag(FirstTypeName.StartLocation,
2836 diag::err_pseudo_dtor_destructor_non_type)
2837 << FirstTypeName.Identifier << ObjectType;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002838
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002839 if (isSFINAEContext())
2840 return ExprError();
2841
2842 // Just drop this type. It's unnecessary anyway.
2843 ScopeType = QualType();
2844 } else
2845 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002846 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002847 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002848 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002849 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2850 TemplateId->getTemplateArgs(),
2851 TemplateId->NumArgs);
2852 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2853 TemplateId->TemplateNameLoc,
2854 TemplateId->LAngleLoc,
2855 TemplateArgsPtr,
2856 TemplateId->RAngleLoc);
2857 if (T.isInvalid() || !T.get()) {
2858 // Recover by dropping this type.
2859 ScopeType = QualType();
2860 } else
2861 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002862 }
2863 }
Douglas Gregor90ad9222010-02-24 23:02:30 +00002864
2865 if (!ScopeType.isNull() && !ScopeTypeInfo)
2866 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
2867 FirstTypeName.StartLocation);
2868
2869
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002870 return BuildPseudoDestructorExpr(move(Base), OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00002871 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002872 Destructed, HasTrailingLParen);
Douglas Gregore610ada2010-02-24 18:44:31 +00002873}
2874
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00002875CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2876 CXXMethodDecl *Method) {
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002877 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0, Method))
Eli Friedmanf7195532009-12-09 04:53:56 +00002878 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
2879
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00002880 MemberExpr *ME =
2881 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2882 SourceLocation(), Method->getType());
Eli Friedmanf7195532009-12-09 04:53:56 +00002883 QualType ResultType = Method->getResultType().getNonReferenceType();
Douglas Gregor27381f32009-11-23 12:27:39 +00002884 MarkDeclarationReferenced(Exp->getLocStart(), Method);
2885 CXXMemberCallExpr *CE =
2886 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
2887 Exp->getLocEnd());
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00002888 return CE;
2889}
2890
Anders Carlssone9766d52009-09-09 21:33:21 +00002891Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2892 QualType Ty,
2893 CastExpr::CastKind Kind,
2894 CXXMethodDecl *Method,
2895 ExprArg Arg) {
2896 Expr *From = Arg.takeAs<Expr>();
2897
2898 switch (Kind) {
2899 default: assert(0 && "Unhandled cast kind!");
2900 case CastExpr::CK_ConstructorConversion: {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00002901 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2902
2903 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2904 MultiExprArg(*this, (void **)&From, 1),
2905 CastLoc, ConstructorArgs))
2906 return ExprError();
Anders Carlsson8f741bf2009-10-18 21:20:14 +00002907
2908 OwningExprResult Result =
2909 BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2910 move_arg(ConstructorArgs));
2911 if (Result.isInvalid())
2912 return ExprError();
2913
2914 return MaybeBindToTemporary(Result.takeAs<Expr>());
Anders Carlssone9766d52009-09-09 21:33:21 +00002915 }
2916
2917 case CastExpr::CK_UserDefinedConversion: {
Anders Carlsson6b2737d2009-09-15 07:42:44 +00002918 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
Eli Friedmanf7195532009-12-09 04:53:56 +00002919
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00002920 // Create an implicit call expr that calls it.
2921 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method);
Anders Carlsson8f741bf2009-10-18 21:20:14 +00002922 return MaybeBindToTemporary(CE);
Anders Carlssone9766d52009-09-09 21:33:21 +00002923 }
Anders Carlssone9766d52009-09-09 21:33:21 +00002924 }
2925}
2926
Anders Carlsson85a307d2009-05-17 18:41:29 +00002927Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2928 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002929 if (FullExpr)
Anders Carlsson6e997b22009-12-15 20:51:39 +00002930 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Anders Carlsson7e3f0e42009-08-25 23:46:41 +00002931
Anders Carlsson85a307d2009-05-17 18:41:29 +00002932 return Owned(FullExpr);
2933}