blob: f52bc8446733e5b7e81d5312d22a06935cd6fee7 [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,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +000032 Scope *S, CXXScopeSpec &SS,
Douglas Gregorfe17d252010-02-16 19:09:40 +000033 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
Douglas Gregore8154332010-04-15 18:05:39 +0000414 if (RequireNonAbstractType(ThrowLoc, E->getType(),
415 PDiag(diag::err_throw_abstract_type)
416 << E->getSourceRange()))
417 return true;
418
Rafael Espindola70e040d2010-03-02 21:28:26 +0000419 // FIXME: This is just a hack to mark the copy constructor referenced.
420 // This should go away when the next FIXME is fixed.
421 const RecordType *RT = Ty->getAs<RecordType>();
422 if (!RT)
423 return false;
424
425 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
426 if (RD->hasTrivialCopyConstructor())
427 return false;
428 CXXConstructorDecl *CopyCtor = RD->getCopyConstructor(Context, 0);
429 MarkDeclarationReferenced(ThrowLoc, CopyCtor);
Sebastian Redl4de47b42009-04-27 20:27:31 +0000430 }
431
432 // FIXME: Construct a temporary here.
433 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000434}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000435
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000436Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000437 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
438 /// is a non-lvalue expression whose value is the address of the object for
439 /// which the function is called.
440
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000441 if (!isa<FunctionDecl>(CurContext))
442 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000443
444 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
445 if (MD->isInstance())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000446 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregorb15af892010-01-07 23:12:05 +0000447 MD->getThisType(Context),
448 /*isImplicit=*/false));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000449
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000450 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000451}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000452
453/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
454/// Can be interpreted either as function-style casting ("int(x)")
455/// or class type construction ("ClassType(x,y,z)")
456/// or creation of a value-initialized type ("int()").
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000457Action::OwningExprResult
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000458Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
459 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000460 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000461 SourceLocation *CommaLocs,
462 SourceLocation RParenLoc) {
Douglas Gregor7df89f52010-02-05 19:11:37 +0000463 if (!TypeRep)
464 return ExprError();
465
John McCall97513962010-01-15 18:39:57 +0000466 TypeSourceInfo *TInfo;
467 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
468 if (!TInfo)
469 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000470 unsigned NumExprs = exprs.size();
471 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000472 SourceLocation TyBeginLoc = TypeRange.getBegin();
473 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
474
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000475 if (Ty->isDependentType() ||
Douglas Gregor0950e412009-03-13 21:01:28 +0000476 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000477 exprs.release();
Mike Stump11289f42009-09-09 15:08:12 +0000478
479 return Owned(CXXUnresolvedConstructExpr::Create(Context,
480 TypeRange.getBegin(), Ty,
Douglas Gregorce934142009-05-20 18:46:25 +0000481 LParenLoc,
482 Exprs, NumExprs,
483 RParenLoc));
Douglas Gregor0950e412009-03-13 21:01:28 +0000484 }
485
Anders Carlsson55243162009-08-27 03:53:50 +0000486 if (Ty->isArrayType())
487 return ExprError(Diag(TyBeginLoc,
488 diag::err_value_init_for_array_type) << FullRange);
489 if (!Ty->isVoidType() &&
490 RequireCompleteType(TyBeginLoc, Ty,
491 PDiag(diag::err_invalid_incomplete_type_use)
492 << FullRange))
493 return ExprError();
Fariborz Jahanian9a14b842009-10-23 21:01:39 +0000494
Anders Carlsson55243162009-08-27 03:53:50 +0000495 if (RequireNonAbstractType(TyBeginLoc, Ty,
496 diag::err_allocation_of_abstract_type))
497 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000498
499
Douglas Gregordd04d332009-01-16 18:33:17 +0000500 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000501 // If the expression list is a single expression, the type conversion
502 // expression is equivalent (in definedness, and if defined in meaning) to the
503 // corresponding cast expression.
504 //
505 if (NumExprs == 1) {
Anders Carlssonf10e4142009-08-07 22:21:05 +0000506 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000507 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, /*FunctionalStyle=*/true))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000508 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +0000509
510 exprs.release();
Anders Carlssone9766d52009-09-09 21:33:21 +0000511
512 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
John McCall97513962010-01-15 18:39:57 +0000513 TInfo, TyBeginLoc, Kind,
Anders Carlssone9766d52009-09-09 21:33:21 +0000514 Exprs[0], RParenLoc));
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000515 }
516
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000517 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregordd04d332009-01-16 18:33:17 +0000518 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000519
Mike Stump11289f42009-09-09 15:08:12 +0000520 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlsson574315a2009-08-27 05:08:22 +0000521 !Record->hasTrivialDestructor()) {
Eli Friedmana6824272010-01-31 20:58:15 +0000522 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
523 InitializationKind Kind
524 = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
525 LParenLoc, RParenLoc)
526 : InitializationKind::CreateValue(TypeRange.getBegin(),
527 LParenLoc, RParenLoc);
528 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
529 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
530 move(exprs));
Douglas Gregordd04d332009-01-16 18:33:17 +0000531
Eli Friedmana6824272010-01-31 20:58:15 +0000532 // FIXME: Improve AST representation?
533 return move(Result);
Douglas Gregordd04d332009-01-16 18:33:17 +0000534 }
535
536 // Fall through to value-initialize an object of class type that
537 // doesn't have a user-declared default constructor.
538 }
539
540 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000541 // If the expression list specifies more than a single value, the type shall
542 // be a class with a suitably declared constructor.
543 //
544 if (NumExprs > 1)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000545 return ExprError(Diag(CommaLocs[0],
546 diag::err_builtin_func_cast_more_than_one_arg)
547 << FullRange);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000548
549 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregordd04d332009-01-16 18:33:17 +0000550 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000551 // The expression T(), where T is a simple-type-specifier for a non-array
552 // complete object type or the (possibly cv-qualified) void type, creates an
553 // rvalue of the specified type, which is value-initialized.
554 //
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000555 exprs.release();
556 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000557}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000558
559
Sebastian Redlbd150f42008-11-21 19:14:01 +0000560/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
561/// @code new (memory) int[size][4] @endcode
562/// or
563/// @code ::new Foo(23, "hello") @endcode
564/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000565Action::OwningExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +0000566Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000567 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redlbd150f42008-11-21 19:14:01 +0000568 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redl351bb782008-12-02 14:43:59 +0000569 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000570 MultiExprArg ConstructorArgs,
Mike Stump11289f42009-09-09 15:08:12 +0000571 SourceLocation ConstructorRParen) {
Sebastian Redl351bb782008-12-02 14:43:59 +0000572 Expr *ArraySize = 0;
Sebastian Redl351bb782008-12-02 14:43:59 +0000573 // If the specified type is an array, unwrap it and save the expression.
574 if (D.getNumTypeObjects() > 0 &&
575 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
576 DeclaratorChunk &Chunk = D.getTypeObject(0);
577 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000578 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
579 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000580 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000581 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
582 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000583
584 if (ParenTypeId) {
585 // Can't have dynamic array size when the type-id is in parentheses.
586 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
587 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
588 !NumElts->isIntegerConstantExpr(Context)) {
589 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
590 << NumElts->getSourceRange();
591 return ExprError();
592 }
593 }
594
Sebastian Redl351bb782008-12-02 14:43:59 +0000595 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000596 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +0000597 }
598
Douglas Gregor73341c42009-09-11 00:18:58 +0000599 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000600 if (ArraySize) {
601 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +0000602 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
603 break;
604
605 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
606 if (Expr *NumElts = (Expr *)Array.NumElts) {
607 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
608 !NumElts->isIntegerConstantExpr(Context)) {
609 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
610 << NumElts->getSourceRange();
611 return ExprError();
612 }
613 }
614 }
615 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000616
John McCallbcd03502009-12-07 02:54:59 +0000617 //FIXME: Store TypeSourceInfo in CXXNew expression.
618 TypeSourceInfo *TInfo = 0;
619 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000620 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000621 return ExprError();
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000622
Mike Stump11289f42009-09-09 15:08:12 +0000623 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000624 PlacementLParen,
Mike Stump11289f42009-09-09 15:08:12 +0000625 move(PlacementArgs),
Douglas Gregord0fefba2009-05-21 00:00:09 +0000626 PlacementRParen,
627 ParenTypeId,
Mike Stump11289f42009-09-09 15:08:12 +0000628 AllocType,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000629 D.getSourceRange().getBegin(),
630 D.getSourceRange(),
631 Owned(ArraySize),
632 ConstructorLParen,
633 move(ConstructorArgs),
634 ConstructorRParen);
635}
636
Mike Stump11289f42009-09-09 15:08:12 +0000637Sema::OwningExprResult
Douglas Gregord0fefba2009-05-21 00:00:09 +0000638Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
639 SourceLocation PlacementLParen,
640 MultiExprArg PlacementArgs,
641 SourceLocation PlacementRParen,
Mike Stump11289f42009-09-09 15:08:12 +0000642 bool ParenTypeId,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000643 QualType AllocType,
644 SourceLocation TypeLoc,
645 SourceRange TypeRange,
646 ExprArg ArraySizeE,
647 SourceLocation ConstructorLParen,
648 MultiExprArg ConstructorArgs,
649 SourceLocation ConstructorRParen) {
650 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000651 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +0000652
Douglas Gregord0fefba2009-05-21 00:00:09 +0000653 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redlbd150f42008-11-21 19:14:01 +0000654
655 // That every array dimension except the first is constant was already
656 // checked by the type check above.
Sebastian Redl351bb782008-12-02 14:43:59 +0000657
Sebastian Redlbd150f42008-11-21 19:14:01 +0000658 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
659 // or enumeration type with a non-negative value."
Douglas Gregord0fefba2009-05-21 00:00:09 +0000660 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000661 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redl351bb782008-12-02 14:43:59 +0000662 QualType SizeType = ArraySize->getType();
663 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000664 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
665 diag::err_array_size_not_integral)
666 << SizeType << ArraySize->getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000667 // Let's see if this is a constant < 0. If so, we reject it out of hand.
668 // We don't care about special rules, so we tell the machinery it's not
669 // evaluated - it gives us a result in more cases.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000670 if (!ArraySize->isValueDependent()) {
671 llvm::APSInt Value;
672 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
673 if (Value < llvm::APSInt(
Anders Carlsson8ab20bb2009-09-23 00:37:25 +0000674 llvm::APInt::getNullValue(Value.getBitWidth()),
675 Value.isUnsigned()))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000676 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
677 diag::err_typecheck_negative_array_size)
678 << ArraySize->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000679 }
Sebastian Redl351bb782008-12-02 14:43:59 +0000680 }
Anders Carlsson8ab20bb2009-09-23 00:37:25 +0000681
Eli Friedman06ed2a52009-10-20 08:27:19 +0000682 ImpCastExprToType(ArraySize, Context.getSizeType(),
683 CastExpr::CK_IntegralCast);
Sebastian Redl351bb782008-12-02 14:43:59 +0000684 }
Sebastian Redlbd150f42008-11-21 19:14:01 +0000685
Sebastian Redlbd150f42008-11-21 19:14:01 +0000686 FunctionDecl *OperatorNew = 0;
687 FunctionDecl *OperatorDelete = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000688 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
689 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000690
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000691 if (!AllocType->isDependentType() &&
692 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
693 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000694 SourceRange(PlacementLParen, PlacementRParen),
695 UseGlobal, AllocType, ArraySize, PlaceArgs,
696 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000697 return ExprError();
Fariborz Jahanian835026e2009-11-24 18:29:37 +0000698 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000699 if (OperatorNew) {
700 // Add default arguments, if any.
701 const FunctionProtoType *Proto =
702 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +0000703 VariadicCallType CallType =
704 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Fariborz Jahanian835026e2009-11-24 18:29:37 +0000705 bool Invalid = GatherArgumentsForCall(PlacementLParen, OperatorNew,
706 Proto, 1, PlaceArgs, NumPlaceArgs,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +0000707 AllPlaceArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +0000708 if (Invalid)
709 return ExprError();
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000710
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000711 NumPlaceArgs = AllPlaceArgs.size();
712 if (NumPlaceArgs > 0)
713 PlaceArgs = &AllPlaceArgs[0];
714 }
715
Sebastian Redlbd150f42008-11-21 19:14:01 +0000716 bool Init = ConstructorLParen.isValid();
717 // --- Choosing a constructor ---
Sebastian Redlbd150f42008-11-21 19:14:01 +0000718 CXXConstructorDecl *Constructor = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000719 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
720 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmanfd8d4e12009-11-08 22:15:39 +0000721 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
722
Douglas Gregor85dabae2009-12-16 01:38:02 +0000723 if (!AllocType->isDependentType() &&
724 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
725 // C++0x [expr.new]p15:
726 // A new-expression that creates an object of type T initializes that
727 // object as follows:
728 InitializationKind Kind
729 // - If the new-initializer is omitted, the object is default-
730 // initialized (8.5); if no initialization is performed,
731 // the object has indeterminate value
732 = !Init? InitializationKind::CreateDefault(TypeLoc)
733 // - Otherwise, the new-initializer is interpreted according to the
734 // initialization rules of 8.5 for direct-initialization.
735 : InitializationKind::CreateDirect(TypeLoc,
736 ConstructorLParen,
737 ConstructorRParen);
738
Douglas Gregor85dabae2009-12-16 01:38:02 +0000739 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +0000740 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000741 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000742 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
743 move(ConstructorArgs));
744 if (FullInit.isInvalid())
745 return ExprError();
746
747 // FullInit is our initializer; walk through it to determine if it's a
748 // constructor call, which CXXNewExpr handles directly.
749 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
750 if (CXXBindTemporaryExpr *Binder
751 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
752 FullInitExpr = Binder->getSubExpr();
753 if (CXXConstructExpr *Construct
754 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
755 Constructor = Construct->getConstructor();
756 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
757 AEnd = Construct->arg_end();
758 A != AEnd; ++A)
759 ConvertedConstructorArgs.push_back(A->Retain());
760 } else {
761 // Take the converted initializer.
762 ConvertedConstructorArgs.push_back(FullInit.release());
763 }
764 } else {
765 // No initialization required.
766 }
767
768 // Take the converted arguments and use them for the new expression.
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000769 NumConsArgs = ConvertedConstructorArgs.size();
770 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redlbd150f42008-11-21 19:14:01 +0000771 }
Douglas Gregor85dabae2009-12-16 01:38:02 +0000772
Douglas Gregor6642ca22010-02-26 05:06:18 +0000773 // Mark the new and delete operators as referenced.
774 if (OperatorNew)
775 MarkDeclarationReferenced(StartLoc, OperatorNew);
776 if (OperatorDelete)
777 MarkDeclarationReferenced(StartLoc, OperatorDelete);
778
Sebastian Redlbd150f42008-11-21 19:14:01 +0000779 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor4bbd1ac2009-10-17 21:40:42 +0000780
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000781 PlacementArgs.release();
782 ConstructorArgs.release();
Douglas Gregord0fefba2009-05-21 00:00:09 +0000783 ArraySizeE.release();
Ted Kremenek9d6eb402010-02-11 22:51:03 +0000784 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
785 PlaceArgs, NumPlaceArgs, ParenTypeId,
786 ArraySize, Constructor, Init,
787 ConsArgs, NumConsArgs, OperatorDelete,
788 ResultType, StartLoc,
789 Init ? ConstructorRParen :
790 SourceLocation()));
Sebastian Redlbd150f42008-11-21 19:14:01 +0000791}
792
793/// CheckAllocatedType - Checks that a type is suitable as the allocated type
794/// in a new-expression.
795/// dimension off and stores the size expression in ArraySize.
Douglas Gregord0fefba2009-05-21 00:00:09 +0000796bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000797 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +0000798 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
799 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +0000800 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +0000801 return Diag(Loc, diag::err_bad_new_type)
802 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +0000803 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +0000804 return Diag(Loc, diag::err_bad_new_type)
805 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +0000806 else if (!AllocType->isDependentType() &&
Douglas Gregord0fefba2009-05-21 00:00:09 +0000807 RequireCompleteType(Loc, AllocType,
Anders Carlssond624e162009-08-26 23:45:07 +0000808 PDiag(diag::err_new_incomplete_type)
809 << R))
Sebastian Redlbd150f42008-11-21 19:14:01 +0000810 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +0000811 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +0000812 diag::err_allocation_of_abstract_type))
813 return true;
Sebastian Redlbd150f42008-11-21 19:14:01 +0000814
Sebastian Redlbd150f42008-11-21 19:14:01 +0000815 return false;
816}
817
Douglas Gregor6642ca22010-02-26 05:06:18 +0000818/// \brief Determine whether the given function is a non-placement
819/// deallocation function.
820static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
821 if (FD->isInvalidDecl())
822 return false;
823
824 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
825 return Method->isUsualDeallocationFunction();
826
827 return ((FD->getOverloadedOperator() == OO_Delete ||
828 FD->getOverloadedOperator() == OO_Array_Delete) &&
829 FD->getNumParams() == 1);
830}
831
Sebastian Redlfaf68082008-12-03 20:26:15 +0000832/// FindAllocationFunctions - Finds the overloads of operator new and delete
833/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000834bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
835 bool UseGlobal, QualType AllocType,
836 bool IsArray, Expr **PlaceArgs,
837 unsigned NumPlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +0000838 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +0000839 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-12-03 20:26:15 +0000840 // --- Choosing an allocation function ---
841 // C++ 5.3.4p8 - 14 & 18
842 // 1) If UseGlobal is true, only look in the global scope. Else, also look
843 // in the scope of the allocated class.
844 // 2) If an array size is given, look for operator new[], else look for
845 // operator new.
846 // 3) The first argument is always size_t. Append the arguments from the
847 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +0000848
849 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
850 // We don't care about the actual value of this argument.
851 // FIXME: Should the Sema create the expression and embed it in the syntax
852 // tree? Or should the consumer just recalculate the value?
Anders Carlssona471db02009-08-16 20:29:29 +0000853 IntegerLiteral Size(llvm::APInt::getNullValue(
854 Context.Target.getPointerWidth(0)),
855 Context.getSizeType(),
856 SourceLocation());
857 AllocArgs[0] = &Size;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000858 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
859
Douglas Gregor6642ca22010-02-26 05:06:18 +0000860 // C++ [expr.new]p8:
861 // If the allocated type is a non-array type, the allocation
862 // function’s name is operator new and the deallocation function’s
863 // name is operator delete. If the allocated type is an array
864 // type, the allocation function’s name is operator new[] and the
865 // deallocation function’s name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +0000866 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
867 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +0000868 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
869 IsArray ? OO_Array_Delete : OO_Delete);
870
Sebastian Redlfaf68082008-12-03 20:26:15 +0000871 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump11289f42009-09-09 15:08:12 +0000872 CXXRecordDecl *Record
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000873 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000874 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +0000875 AllocArgs.size(), Record, /*AllowMissing=*/true,
876 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +0000877 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000878 }
879 if (!OperatorNew) {
880 // Didn't find a member overload. Look for a global one.
881 DeclareGlobalNewDelete();
Sebastian Redl33a31012008-12-04 22:20:51 +0000882 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000883 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +0000884 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
885 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +0000886 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000887 }
888
Anders Carlsson6f9dabf2009-05-31 20:26:12 +0000889 // FindAllocationOverload can change the passed in arguments, so we need to
890 // copy them back.
891 if (NumPlaceArgs > 0)
892 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump11289f42009-09-09 15:08:12 +0000893
Douglas Gregor6642ca22010-02-26 05:06:18 +0000894 // C++ [expr.new]p19:
895 //
896 // If the new-expression begins with a unary :: operator, the
897 // deallocation function’s name is looked up in the global
898 // scope. Otherwise, if the allocated type is a class type T or an
899 // array thereof, the deallocation function’s name is looked up in
900 // the scope of T. If this lookup fails to find the name, or if
901 // the allocated type is not a class type or array thereof, the
902 // deallocation function’s name is looked up in the global scope.
903 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
904 if (AllocType->isRecordType() && !UseGlobal) {
905 CXXRecordDecl *RD
906 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
907 LookupQualifiedName(FoundDelete, RD);
908 }
John McCallfb6f5262010-03-18 08:19:33 +0000909 if (FoundDelete.isAmbiguous())
910 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +0000911
912 if (FoundDelete.empty()) {
913 DeclareGlobalNewDelete();
914 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
915 }
916
917 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +0000918
919 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
920
John McCallfb6f5262010-03-18 08:19:33 +0000921 if (NumPlaceArgs > 0) {
Douglas Gregor6642ca22010-02-26 05:06:18 +0000922 // C++ [expr.new]p20:
923 // A declaration of a placement deallocation function matches the
924 // declaration of a placement allocation function if it has the
925 // same number of parameters and, after parameter transformations
926 // (8.3.5), all parameter types except the first are
927 // identical. [...]
928 //
929 // To perform this comparison, we compute the function type that
930 // the deallocation function should have, and use that type both
931 // for template argument deduction and for comparison purposes.
932 QualType ExpectedFunctionType;
933 {
934 const FunctionProtoType *Proto
935 = OperatorNew->getType()->getAs<FunctionProtoType>();
936 llvm::SmallVector<QualType, 4> ArgTypes;
937 ArgTypes.push_back(Context.VoidPtrTy);
938 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
939 ArgTypes.push_back(Proto->getArgType(I));
940
941 ExpectedFunctionType
942 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
943 ArgTypes.size(),
944 Proto->isVariadic(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000945 0, false, false, 0, 0,
946 FunctionType::ExtInfo());
Douglas Gregor6642ca22010-02-26 05:06:18 +0000947 }
948
949 for (LookupResult::iterator D = FoundDelete.begin(),
950 DEnd = FoundDelete.end();
951 D != DEnd; ++D) {
952 FunctionDecl *Fn = 0;
953 if (FunctionTemplateDecl *FnTmpl
954 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
955 // Perform template argument deduction to try to match the
956 // expected function type.
957 TemplateDeductionInfo Info(Context, StartLoc);
958 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
959 continue;
960 } else
961 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
962
963 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +0000964 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +0000965 }
966 } else {
967 // C++ [expr.new]p20:
968 // [...] Any non-placement deallocation function matches a
969 // non-placement allocation function. [...]
970 for (LookupResult::iterator D = FoundDelete.begin(),
971 DEnd = FoundDelete.end();
972 D != DEnd; ++D) {
973 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
974 if (isNonPlacementDeallocationFunction(Fn))
John McCalla0296f72010-03-19 07:35:19 +0000975 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +0000976 }
977 }
978
979 // C++ [expr.new]p20:
980 // [...] If the lookup finds a single matching deallocation
981 // function, that function will be called; otherwise, no
982 // deallocation function will be called.
983 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +0000984 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +0000985
986 // C++0x [expr.new]p20:
987 // If the lookup finds the two-parameter form of a usual
988 // deallocation function (3.7.4.2) and that function, considered
989 // as a placement deallocation function, would have been
990 // selected as a match for the allocation function, the program
991 // is ill-formed.
992 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
993 isNonPlacementDeallocationFunction(OperatorDelete)) {
994 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
995 << SourceRange(PlaceArgs[0]->getLocStart(),
996 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
997 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
998 << DeleteName;
John McCallfb6f5262010-03-18 08:19:33 +0000999 } else {
1000 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCalla0296f72010-03-19 07:35:19 +00001001 Matches[0].first);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001002 }
1003 }
1004
Sebastian Redlfaf68082008-12-03 20:26:15 +00001005 return false;
1006}
1007
Sebastian Redl33a31012008-12-04 22:20:51 +00001008/// FindAllocationOverload - Find an fitting overload for the allocation
1009/// function in the specified scope.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001010bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1011 DeclarationName Name, Expr** Args,
1012 unsigned NumArgs, DeclContext *Ctx,
Mike Stump11289f42009-09-09 15:08:12 +00001013 bool AllowMissing, FunctionDecl *&Operator) {
John McCall27b18f82009-11-17 02:14:36 +00001014 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1015 LookupQualifiedName(R, Ctx);
John McCall9f3059a2009-10-09 21:13:30 +00001016 if (R.empty()) {
Sebastian Redl33a31012008-12-04 22:20:51 +00001017 if (AllowMissing)
1018 return false;
Sebastian Redl33a31012008-12-04 22:20:51 +00001019 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00001020 << Name << Range;
Sebastian Redl33a31012008-12-04 22:20:51 +00001021 }
1022
John McCallfb6f5262010-03-18 08:19:33 +00001023 if (R.isAmbiguous())
1024 return true;
1025
1026 R.suppressDiagnostics();
John McCall9f3059a2009-10-09 21:13:30 +00001027
John McCallbc077cf2010-02-08 23:07:23 +00001028 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor80a6cc52009-09-30 00:03:47 +00001029 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1030 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor55297ac2008-12-23 00:26:44 +00001031 // Even member operator new/delete are implicitly treated as
1032 // static, so don't use AddMemberCandidate.
John McCalla0296f72010-03-19 07:35:19 +00001033 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth93538422010-02-03 11:02:14 +00001034
John McCalla0296f72010-03-19 07:35:19 +00001035 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1036 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth93538422010-02-03 11:02:14 +00001037 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1038 Candidates,
1039 /*SuppressUserConversions=*/false);
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001040 continue;
Chandler Carruth93538422010-02-03 11:02:14 +00001041 }
1042
John McCalla0296f72010-03-19 07:35:19 +00001043 FunctionDecl *Fn = cast<FunctionDecl>(D);
1044 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth93538422010-02-03 11:02:14 +00001045 /*SuppressUserConversions=*/false);
Sebastian Redl33a31012008-12-04 22:20:51 +00001046 }
1047
1048 // Do the resolution.
1049 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001050 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl33a31012008-12-04 22:20:51 +00001051 case OR_Success: {
1052 // Got one!
1053 FunctionDecl *FnDecl = Best->Function;
1054 // The first argument is size_t, and the first parameter must be size_t,
1055 // too. This is checked on declaration and can be assumed. (It can't be
1056 // asserted on, though, since invalid decls are left in there.)
John McCallfb6f5262010-03-18 08:19:33 +00001057 // Watch out for variadic allocator function.
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001058 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1059 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Douglas Gregor34147272010-03-26 20:35:59 +00001060 OwningExprResult Result
1061 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
1062 FnDecl->getParamDecl(i)),
1063 SourceLocation(),
1064 Owned(Args[i]->Retain()));
1065 if (Result.isInvalid())
Sebastian Redl33a31012008-12-04 22:20:51 +00001066 return true;
Douglas Gregor34147272010-03-26 20:35:59 +00001067
1068 Args[i] = Result.takeAs<Expr>();
Sebastian Redl33a31012008-12-04 22:20:51 +00001069 }
1070 Operator = FnDecl;
John McCalla0296f72010-03-19 07:35:19 +00001071 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl33a31012008-12-04 22:20:51 +00001072 return false;
1073 }
1074
1075 case OR_No_Viable_Function:
Sebastian Redl33a31012008-12-04 22:20:51 +00001076 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00001077 << Name << Range;
John McCallad907772010-01-12 07:18:19 +00001078 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl33a31012008-12-04 22:20:51 +00001079 return true;
1080
1081 case OR_Ambiguous:
Sebastian Redl33a31012008-12-04 22:20:51 +00001082 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001083 << Name << Range;
John McCallad907772010-01-12 07:18:19 +00001084 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl33a31012008-12-04 22:20:51 +00001085 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001086
1087 case OR_Deleted:
1088 Diag(StartLoc, diag::err_ovl_deleted_call)
1089 << Best->Function->isDeleted()
1090 << Name << Range;
John McCallad907772010-01-12 07:18:19 +00001091 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001092 return true;
Sebastian Redl33a31012008-12-04 22:20:51 +00001093 }
1094 assert(false && "Unreachable, bad result from BestViableFunction");
1095 return true;
1096}
1097
1098
Sebastian Redlfaf68082008-12-03 20:26:15 +00001099/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1100/// delete. These are:
1101/// @code
1102/// void* operator new(std::size_t) throw(std::bad_alloc);
1103/// void* operator new[](std::size_t) throw(std::bad_alloc);
1104/// void operator delete(void *) throw();
1105/// void operator delete[](void *) throw();
1106/// @endcode
1107/// Note that the placement and nothrow forms of new are *not* implicitly
1108/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00001109void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001110 if (GlobalNewDeleteDeclared)
1111 return;
Douglas Gregor87f54062009-09-15 22:30:29 +00001112
1113 // C++ [basic.std.dynamic]p2:
1114 // [...] The following allocation and deallocation functions (18.4) are
1115 // implicitly declared in global scope in each translation unit of a
1116 // program
1117 //
1118 // void* operator new(std::size_t) throw(std::bad_alloc);
1119 // void* operator new[](std::size_t) throw(std::bad_alloc);
1120 // void operator delete(void*) throw();
1121 // void operator delete[](void*) throw();
1122 //
1123 // These implicit declarations introduce only the function names operator
1124 // new, operator new[], operator delete, operator delete[].
1125 //
1126 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1127 // "std" or "bad_alloc" as necessary to form the exception specification.
1128 // However, we do not make these implicit declarations visible to name
1129 // lookup.
1130 if (!StdNamespace) {
1131 // The "std" namespace has not yet been defined, so build one implicitly.
1132 StdNamespace = NamespaceDecl::Create(Context,
1133 Context.getTranslationUnitDecl(),
1134 SourceLocation(),
1135 &PP.getIdentifierTable().get("std"));
1136 StdNamespace->setImplicit(true);
1137 }
1138
1139 if (!StdBadAlloc) {
1140 // The "std::bad_alloc" class has not yet been declared, so build it
1141 // implicitly.
1142 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
1143 StdNamespace,
1144 SourceLocation(),
1145 &PP.getIdentifierTable().get("bad_alloc"),
1146 SourceLocation(), 0);
1147 StdBadAlloc->setImplicit(true);
1148 }
1149
Sebastian Redlfaf68082008-12-03 20:26:15 +00001150 GlobalNewDeleteDeclared = true;
1151
1152 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1153 QualType SizeT = Context.getSizeType();
Nuno Lopes13c88c72009-12-16 16:59:22 +00001154 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001155
Sebastian Redlfaf68082008-12-03 20:26:15 +00001156 DeclareGlobalAllocationFunction(
1157 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001158 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001159 DeclareGlobalAllocationFunction(
1160 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001161 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001162 DeclareGlobalAllocationFunction(
1163 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1164 Context.VoidTy, VoidPtr);
1165 DeclareGlobalAllocationFunction(
1166 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1167 Context.VoidTy, VoidPtr);
1168}
1169
1170/// DeclareGlobalAllocationFunction - Declares a single implicit global
1171/// allocation function if it doesn't already exist.
1172void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopes13c88c72009-12-16 16:59:22 +00001173 QualType Return, QualType Argument,
1174 bool AddMallocAttr) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001175 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1176
1177 // Check if this function is already declared.
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001178 {
Douglas Gregor17eb26b2008-12-23 22:05:29 +00001179 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001180 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001181 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth93538422010-02-03 11:02:14 +00001182 // Only look at non-template functions, as it is the predefined,
1183 // non-templated allocation function we are trying to declare here.
1184 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1185 QualType InitialParamType =
Douglas Gregor684d7bd2009-12-22 23:42:49 +00001186 Context.getCanonicalType(
Chandler Carruth93538422010-02-03 11:02:14 +00001187 Func->getParamDecl(0)->getType().getUnqualifiedType());
1188 // FIXME: Do we need to check for default arguments here?
1189 if (Func->getNumParams() == 1 && InitialParamType == Argument)
1190 return;
1191 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00001192 }
1193 }
1194
Douglas Gregor87f54062009-09-15 22:30:29 +00001195 QualType BadAllocType;
1196 bool HasBadAllocExceptionSpec
1197 = (Name.getCXXOverloadedOperator() == OO_New ||
1198 Name.getCXXOverloadedOperator() == OO_Array_New);
1199 if (HasBadAllocExceptionSpec) {
1200 assert(StdBadAlloc && "Must have std::bad_alloc declared");
1201 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
1202 }
1203
1204 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1205 true, false,
1206 HasBadAllocExceptionSpec? 1 : 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001207 &BadAllocType,
1208 FunctionType::ExtInfo());
Sebastian Redlfaf68082008-12-03 20:26:15 +00001209 FunctionDecl *Alloc =
1210 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCallbcd03502009-12-07 02:54:59 +00001211 FnType, /*TInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001212 Alloc->setImplicit();
Nuno Lopes13c88c72009-12-16 16:59:22 +00001213
1214 if (AddMallocAttr)
1215 Alloc->addAttr(::new (Context) MallocAttr());
1216
Sebastian Redlfaf68082008-12-03 20:26:15 +00001217 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCallbcd03502009-12-07 02:54:59 +00001218 0, Argument, /*TInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00001219 VarDecl::None, 0);
Douglas Gregord5058122010-02-11 01:19:42 +00001220 Alloc->setParams(&Param, 1);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001221
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001222 // FIXME: Also add this declaration to the IdentifierResolver, but
1223 // make sure it is at the end of the chain to coincide with the
1224 // global scope.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001225 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001226}
1227
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001228bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1229 DeclarationName Name,
Anders Carlssonf98849e2009-12-02 17:15:43 +00001230 FunctionDecl* &Operator) {
John McCall27b18f82009-11-17 02:14:36 +00001231 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001232 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00001233 LookupQualifiedName(Found, RD);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001234
John McCall27b18f82009-11-17 02:14:36 +00001235 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001236 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001237
1238 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1239 F != FEnd; ++F) {
1240 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
1241 if (Delete->isUsualDeallocationFunction()) {
1242 Operator = Delete;
1243 return false;
1244 }
1245 }
1246
1247 // We did find operator delete/operator delete[] declarations, but
1248 // none of them were suitable.
1249 if (!Found.empty()) {
1250 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1251 << Name << RD;
1252
1253 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1254 F != FEnd; ++F) {
1255 Diag((*F)->getLocation(),
1256 diag::note_delete_member_function_declared_here)
1257 << Name;
1258 }
1259
1260 return true;
1261 }
1262
1263 // Look for a global declaration.
1264 DeclareGlobalNewDelete();
1265 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1266
1267 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1268 Expr* DeallocArgs[1];
1269 DeallocArgs[0] = &Null;
1270 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1271 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1272 Operator))
1273 return true;
1274
1275 assert(Operator && "Did not find a deallocation function!");
1276 return false;
1277}
1278
Sebastian Redlbd150f42008-11-21 19:14:01 +00001279/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1280/// @code ::delete ptr; @endcode
1281/// or
1282/// @code delete [] ptr; @endcode
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001283Action::OwningExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001284Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump11289f42009-09-09 15:08:12 +00001285 bool ArrayForm, ExprArg Operand) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001286 // C++ [expr.delete]p1:
1287 // The operand shall have a pointer type, or a class type having a single
1288 // conversion function to a pointer type. The result has type void.
1289 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00001290 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1291
Anders Carlssona471db02009-08-16 20:29:29 +00001292 FunctionDecl *OperatorDelete = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001293
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001294 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001295 if (!Ex->isTypeDependent()) {
1296 QualType Type = Ex->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00001297
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001298 if (const RecordType *Record = Type->getAs<RecordType>()) {
John McCallda4458e2010-03-31 01:36:47 +00001299 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1300
Fariborz Jahanianb54ccb22009-09-11 21:44:33 +00001301 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCallda4458e2010-03-31 01:36:47 +00001302 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001303 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001304 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00001305 NamedDecl *D = I.getDecl();
1306 if (isa<UsingShadowDecl>(D))
1307 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1308
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001309 // Skip over templated conversion functions; they aren't considered.
John McCallda4458e2010-03-31 01:36:47 +00001310 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001311 continue;
1312
John McCallda4458e2010-03-31 01:36:47 +00001313 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001314
1315 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1316 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1317 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001318 ObjectPtrConversions.push_back(Conv);
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001319 }
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001320 if (ObjectPtrConversions.size() == 1) {
1321 // We have a single conversion to a pointer-to-object type. Perform
1322 // that conversion.
John McCallda4458e2010-03-31 01:36:47 +00001323 // TODO: don't redo the conversion calculation.
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001324 Operand.release();
John McCallda4458e2010-03-31 01:36:47 +00001325 if (!PerformImplicitConversion(Ex,
1326 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001327 AA_Converting)) {
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001328 Operand = Owned(Ex);
1329 Type = Ex->getType();
1330 }
1331 }
1332 else if (ObjectPtrConversions.size() > 1) {
1333 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1334 << Type << Ex->getSourceRange();
John McCallda4458e2010-03-31 01:36:47 +00001335 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1336 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001337 return ExprError();
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001338 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001339 }
1340
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001341 if (!Type->isPointerType())
1342 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1343 << Type << Ex->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001344
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001345 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001346 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001347 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1348 << Type << Ex->getSourceRange());
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001349 else if (!Pointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00001350 RequireCompleteType(StartLoc, Pointee,
Anders Carlssond624e162009-08-26 23:45:07 +00001351 PDiag(diag::warn_delete_incomplete)
1352 << Ex->getSourceRange()))
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001353 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001354
Douglas Gregor98496dc2009-09-29 21:38:53 +00001355 // C++ [expr.delete]p2:
1356 // [Note: a pointer to a const type can be the operand of a
1357 // delete-expression; it is not necessary to cast away the constness
1358 // (5.2.11) of the pointer expression before it is used as the operand
1359 // of the delete-expression. ]
1360 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
1361 CastExpr::CK_NoOp);
1362
1363 // Update the operand.
1364 Operand.take();
1365 Operand = ExprArg(*this, Ex);
1366
Anders Carlssona471db02009-08-16 20:29:29 +00001367 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1368 ArrayForm ? OO_Array_Delete : OO_Delete);
1369
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001370 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
1371 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1372
1373 if (!UseGlobal &&
1374 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00001375 return ExprError();
Anders Carlsson654e5c72009-11-14 03:17:38 +00001376
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001377 if (!RD->hasTrivialDestructor())
1378 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump11289f42009-09-09 15:08:12 +00001379 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001380 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssona471db02009-08-16 20:29:29 +00001381 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001382
Anders Carlssona471db02009-08-16 20:29:29 +00001383 if (!OperatorDelete) {
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001384 // Look for a global declaration.
Anders Carlssona471db02009-08-16 20:29:29 +00001385 DeclareGlobalNewDelete();
1386 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001387 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001388 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssona471db02009-08-16 20:29:29 +00001389 OperatorDelete))
1390 return ExprError();
1391 }
Mike Stump11289f42009-09-09 15:08:12 +00001392
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001393 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redlbd150f42008-11-21 19:14:01 +00001394 }
1395
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001396 Operand.release();
1397 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssona471db02009-08-16 20:29:29 +00001398 OperatorDelete, Ex, StartLoc));
Sebastian Redlbd150f42008-11-21 19:14:01 +00001399}
1400
Douglas Gregor633caca2009-11-23 23:44:04 +00001401/// \brief Check the use of the given variable as a C++ condition in an if,
1402/// while, do-while, or switch statement.
1403Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar) {
1404 QualType T = ConditionVar->getType();
1405
1406 // C++ [stmt.select]p2:
1407 // The declarator shall not specify a function or an array.
1408 if (T->isFunctionType())
1409 return ExprError(Diag(ConditionVar->getLocation(),
1410 diag::err_invalid_use_of_function_type)
1411 << ConditionVar->getSourceRange());
1412 else if (T->isArrayType())
1413 return ExprError(Diag(ConditionVar->getLocation(),
1414 diag::err_invalid_use_of_array_type)
1415 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00001416
Douglas Gregor633caca2009-11-23 23:44:04 +00001417 return Owned(DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1418 ConditionVar->getLocation(),
1419 ConditionVar->getType().getNonReferenceType()));
1420}
1421
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001422/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1423bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1424 // C++ 6.4p4:
1425 // The value of a condition that is an initialized declaration in a statement
1426 // other than a switch statement is the value of the declared variable
1427 // implicitly converted to type bool. If that conversion is ill-formed, the
1428 // program is ill-formed.
1429 // The value of a condition that is an expression is the value of the
1430 // expression, implicitly converted to bool.
1431 //
Douglas Gregor5fb53972009-01-14 15:45:31 +00001432 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001433}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001434
1435/// Helper function to determine whether this is the (deprecated) C++
1436/// conversion from a string literal to a pointer to non-const char or
1437/// non-const wchar_t (for narrow and wide string literals,
1438/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00001439bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001440Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1441 // Look inside the implicit cast, if it exists.
1442 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1443 From = Cast->getSubExpr();
1444
1445 // A string literal (2.13.4) that is not a wide string literal can
1446 // be converted to an rvalue of type "pointer to char"; a wide
1447 // string literal can be converted to an rvalue of type "pointer
1448 // to wchar_t" (C++ 4.2p2).
1449 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001450 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001451 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00001452 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001453 // This conversion is considered only when there is an
1454 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall8ccfcb52009-09-24 19:53:00 +00001455 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001456 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1457 (!StrLit->isWide() &&
1458 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1459 ToPointeeType->getKind() == BuiltinType::Char_S))))
1460 return true;
1461 }
1462
1463 return false;
1464}
Douglas Gregor39c16d42008-10-24 04:54:22 +00001465
1466/// PerformImplicitConversion - Perform an implicit conversion of the
1467/// expression From to the type ToType. Returns true if there was an
1468/// error, false otherwise. The expression From is replaced with the
Douglas Gregor47d3f272008-12-19 17:40:08 +00001469/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor5fb53972009-01-14 15:45:31 +00001470/// performing, used in the error message. If @p AllowExplicit,
Douglas Gregorf1495202010-04-16 17:16:43 +00001471/// explicit user-defined conversions are permitted.
Sebastian Redl42e92c42009-04-12 17:16:29 +00001472bool
Douglas Gregor47d3f272008-12-19 17:40:08 +00001473Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregorf1495202010-04-16 17:16:43 +00001474 AssignmentAction Action, bool AllowExplicit) {
Sebastian Redl42e92c42009-04-12 17:16:29 +00001475 ImplicitConversionSequence ICS;
Douglas Gregorf1495202010-04-16 17:16:43 +00001476 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00001477}
1478
1479bool
1480Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001481 AssignmentAction Action, bool AllowExplicit,
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00001482 ImplicitConversionSequence& ICS) {
Douglas Gregorf1495202010-04-16 17:16:43 +00001483 ICS = TryImplicitConversion(From, ToType,
1484 /*SuppressUserConversions=*/false,
1485 AllowExplicit,
Douglas Gregorf1495202010-04-16 17:16:43 +00001486 /*InOverloadResolution=*/false);
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001487 return PerformImplicitConversion(From, ToType, ICS, Action);
Douglas Gregor5fb53972009-01-14 15:45:31 +00001488}
1489
1490/// PerformImplicitConversion - Perform an implicit conversion of the
1491/// expression From to the type ToType using the pre-computed implicit
1492/// conversion sequence ICS. Returns true if there was an error, false
1493/// otherwise. The expression From is replaced with the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001494/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001495/// used in the error message.
1496bool
1497Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1498 const ImplicitConversionSequence &ICS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001499 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall0d1da222010-01-12 00:44:57 +00001500 switch (ICS.getKind()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001501 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001502 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redl7c353682009-11-14 21:15:49 +00001503 IgnoreBaseAccess))
Douglas Gregor39c16d42008-10-24 04:54:22 +00001504 return true;
1505 break;
1506
Anders Carlsson110b07b2009-09-15 06:28:28 +00001507 case ImplicitConversionSequence::UserDefinedConversion: {
1508
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00001509 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1510 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlsson110b07b2009-09-15 06:28:28 +00001511 QualType BeforeToType;
1512 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00001513 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlsson110b07b2009-09-15 06:28:28 +00001514
1515 // If the user-defined conversion is specified by a conversion function,
1516 // the initial standard conversion sequence converts the source type to
1517 // the implicit object parameter of the conversion function.
1518 BeforeToType = Context.getTagDeclType(Conv->getParent());
1519 } else if (const CXXConstructorDecl *Ctor =
1520 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlssone9766d52009-09-09 21:33:21 +00001521 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001522 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00001523 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian55824512009-11-06 00:23:08 +00001524 // If the user-defined conversion is specified by a constructor, the
1525 // initial standard conversion sequence converts the source type to the
1526 // type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00001527 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1528 }
Anders Carlsson110b07b2009-09-15 06:28:28 +00001529 }
Anders Carlssone9766d52009-09-09 21:33:21 +00001530 else
1531 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian55824512009-11-06 00:23:08 +00001532 // Whatch out for elipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00001533 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian55824512009-11-06 00:23:08 +00001534 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001535 ICS.UserDefined.Before, AA_Converting,
Sebastian Redl7c353682009-11-14 21:15:49 +00001536 IgnoreBaseAccess))
Fariborz Jahanian55824512009-11-06 00:23:08 +00001537 return true;
1538 }
Anders Carlsson110b07b2009-09-15 06:28:28 +00001539
Anders Carlssone9766d52009-09-09 21:33:21 +00001540 OwningExprResult CastArg
1541 = BuildCXXCastArgument(From->getLocStart(),
1542 ToType.getNonReferenceType(),
1543 CastKind, cast<CXXMethodDecl>(FD),
1544 Owned(From));
1545
1546 if (CastArg.isInvalid())
1547 return true;
Eli Friedmane96f1d32009-11-27 04:41:50 +00001548
1549 From = CastArg.takeAs<Expr>();
1550
Eli Friedmane96f1d32009-11-27 04:41:50 +00001551 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001552 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00001553 }
John McCall0d1da222010-01-12 00:44:57 +00001554
1555 case ImplicitConversionSequence::AmbiguousConversion:
1556 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1557 PDiag(diag::err_typecheck_ambiguous_condition)
1558 << From->getSourceRange());
1559 return true;
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00001560
Douglas Gregor39c16d42008-10-24 04:54:22 +00001561 case ImplicitConversionSequence::EllipsisConversion:
1562 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001563 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001564
1565 case ImplicitConversionSequence::BadConversion:
1566 return true;
1567 }
1568
1569 // Everything went well.
1570 return false;
1571}
1572
1573/// PerformImplicitConversion - Perform an implicit conversion of the
1574/// expression From to the type ToType by following the standard
1575/// conversion sequence SCS. Returns true if there was an error, false
1576/// otherwise. The expression From is replaced with the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00001577/// expression. Flavor is the context in which we're performing this
1578/// conversion, for use in error messages.
Mike Stump11289f42009-09-09 15:08:12 +00001579bool
Douglas Gregor39c16d42008-10-24 04:54:22 +00001580Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001581 const StandardConversionSequence& SCS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001582 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001583 // Overall FIXME: we are recomputing too many types here and doing far too
1584 // much extra work. What this means is that we need to keep track of more
1585 // information that is computed when we try the implicit conversion initially,
1586 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00001587 QualType FromType = From->getType();
1588
Douglas Gregor2fe98832008-11-03 19:09:14 +00001589 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00001590 // FIXME: When can ToType be a reference type?
1591 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00001592 if (SCS.Second == ICK_Derived_To_Base) {
1593 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1594 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1595 MultiExprArg(*this, (void **)&From, 1),
1596 /*FIXME:ConstructLoc*/SourceLocation(),
1597 ConstructorArgs))
1598 return true;
1599 OwningExprResult FromResult =
1600 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1601 ToType, SCS.CopyConstructor,
1602 move_arg(ConstructorArgs));
1603 if (FromResult.isInvalid())
1604 return true;
1605 From = FromResult.takeAs<Expr>();
1606 return false;
1607 }
Mike Stump11289f42009-09-09 15:08:12 +00001608 OwningExprResult FromResult =
1609 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1610 ToType, SCS.CopyConstructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00001611 MultiExprArg(*this, (void**)&From, 1));
Mike Stump11289f42009-09-09 15:08:12 +00001612
Anders Carlsson6eb55572009-08-25 05:12:04 +00001613 if (FromResult.isInvalid())
1614 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001615
Anders Carlsson6eb55572009-08-25 05:12:04 +00001616 From = FromResult.takeAs<Expr>();
Douglas Gregor2fe98832008-11-03 19:09:14 +00001617 return false;
1618 }
1619
Douglas Gregor39c16d42008-10-24 04:54:22 +00001620 // Perform the first implicit conversion.
1621 switch (SCS.First) {
1622 case ICK_Identity:
1623 case ICK_Lvalue_To_Rvalue:
1624 // Nothing to do.
1625 break;
1626
1627 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00001628 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson2c101b32009-08-08 21:04:35 +00001629 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001630 break;
1631
1632 case ICK_Function_To_Pointer:
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001633 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
John McCall16df1e52010-03-30 21:47:33 +00001634 DeclAccessPair Found;
1635 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1636 true, Found);
Douglas Gregorcd695e52008-11-10 20:40:00 +00001637 if (!Fn)
1638 return true;
1639
Douglas Gregor171c45a2009-02-18 21:56:37 +00001640 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1641 return true;
1642
John McCall16df1e52010-03-30 21:47:33 +00001643 From = FixOverloadedFunctionReference(From, Found, Fn);
Douglas Gregorcd695e52008-11-10 20:40:00 +00001644 FromType = From->getType();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00001645
Sebastian Redlfef1c0d2009-10-17 20:50:27 +00001646 // If there's already an address-of operator in the expression, we have
1647 // the right type already, and the code below would just introduce an
1648 // invalid additional pointer level.
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00001649 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
Sebastian Redlfef1c0d2009-10-17 20:50:27 +00001650 break;
Douglas Gregorcd695e52008-11-10 20:40:00 +00001651 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001652 FromType = Context.getPointerType(FromType);
Anders Carlsson6904f642009-09-01 20:37:18 +00001653 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001654 break;
1655
1656 default:
1657 assert(false && "Improper first standard conversion");
1658 break;
1659 }
1660
1661 // Perform the second implicit conversion
1662 switch (SCS.Second) {
1663 case ICK_Identity:
Sebastian Redl5d431642009-10-10 12:04:10 +00001664 // If both sides are functions (or pointers/references to them), there could
1665 // be incompatible exception declarations.
1666 if (CheckExceptionSpecCompatibility(From, ToType))
1667 return true;
1668 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00001669 break;
1670
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001671 case ICK_NoReturn_Adjustment:
1672 // If both sides are functions (or pointers/references to them), there could
1673 // be incompatible exception declarations.
1674 if (CheckExceptionSpecCompatibility(From, ToType))
1675 return true;
1676
1677 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1678 CastExpr::CK_NoOp);
1679 break;
1680
Douglas Gregor39c16d42008-10-24 04:54:22 +00001681 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001682 case ICK_Integral_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001683 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1684 break;
1685
1686 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001687 case ICK_Floating_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001688 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1689 break;
1690
1691 case ICK_Complex_Promotion:
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001692 case ICK_Complex_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001693 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1694 break;
1695
Douglas Gregor39c16d42008-10-24 04:54:22 +00001696 case ICK_Floating_Integral:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001697 if (ToType->isFloatingType())
1698 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1699 else
1700 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1701 break;
1702
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001703 case ICK_Complex_Real:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001704 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1705 break;
1706
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001707 case ICK_Compatible_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001708 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001709 break;
1710
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001711 case ICK_Pointer_Conversion: {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001712 if (SCS.IncompatibleObjC) {
1713 // Diagnose incompatible Objective-C conversions
Mike Stump11289f42009-09-09 15:08:12 +00001714 Diag(From->getSourceRange().getBegin(),
Douglas Gregor47d3f272008-12-19 17:40:08 +00001715 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001716 << From->getType() << ToType << Action
Douglas Gregor47d3f272008-12-19 17:40:08 +00001717 << From->getSourceRange();
1718 }
1719
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001720
1721 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redl7c353682009-11-14 21:15:49 +00001722 if (CheckPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Douglas Gregor39c16d42008-10-24 04:54:22 +00001723 return true;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001724 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001725 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001726 }
1727
1728 case ICK_Pointer_Member: {
1729 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redl7c353682009-11-14 21:15:49 +00001730 if (CheckMemberPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001731 return true;
Sebastian Redl5d431642009-10-10 12:04:10 +00001732 if (CheckExceptionSpecCompatibility(From, ToType))
1733 return true;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001734 ImpCastExprToType(From, ToType, Kind);
1735 break;
1736 }
Anders Carlsson7fa434c2009-11-23 20:04:44 +00001737 case ICK_Boolean_Conversion: {
1738 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1739 if (FromType->isMemberPointerType())
1740 Kind = CastExpr::CK_MemberPointerToBoolean;
1741
1742 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001743 break;
Anders Carlsson7fa434c2009-11-23 20:04:44 +00001744 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001745
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001746 case ICK_Derived_To_Base:
1747 if (CheckDerivedToBaseConversion(From->getType(),
1748 ToType.getNonReferenceType(),
1749 From->getLocStart(),
Sebastian Redl7c353682009-11-14 21:15:49 +00001750 From->getSourceRange(),
1751 IgnoreBaseAccess))
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001752 return true;
1753 ImpCastExprToType(From, ToType.getNonReferenceType(),
1754 CastExpr::CK_DerivedToBase);
1755 break;
1756
Douglas Gregor39c16d42008-10-24 04:54:22 +00001757 default:
1758 assert(false && "Improper second standard conversion");
1759 break;
1760 }
1761
1762 switch (SCS.Third) {
1763 case ICK_Identity:
1764 // Nothing to do.
1765 break;
1766
1767 case ICK_Qualification:
Mike Stump87c57ac2009-05-16 07:39:55 +00001768 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1769 // references.
Mike Stump11289f42009-09-09 15:08:12 +00001770 ImpCastExprToType(From, ToType.getNonReferenceType(),
Eli Friedman06ed2a52009-10-20 08:27:19 +00001771 CastExpr::CK_NoOp,
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001772 ToType->isLValueReferenceType());
Douglas Gregore489a7d2010-02-28 18:30:25 +00001773
1774 if (SCS.DeprecatedStringLiteralToCharPtr)
1775 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
1776 << ToType.getNonReferenceType();
1777
Douglas Gregor39c16d42008-10-24 04:54:22 +00001778 break;
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001779
Douglas Gregor39c16d42008-10-24 04:54:22 +00001780 default:
1781 assert(false && "Improper second standard conversion");
1782 break;
1783 }
1784
1785 return false;
1786}
1787
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001788Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1789 SourceLocation KWLoc,
1790 SourceLocation LParen,
1791 TypeTy *Ty,
1792 SourceLocation RParen) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001793 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00001794
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001795 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1796 // all traits except __is_class, __is_enum and __is_union require a the type
1797 // to be complete.
1798 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump11289f42009-09-09 15:08:12 +00001799 if (RequireCompleteType(KWLoc, T,
Anders Carlsson029fc692009-08-26 22:59:12 +00001800 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001801 return ExprError();
1802 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001803
1804 // There is no point in eagerly computing the value. The traits are designed
1805 // to be used from type trait templates, so Ty will be a template parameter
1806 // 99% of the time.
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001807 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1808 RParen, Context.BoolTy));
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001809}
Sebastian Redl5822f082009-02-07 20:10:22 +00001810
1811QualType Sema::CheckPointerToMemberOperands(
Mike Stump11289f42009-09-09 15:08:12 +00001812 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl5822f082009-02-07 20:10:22 +00001813 const char *OpSpelling = isIndirect ? "->*" : ".*";
1814 // C++ 5.5p2
1815 // The binary operator .* [p3: ->*] binds its second operand, which shall
1816 // be of type "pointer to member of T" (where T is a completely-defined
1817 // class type) [...]
1818 QualType RType = rex->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001819 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00001820 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00001821 Diag(Loc, diag::err_bad_memptr_rhs)
1822 << OpSpelling << RType << rex->getSourceRange();
1823 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001824 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00001825
Sebastian Redl5822f082009-02-07 20:10:22 +00001826 QualType Class(MemPtr->getClass(), 0);
1827
Sebastian Redlc72350e2010-04-10 10:14:54 +00001828 if (RequireCompleteType(Loc, Class, diag::err_memptr_rhs_to_incomplete))
1829 return QualType();
1830
Sebastian Redl5822f082009-02-07 20:10:22 +00001831 // C++ 5.5p2
1832 // [...] to its first operand, which shall be of class T or of a class of
1833 // which T is an unambiguous and accessible base class. [p3: a pointer to
1834 // such a class]
1835 QualType LType = lex->getType();
1836 if (isIndirect) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001837 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl5822f082009-02-07 20:10:22 +00001838 LType = Ptr->getPointeeType().getNonReferenceType();
1839 else {
1840 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanian59f64202009-10-26 20:45:27 +00001841 << OpSpelling << 1 << LType
Douglas Gregora771f462010-03-31 17:46:05 +00001842 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00001843 return QualType();
1844 }
1845 }
1846
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001847 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001848 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1849 /*DetectVirtual=*/false);
Mike Stump87c57ac2009-05-16 07:39:55 +00001850 // FIXME: Would it be useful to print full ambiguity paths, or is that
1851 // overkill?
Sebastian Redl5822f082009-02-07 20:10:22 +00001852 if (!IsDerivedFrom(LType, Class, Paths) ||
1853 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1854 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman1fcf66b2010-01-16 00:00:48 +00001855 << (int)isIndirect << lex->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00001856 return QualType();
1857 }
Eli Friedman1fcf66b2010-01-16 00:00:48 +00001858 // Cast LHS to type of use.
1859 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
1860 bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid;
1861 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue);
Sebastian Redl5822f082009-02-07 20:10:22 +00001862 }
1863
Fariborz Jahanianfff3fb22009-11-18 22:16:17 +00001864 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00001865 // Diagnose use of pointer-to-member type which when used as
1866 // the functional cast in a pointer-to-member expression.
1867 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1868 return QualType();
1869 }
Sebastian Redl5822f082009-02-07 20:10:22 +00001870 // C++ 5.5p2
1871 // The result is an object or a function of the type specified by the
1872 // second operand.
1873 // The cv qualifiers are the union of those in the pointer and the left side,
1874 // in accordance with 5.5p5 and 5.2.5.
1875 // FIXME: This returns a dereferenced member function pointer as a normal
1876 // function type. However, the only operation valid on such functions is
Mike Stump87c57ac2009-05-16 07:39:55 +00001877 // calling them. There's also a GCC extension to get a function pointer to the
1878 // thing, which is another complication, because this type - unlike the type
1879 // that is the result of this expression - takes the class as the first
Sebastian Redl5822f082009-02-07 20:10:22 +00001880 // argument.
1881 // We probably need a "MemberFunctionClosureType" or something like that.
1882 QualType Result = MemPtr->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00001883 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl5822f082009-02-07 20:10:22 +00001884 return Result;
1885}
Sebastian Redl1a99f442009-04-16 17:51:27 +00001886
Sebastian Redl1a99f442009-04-16 17:51:27 +00001887/// \brief Try to convert a type to another according to C++0x 5.16p3.
1888///
1889/// This is part of the parameter validation for the ? operator. If either
1890/// value operand is a class type, the two operands are attempted to be
1891/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00001892/// It returns true if the program is ill-formed and has already been diagnosed
1893/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00001894static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1895 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00001896 bool &HaveConversion,
1897 QualType &ToType) {
1898 HaveConversion = false;
1899 ToType = To->getType();
1900
1901 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
1902 SourceLocation());
Sebastian Redl1a99f442009-04-16 17:51:27 +00001903 // C++0x 5.16p3
1904 // The process for determining whether an operand expression E1 of type T1
1905 // can be converted to match an operand expression E2 of type T2 is defined
1906 // as follows:
1907 // -- If E2 is an lvalue:
Douglas Gregorf9edf802010-03-26 20:59:55 +00001908 bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid);
1909 if (ToIsLvalue) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00001910 // E1 can be converted to match E2 if E1 can be implicitly converted to
1911 // type "lvalue reference to T2", subject to the constraint that in the
1912 // conversion the reference must bind directly to E1.
Douglas Gregor838fcc32010-03-26 20:14:36 +00001913 QualType T = Self.Context.getLValueReferenceType(ToType);
1914 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
1915
1916 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
1917 if (InitSeq.isDirectReferenceBinding()) {
1918 ToType = T;
1919 HaveConversion = true;
1920 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00001921 }
Douglas Gregor838fcc32010-03-26 20:14:36 +00001922
1923 if (InitSeq.isAmbiguous())
1924 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl1a99f442009-04-16 17:51:27 +00001925 }
John McCall65eb8792010-02-25 01:37:24 +00001926
Sebastian Redl1a99f442009-04-16 17:51:27 +00001927 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1928 // -- if E1 and E2 have class type, and the underlying class types are
1929 // the same or one is a base class of the other:
1930 QualType FTy = From->getType();
1931 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001932 const RecordType *FRec = FTy->getAs<RecordType>();
1933 const RecordType *TRec = TTy->getAs<RecordType>();
Douglas Gregor838fcc32010-03-26 20:14:36 +00001934 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
1935 Self.IsDerivedFrom(FTy, TTy);
1936 if (FRec && TRec &&
1937 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00001938 // E1 can be converted to match E2 if the class of T2 is the
1939 // same type as, or a base class of, the class of T1, and
1940 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00001941 if (FRec == TRec || FDerivedFromT) {
1942 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00001943 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
1944 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
1945 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
1946 HaveConversion = true;
1947 return false;
1948 }
1949
1950 if (InitSeq.isAmbiguous())
1951 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
1952 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00001953 }
Douglas Gregor838fcc32010-03-26 20:14:36 +00001954
1955 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00001956 }
Douglas Gregor838fcc32010-03-26 20:14:36 +00001957
1958 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1959 // implicitly converted to the type that expression E2 would have
Douglas Gregorf9edf802010-03-26 20:59:55 +00001960 // if E2 were converted to an rvalue (or the type it has, if E2 is
1961 // an rvalue).
1962 //
1963 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
1964 // to the array-to-pointer or function-to-pointer conversions.
1965 if (!TTy->getAs<TagType>())
1966 TTy = TTy.getUnqualifiedType();
Douglas Gregor838fcc32010-03-26 20:14:36 +00001967
1968 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
1969 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
1970 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
1971 ToType = TTy;
1972 if (InitSeq.isAmbiguous())
1973 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
1974
Sebastian Redl1a99f442009-04-16 17:51:27 +00001975 return false;
1976}
1977
1978/// \brief Try to find a common type for two according to C++0x 5.16p5.
1979///
1980/// This is part of the parameter validation for the ? operator. If either
1981/// value operand is a class type, overload resolution is used to find a
1982/// conversion to a common type.
1983static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1984 SourceLocation Loc) {
1985 Expr *Args[2] = { LHS, RHS };
John McCallbc077cf2010-02-08 23:07:23 +00001986 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00001987 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00001988
1989 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001990 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001991 case OR_Success:
Sebastian Redl1a99f442009-04-16 17:51:27 +00001992 // We found a match. Perform the conversions on the arguments and move on.
1993 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001994 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00001995 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001996 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl1a99f442009-04-16 17:51:27 +00001997 break;
1998 return false;
1999
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002000 case OR_No_Viable_Function:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002001 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2002 << LHS->getType() << RHS->getType()
2003 << LHS->getSourceRange() << RHS->getSourceRange();
2004 return true;
2005
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002006 case OR_Ambiguous:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002007 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2008 << LHS->getType() << RHS->getType()
2009 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00002010 // FIXME: Print the possible common types by printing the return types of
2011 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00002012 break;
2013
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002014 case OR_Deleted:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002015 assert(false && "Conditional operator has only built-in overloads");
2016 break;
2017 }
2018 return true;
2019}
2020
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002021/// \brief Perform an "extended" implicit conversion as returned by
2022/// TryClassUnification.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002023static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2024 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2025 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2026 SourceLocation());
2027 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
2028 Sema::OwningExprResult Result = InitSeq.Perform(Self, Entity, Kind,
2029 Sema::MultiExprArg(Self, (void **)&E, 1));
2030 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002031 return true;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002032
2033 E = Result.takeAs<Expr>();
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002034 return false;
2035}
2036
Sebastian Redl1a99f442009-04-16 17:51:27 +00002037/// \brief Check the operands of ?: under C++ semantics.
2038///
2039/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2040/// extension. In this case, LHS == Cond. (But they're not aliases.)
2041QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2042 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00002043 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2044 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00002045
2046 // C++0x 5.16p1
2047 // The first expression is contextually converted to bool.
2048 if (!Cond->isTypeDependent()) {
2049 if (CheckCXXBooleanCondition(Cond))
2050 return QualType();
2051 }
2052
2053 // Either of the arguments dependent?
2054 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2055 return Context.DependentTy;
2056
John McCall71d8d9b2010-03-11 19:43:18 +00002057 CheckSignCompare(LHS, RHS, QuestionLoc);
John McCall1fa36b72009-11-05 09:23:39 +00002058
Sebastian Redl1a99f442009-04-16 17:51:27 +00002059 // C++0x 5.16p2
2060 // If either the second or the third operand has type (cv) void, ...
2061 QualType LTy = LHS->getType();
2062 QualType RTy = RHS->getType();
2063 bool LVoid = LTy->isVoidType();
2064 bool RVoid = RTy->isVoidType();
2065 if (LVoid || RVoid) {
2066 // ... then the [l2r] conversions are performed on the second and third
2067 // operands ...
Douglas Gregorb92a1562010-02-03 00:27:59 +00002068 DefaultFunctionArrayLvalueConversion(LHS);
2069 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002070 LTy = LHS->getType();
2071 RTy = RHS->getType();
2072
2073 // ... and one of the following shall hold:
2074 // -- The second or the third operand (but not both) is a throw-
2075 // expression; the result is of the type of the other and is an rvalue.
2076 bool LThrow = isa<CXXThrowExpr>(LHS);
2077 bool RThrow = isa<CXXThrowExpr>(RHS);
2078 if (LThrow && !RThrow)
2079 return RTy;
2080 if (RThrow && !LThrow)
2081 return LTy;
2082
2083 // -- Both the second and third operands have type void; the result is of
2084 // type void and is an rvalue.
2085 if (LVoid && RVoid)
2086 return Context.VoidTy;
2087
2088 // Neither holds, error.
2089 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2090 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2091 << LHS->getSourceRange() << RHS->getSourceRange();
2092 return QualType();
2093 }
2094
2095 // Neither is void.
2096
2097 // C++0x 5.16p3
2098 // Otherwise, if the second and third operand have different types, and
2099 // either has (cv) class type, and attempt is made to convert each of those
2100 // operands to the other.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002101 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00002102 (LTy->isRecordType() || RTy->isRecordType())) {
2103 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2104 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002105 QualType L2RType, R2LType;
2106 bool HaveL2R, HaveR2L;
2107 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002108 return QualType();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002109 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002110 return QualType();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002111
Sebastian Redl1a99f442009-04-16 17:51:27 +00002112 // If both can be converted, [...] the program is ill-formed.
2113 if (HaveL2R && HaveR2L) {
2114 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2115 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2116 return QualType();
2117 }
2118
2119 // If exactly one conversion is possible, that conversion is applied to
2120 // the chosen operand and the converted operands are used in place of the
2121 // original operands for the remainder of this section.
2122 if (HaveL2R) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00002123 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002124 return QualType();
2125 LTy = LHS->getType();
2126 } else if (HaveR2L) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00002127 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002128 return QualType();
2129 RTy = RHS->getType();
2130 }
2131 }
2132
2133 // C++0x 5.16p4
2134 // If the second and third operands are lvalues and have the same type,
2135 // the result is of that type [...]
Douglas Gregor697a3912010-04-01 22:47:07 +00002136 bool Same = Context.hasSameType(LTy, RTy);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002137 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
2138 RHS->isLvalue(Context) == Expr::LV_Valid)
2139 return LTy;
2140
2141 // C++0x 5.16p5
2142 // Otherwise, the result is an rvalue. If the second and third operands
2143 // do not have the same type, and either has (cv) class type, ...
2144 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2145 // ... overload resolution is used to determine the conversions (if any)
2146 // to be applied to the operands. If the overload resolution fails, the
2147 // program is ill-formed.
2148 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2149 return QualType();
2150 }
2151
2152 // C++0x 5.16p6
2153 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2154 // conversions are performed on the second and third operands.
Douglas Gregorb92a1562010-02-03 00:27:59 +00002155 DefaultFunctionArrayLvalueConversion(LHS);
2156 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002157 LTy = LHS->getType();
2158 RTy = RHS->getType();
2159
2160 // After those conversions, one of the following shall hold:
2161 // -- The second and third operands have the same type; the result
2162 // is of that type.
2163 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
2164 return LTy;
2165
2166 // -- The second and third operands have arithmetic or enumeration type;
2167 // the usual arithmetic conversions are performed to bring them to a
2168 // common type, and the result is of that type.
2169 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2170 UsualArithmeticConversions(LHS, RHS);
2171 return LHS->getType();
2172 }
2173
2174 // -- The second and third operands have pointer type, or one has pointer
2175 // type and the other is a null pointer constant; pointer conversions
2176 // and qualification conversions are performed to bring them to their
2177 // composite pointer type. The result is of the composite pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00002178 // -- The second and third operands have pointer to member type, or one has
2179 // pointer to member type and the other is a null pointer constant;
2180 // pointer to member conversions and qualification conversions are
2181 // performed to bring them to a common type, whose cv-qualification
2182 // shall match the cv-qualification of either the second or the third
2183 // operand. The result is of the common type.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002184 bool NonStandardCompositeType = false;
2185 QualType Composite = FindCompositePointerType(LHS, RHS,
2186 isSFINAEContext()? 0 : &NonStandardCompositeType);
2187 if (!Composite.isNull()) {
2188 if (NonStandardCompositeType)
2189 Diag(QuestionLoc,
2190 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2191 << LTy << RTy << Composite
2192 << LHS->getSourceRange() << RHS->getSourceRange();
2193
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002194 return Composite;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002195 }
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00002196
Douglas Gregor697a3912010-04-01 22:47:07 +00002197 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00002198 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2199 if (!Composite.isNull())
2200 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00002201
Sebastian Redl1a99f442009-04-16 17:51:27 +00002202 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2203 << LHS->getType() << RHS->getType()
2204 << LHS->getSourceRange() << RHS->getSourceRange();
2205 return QualType();
2206}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002207
2208/// \brief Find a merged pointer type and convert the two expressions to it.
2209///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002210/// This finds the composite pointer type (or member pointer type) for @p E1
2211/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2212/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002213/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002214///
2215/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2216/// a non-standard (but still sane) composite type to which both expressions
2217/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2218/// will be set true.
2219QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2,
2220 bool *NonStandardCompositeType) {
2221 if (NonStandardCompositeType)
2222 *NonStandardCompositeType = false;
2223
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002224 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2225 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002226
Fariborz Jahanian33e148f2009-12-08 20:04:24 +00002227 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2228 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002229 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002230
2231 // C++0x 5.9p2
2232 // Pointer conversions and qualification conversions are performed on
2233 // pointer operands to bring them to their composite pointer type. If
2234 // one operand is a null pointer constant, the composite pointer type is
2235 // the type of the other operand.
Douglas Gregor56751b52009-09-25 04:25:58 +00002236 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002237 if (T2->isMemberPointerType())
2238 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
2239 else
2240 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002241 return T2;
2242 }
Douglas Gregor56751b52009-09-25 04:25:58 +00002243 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002244 if (T1->isMemberPointerType())
2245 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
2246 else
2247 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002248 return T1;
2249 }
Mike Stump11289f42009-09-09 15:08:12 +00002250
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002251 // Now both have to be pointers or member pointers.
Sebastian Redl658262f2009-11-16 21:03:45 +00002252 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2253 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002254 return QualType();
2255
2256 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2257 // the other has type "pointer to cv2 T" and the composite pointer type is
2258 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2259 // Otherwise, the composite pointer type is a pointer type similar to the
2260 // type of one of the operands, with a cv-qualification signature that is
2261 // the union of the cv-qualification signatures of the operand types.
2262 // In practice, the first part here is redundant; it's subsumed by the second.
2263 // What we do here is, we build the two possible composite types, and try the
2264 // conversions in both directions. If only one works, or if the two composite
2265 // types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00002266 // FIXME: extended qualifiers?
Sebastian Redl658262f2009-11-16 21:03:45 +00002267 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2268 QualifierVector QualifierUnion;
2269 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2270 ContainingClassVector;
2271 ContainingClassVector MemberOfClass;
2272 QualType Composite1 = Context.getCanonicalType(T1),
2273 Composite2 = Context.getCanonicalType(T2);
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002274 unsigned NeedConstBefore = 0;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002275 do {
2276 const PointerType *Ptr1, *Ptr2;
2277 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2278 (Ptr2 = Composite2->getAs<PointerType>())) {
2279 Composite1 = Ptr1->getPointeeType();
2280 Composite2 = Ptr2->getPointeeType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002281
2282 // If we're allowed to create a non-standard composite type, keep track
2283 // of where we need to fill in additional 'const' qualifiers.
2284 if (NonStandardCompositeType &&
2285 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2286 NeedConstBefore = QualifierUnion.size();
2287
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002288 QualifierUnion.push_back(
2289 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2290 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2291 continue;
2292 }
Mike Stump11289f42009-09-09 15:08:12 +00002293
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002294 const MemberPointerType *MemPtr1, *MemPtr2;
2295 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2296 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2297 Composite1 = MemPtr1->getPointeeType();
2298 Composite2 = MemPtr2->getPointeeType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002299
2300 // If we're allowed to create a non-standard composite type, keep track
2301 // of where we need to fill in additional 'const' qualifiers.
2302 if (NonStandardCompositeType &&
2303 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2304 NeedConstBefore = QualifierUnion.size();
2305
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002306 QualifierUnion.push_back(
2307 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2308 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2309 MemPtr2->getClass()));
2310 continue;
2311 }
Mike Stump11289f42009-09-09 15:08:12 +00002312
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002313 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00002314
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002315 // Cannot unwrap any more types.
2316 break;
2317 } while (true);
Mike Stump11289f42009-09-09 15:08:12 +00002318
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002319 if (NeedConstBefore && NonStandardCompositeType) {
2320 // Extension: Add 'const' to qualifiers that come before the first qualifier
2321 // mismatch, so that our (non-standard!) composite type meets the
2322 // requirements of C++ [conv.qual]p4 bullet 3.
2323 for (unsigned I = 0; I != NeedConstBefore; ++I) {
2324 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
2325 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
2326 *NonStandardCompositeType = true;
2327 }
2328 }
2329 }
2330
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002331 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redl658262f2009-11-16 21:03:45 +00002332 ContainingClassVector::reverse_iterator MOC
2333 = MemberOfClass.rbegin();
2334 for (QualifierVector::reverse_iterator
2335 I = QualifierUnion.rbegin(),
2336 E = QualifierUnion.rend();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002337 I != E; (void)++I, ++MOC) {
John McCall8ccfcb52009-09-24 19:53:00 +00002338 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002339 if (MOC->first && MOC->second) {
2340 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00002341 Composite1 = Context.getMemberPointerType(
2342 Context.getQualifiedType(Composite1, Quals),
2343 MOC->first);
2344 Composite2 = Context.getMemberPointerType(
2345 Context.getQualifiedType(Composite2, Quals),
2346 MOC->second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002347 } else {
2348 // Rebuild pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00002349 Composite1
2350 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2351 Composite2
2352 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002353 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002354 }
2355
Mike Stump11289f42009-09-09 15:08:12 +00002356 ImplicitConversionSequence E1ToC1 =
Anders Carlssonef4c7212009-08-27 17:24:15 +00002357 TryImplicitConversion(E1, Composite1,
2358 /*SuppressUserConversions=*/false,
2359 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00002360 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002361 ImplicitConversionSequence E2ToC1 =
Anders Carlssonef4c7212009-08-27 17:24:15 +00002362 TryImplicitConversion(E2, Composite1,
2363 /*SuppressUserConversions=*/false,
2364 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00002365 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002366
John McCall65eb8792010-02-25 01:37:24 +00002367 bool ToC2Viable = false;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002368 ImplicitConversionSequence E1ToC2, E2ToC2;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002369 if (Context.getCanonicalType(Composite1) !=
2370 Context.getCanonicalType(Composite2)) {
Anders Carlssonef4c7212009-08-27 17:24:15 +00002371 E1ToC2 = TryImplicitConversion(E1, Composite2,
2372 /*SuppressUserConversions=*/false,
2373 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00002374 /*InOverloadResolution=*/false);
Anders Carlssonef4c7212009-08-27 17:24:15 +00002375 E2ToC2 = TryImplicitConversion(E2, Composite2,
2376 /*SuppressUserConversions=*/false,
2377 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00002378 /*InOverloadResolution=*/false);
John McCall65eb8792010-02-25 01:37:24 +00002379 ToC2Viable = !E1ToC2.isBad() && !E2ToC2.isBad();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002380 }
2381
John McCall0d1da222010-01-12 00:44:57 +00002382 bool ToC1Viable = !E1ToC1.isBad() && !E2ToC1.isBad();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002383 if (ToC1Viable && !ToC2Viable) {
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002384 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, Sema::AA_Converting) &&
2385 !PerformImplicitConversion(E2, Composite1, E2ToC1, Sema::AA_Converting))
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002386 return Composite1;
2387 }
2388 if (ToC2Viable && !ToC1Viable) {
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002389 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, Sema::AA_Converting) &&
2390 !PerformImplicitConversion(E2, Composite2, E2ToC2, Sema::AA_Converting))
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002391 return Composite2;
2392 }
2393 return QualType();
2394}
Anders Carlsson85a307d2009-05-17 18:41:29 +00002395
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002396Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlssonf86a8d12009-08-15 23:41:35 +00002397 if (!Context.getLangOptions().CPlusPlus)
2398 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00002399
Douglas Gregor363b1512009-12-24 18:51:59 +00002400 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2401
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002402 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002403 if (!RT)
2404 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00002405
John McCall67da35c2010-02-04 22:26:26 +00002406 // If this is the result of a call expression, our source might
2407 // actually be a reference, in which case we shouldn't bind.
Anders Carlssonaedb46f2009-09-14 01:30:44 +00002408 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2409 QualType Ty = CE->getCallee()->getType();
2410 if (const PointerType *PT = Ty->getAs<PointerType>())
2411 Ty = PT->getPointeeType();
Fariborz Jahanianffcfecd2010-02-18 20:31:02 +00002412 else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>())
2413 Ty = BPT->getPointeeType();
2414
John McCall9dd450b2009-09-21 23:43:11 +00002415 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlssonaedb46f2009-09-14 01:30:44 +00002416 if (FTy->getResultType()->isReferenceType())
2417 return Owned(E);
2418 }
John McCall67da35c2010-02-04 22:26:26 +00002419
2420 // That should be enough to guarantee that this type is complete.
2421 // If it has a trivial destructor, we can avoid the extra copy.
2422 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2423 if (RD->hasTrivialDestructor())
2424 return Owned(E);
2425
Mike Stump11289f42009-09-09 15:08:12 +00002426 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002427 RD->getDestructor(Context));
Anders Carlssonc78576e2009-05-30 21:21:49 +00002428 ExprTemporaries.push_back(Temp);
Fariborz Jahanian67828442009-08-03 19:13:25 +00002429 if (CXXDestructorDecl *Destructor =
John McCall8e36d532010-04-07 00:41:46 +00002430 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context))) {
Fariborz Jahanian67828442009-08-03 19:13:25 +00002431 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00002432 CheckDestructorAccess(E->getExprLoc(), Destructor,
2433 PDiag(diag::err_access_dtor_temp)
2434 << E->getType());
2435 }
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002436 // FIXME: Add the temporary to the temporaries vector.
2437 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2438}
2439
Anders Carlsson6e997b22009-12-15 20:51:39 +00002440Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002441 assert(SubExpr && "sub expression can't be null!");
Mike Stump11289f42009-09-09 15:08:12 +00002442
Douglas Gregor580cd4a2009-12-03 17:10:37 +00002443 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2444 assert(ExprTemporaries.size() >= FirstTemporary);
2445 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002446 return SubExpr;
Mike Stump11289f42009-09-09 15:08:12 +00002447
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002448 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor580cd4a2009-12-03 17:10:37 +00002449 &ExprTemporaries[FirstTemporary],
Anders Carlsson6e997b22009-12-15 20:51:39 +00002450 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor580cd4a2009-12-03 17:10:37 +00002451 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2452 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00002453
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002454 return E;
2455}
2456
Douglas Gregorb6ea6082009-12-22 22:17:25 +00002457Sema::OwningExprResult
2458Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2459 if (SubExpr.isInvalid())
2460 return ExprError();
2461
2462 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2463}
2464
Anders Carlssonafb2dad2009-12-16 02:09:40 +00002465FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2466 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2467 assert(ExprTemporaries.size() >= FirstTemporary);
2468
2469 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2470 CXXTemporary **Temporaries =
2471 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2472
2473 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2474
2475 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2476 ExprTemporaries.end());
2477
2478 return E;
2479}
2480
Mike Stump11289f42009-09-09 15:08:12 +00002481Sema::OwningExprResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002482Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
Douglas Gregore610ada2010-02-24 18:44:31 +00002483 tok::TokenKind OpKind, TypeTy *&ObjectType,
2484 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002485 // Since this might be a postfix expression, get rid of ParenListExprs.
2486 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump11289f42009-09-09 15:08:12 +00002487
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002488 Expr *BaseExpr = (Expr*)Base.get();
2489 assert(BaseExpr && "no record expansion");
Mike Stump11289f42009-09-09 15:08:12 +00002490
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002491 QualType BaseType = BaseExpr->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00002492 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002493 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00002494 // If we have a pointer to a dependent type and are using the -> operator,
2495 // the object type is the type that the pointer points to. We might still
2496 // have enough information about that type to do something useful.
2497 if (OpKind == tok::arrow)
2498 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2499 BaseType = Ptr->getPointeeType();
2500
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002501 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregore610ada2010-02-24 18:44:31 +00002502 MayBePseudoDestructor = true;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002503 return move(Base);
2504 }
Mike Stump11289f42009-09-09 15:08:12 +00002505
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002506 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00002507 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002508 // returned, with the original second operand.
2509 if (OpKind == tok::arrow) {
John McCallc1538c02009-09-30 01:01:30 +00002510 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00002511 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002512 llvm::SmallVector<SourceLocation, 8> Locations;
John McCallbd0465b2009-09-30 01:30:54 +00002513 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc1538c02009-09-30 01:01:30 +00002514
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002515 while (BaseType->isRecordType()) {
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00002516 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002517 BaseExpr = (Expr*)Base.get();
2518 if (BaseExpr == NULL)
2519 return ExprError();
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002520 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonfbd2d492009-10-13 22:55:59 +00002521 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc1538c02009-09-30 01:01:30 +00002522 BaseType = BaseExpr->getType();
2523 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCallbd0465b2009-09-30 01:30:54 +00002524 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00002525 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002526 for (unsigned i = 0; i < Locations.size(); i++)
2527 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00002528 return ExprError();
2529 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002530 }
Mike Stump11289f42009-09-09 15:08:12 +00002531
Douglas Gregore4f764f2009-11-20 19:58:21 +00002532 if (BaseType->isPointerType())
2533 BaseType = BaseType->getPointeeType();
2534 }
Mike Stump11289f42009-09-09 15:08:12 +00002535
2536 // We could end up with various non-record types here, such as extended
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002537 // vector types or Objective-C interfaces. Just return early and let
2538 // ActOnMemberReferenceExpr do the work.
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002539 if (!BaseType->isRecordType()) {
2540 // C++ [basic.lookup.classref]p2:
2541 // [...] If the type of the object expression is of pointer to scalar
2542 // type, the unqualified-id is looked up in the context of the complete
2543 // postfix-expression.
Douglas Gregore610ada2010-02-24 18:44:31 +00002544 //
2545 // This also indicates that we should be parsing a
2546 // pseudo-destructor-name.
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002547 ObjectType = 0;
Douglas Gregore610ada2010-02-24 18:44:31 +00002548 MayBePseudoDestructor = true;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002549 return move(Base);
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002550 }
Mike Stump11289f42009-09-09 15:08:12 +00002551
Douglas Gregor3fad6172009-11-17 05:17:33 +00002552 // The object type must be complete (or dependent).
2553 if (!BaseType->isDependentType() &&
2554 RequireCompleteType(OpLoc, BaseType,
2555 PDiag(diag::err_incomplete_member_access)))
2556 return ExprError();
2557
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002558 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002559 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00002560 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002561 // type C (or of pointer to a class type C), the unqualified-id is looked
2562 // up in the scope of class C. [...]
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002563 ObjectType = BaseType.getAsOpaquePtr();
Mike Stump11289f42009-09-09 15:08:12 +00002564 return move(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002565}
2566
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002567Sema::OwningExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
2568 ExprArg MemExpr) {
2569 Expr *E = (Expr *) MemExpr.get();
2570 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
2571 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2572 << isa<CXXPseudoDestructorExpr>(E)
Douglas Gregora771f462010-03-31 17:46:05 +00002573 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002574
2575 return ActOnCallExpr(/*Scope*/ 0,
2576 move(MemExpr),
2577 /*LPLoc*/ ExpectedLParenLoc,
2578 Sema::MultiExprArg(*this, 0, 0),
2579 /*CommaLocs*/ 0,
2580 /*RPLoc*/ ExpectedLParenLoc);
2581}
Douglas Gregore610ada2010-02-24 18:44:31 +00002582
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002583Sema::OwningExprResult Sema::BuildPseudoDestructorExpr(ExprArg Base,
2584 SourceLocation OpLoc,
2585 tok::TokenKind OpKind,
2586 const CXXScopeSpec &SS,
Douglas Gregor651fe5e2010-02-24 23:40:28 +00002587 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002588 SourceLocation CCLoc,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00002589 SourceLocation TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002590 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002591 bool HasTrailingLParen) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00002592 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002593
2594 // C++ [expr.pseudo]p2:
2595 // The left-hand side of the dot operator shall be of scalar type. The
2596 // left-hand side of the arrow operator shall be of pointer to scalar type.
2597 // This scalar type is the object type.
2598 Expr *BaseE = (Expr *)Base.get();
2599 QualType ObjectType = BaseE->getType();
2600 if (OpKind == tok::arrow) {
2601 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2602 ObjectType = Ptr->getPointeeType();
2603 } else if (!BaseE->isTypeDependent()) {
2604 // The user wrote "p->" when she probably meant "p."; fix it.
2605 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2606 << ObjectType << true
Douglas Gregora771f462010-03-31 17:46:05 +00002607 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002608 if (isSFINAEContext())
2609 return ExprError();
2610
2611 OpKind = tok::period;
2612 }
2613 }
2614
2615 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
2616 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2617 << ObjectType << BaseE->getSourceRange();
2618 return ExprError();
2619 }
2620
2621 // C++ [expr.pseudo]p2:
2622 // [...] The cv-unqualified versions of the object type and of the type
2623 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00002624 if (DestructedTypeInfo) {
2625 QualType DestructedType = DestructedTypeInfo->getType();
2626 SourceLocation DestructedTypeStart
2627 = DestructedTypeInfo->getTypeLoc().getSourceRange().getBegin();
2628 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
2629 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
2630 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
2631 << ObjectType << DestructedType << BaseE->getSourceRange()
2632 << DestructedTypeInfo->getTypeLoc().getSourceRange();
2633
2634 // Recover by setting the destructed type to the object type.
2635 DestructedType = ObjectType;
2636 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
2637 DestructedTypeStart);
2638 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2639 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002640 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00002641
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002642 // C++ [expr.pseudo]p2:
2643 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
2644 // form
2645 //
2646 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
2647 //
2648 // shall designate the same scalar type.
2649 if (ScopeTypeInfo) {
2650 QualType ScopeType = ScopeTypeInfo->getType();
2651 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
2652 !Context.hasSameType(ScopeType, ObjectType)) {
2653
2654 Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(),
2655 diag::err_pseudo_dtor_type_mismatch)
2656 << ObjectType << ScopeType << BaseE->getSourceRange()
2657 << ScopeTypeInfo->getTypeLoc().getSourceRange();
2658
2659 ScopeType = QualType();
2660 ScopeTypeInfo = 0;
2661 }
2662 }
2663
2664 OwningExprResult Result
2665 = Owned(new (Context) CXXPseudoDestructorExpr(Context,
2666 Base.takeAs<Expr>(),
2667 OpKind == tok::arrow,
2668 OpLoc,
2669 (NestedNameSpecifier *) SS.getScopeRep(),
2670 SS.getRange(),
2671 ScopeTypeInfo,
2672 CCLoc,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00002673 TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002674 Destructed));
2675
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002676 if (HasTrailingLParen)
2677 return move(Result);
2678
Douglas Gregor678f90d2010-02-25 01:56:36 +00002679 return DiagnoseDtorReference(Destructed.getLocation(), move(Result));
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002680}
2681
2682Sema::OwningExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, ExprArg Base,
2683 SourceLocation OpLoc,
2684 tok::TokenKind OpKind,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002685 CXXScopeSpec &SS,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002686 UnqualifiedId &FirstTypeName,
2687 SourceLocation CCLoc,
2688 SourceLocation TildeLoc,
2689 UnqualifiedId &SecondTypeName,
2690 bool HasTrailingLParen) {
2691 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2692 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2693 "Invalid first type name in pseudo-destructor");
2694 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2695 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2696 "Invalid second type name in pseudo-destructor");
2697
2698 Expr *BaseE = (Expr *)Base.get();
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002699
2700 // C++ [expr.pseudo]p2:
2701 // The left-hand side of the dot operator shall be of scalar type. The
2702 // left-hand side of the arrow operator shall be of pointer to scalar type.
2703 // This scalar type is the object type.
2704 QualType ObjectType = BaseE->getType();
2705 if (OpKind == tok::arrow) {
2706 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2707 ObjectType = Ptr->getPointeeType();
Douglas Gregor678f90d2010-02-25 01:56:36 +00002708 } else if (!ObjectType->isDependentType()) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002709 // The user wrote "p->" when she probably meant "p."; fix it.
2710 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregor678f90d2010-02-25 01:56:36 +00002711 << ObjectType << true
Douglas Gregora771f462010-03-31 17:46:05 +00002712 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002713 if (isSFINAEContext())
2714 return ExprError();
2715
2716 OpKind = tok::period;
2717 }
2718 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00002719
2720 // Compute the object type that we should use for name lookup purposes. Only
2721 // record types and dependent types matter.
2722 void *ObjectTypePtrForLookup = 0;
2723 if (!SS.isSet()) {
2724 ObjectTypePtrForLookup = (void *)ObjectType->getAs<RecordType>();
2725 if (!ObjectTypePtrForLookup && ObjectType->isDependentType())
2726 ObjectTypePtrForLookup = Context.DependentTy.getAsOpaquePtr();
2727 }
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002728
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002729 // Convert the name of the type being destructed (following the ~) into a
2730 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002731 QualType DestructedType;
2732 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregor678f90d2010-02-25 01:56:36 +00002733 PseudoDestructorTypeStorage Destructed;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002734 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2735 TypeTy *T = getTypeName(*SecondTypeName.Identifier,
2736 SecondTypeName.StartLocation,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002737 S, &SS, true, ObjectTypePtrForLookup);
2738 if (!T &&
2739 ((SS.isSet() && !computeDeclContext(SS, false)) ||
2740 (!SS.isSet() && ObjectType->isDependentType()))) {
2741 // The name of the type being destroyed is a dependent name, and we
2742 // couldn't find anything useful in scope. Just store the identifier and
2743 // it's location, and we'll perform (qualified) name lookup again at
2744 // template instantiation time.
2745 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
2746 SecondTypeName.StartLocation);
2747 } else if (!T) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002748 Diag(SecondTypeName.StartLocation,
2749 diag::err_pseudo_dtor_destructor_non_type)
2750 << SecondTypeName.Identifier << ObjectType;
2751 if (isSFINAEContext())
2752 return ExprError();
2753
2754 // Recover by assuming we had the right type all along.
2755 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002756 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002757 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002758 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002759 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002760 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002761 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2762 TemplateId->getTemplateArgs(),
2763 TemplateId->NumArgs);
2764 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2765 TemplateId->TemplateNameLoc,
2766 TemplateId->LAngleLoc,
2767 TemplateArgsPtr,
2768 TemplateId->RAngleLoc);
2769 if (T.isInvalid() || !T.get()) {
2770 // Recover by assuming we had the right type all along.
2771 DestructedType = ObjectType;
2772 } else
2773 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002774 }
2775
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002776 // If we've performed some kind of recovery, (re-)build the type source
2777 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00002778 if (!DestructedType.isNull()) {
2779 if (!DestructedTypeInfo)
2780 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002781 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00002782 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2783 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002784
2785 // Convert the name of the scope type (the type prior to '::') into a type.
2786 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002787 QualType ScopeType;
2788 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2789 FirstTypeName.Identifier) {
2790 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2791 TypeTy *T = getTypeName(*FirstTypeName.Identifier,
2792 FirstTypeName.StartLocation,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002793 S, &SS, false, ObjectTypePtrForLookup);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002794 if (!T) {
2795 Diag(FirstTypeName.StartLocation,
2796 diag::err_pseudo_dtor_destructor_non_type)
2797 << FirstTypeName.Identifier << ObjectType;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002798
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002799 if (isSFINAEContext())
2800 return ExprError();
2801
2802 // Just drop this type. It's unnecessary anyway.
2803 ScopeType = QualType();
2804 } else
2805 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002806 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002807 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002808 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002809 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2810 TemplateId->getTemplateArgs(),
2811 TemplateId->NumArgs);
2812 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2813 TemplateId->TemplateNameLoc,
2814 TemplateId->LAngleLoc,
2815 TemplateArgsPtr,
2816 TemplateId->RAngleLoc);
2817 if (T.isInvalid() || !T.get()) {
2818 // Recover by dropping this type.
2819 ScopeType = QualType();
2820 } else
2821 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002822 }
2823 }
Douglas Gregor90ad9222010-02-24 23:02:30 +00002824
2825 if (!ScopeType.isNull() && !ScopeTypeInfo)
2826 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
2827 FirstTypeName.StartLocation);
2828
2829
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002830 return BuildPseudoDestructorExpr(move(Base), OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00002831 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002832 Destructed, HasTrailingLParen);
Douglas Gregore610ada2010-02-24 18:44:31 +00002833}
2834
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00002835CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
John McCall16df1e52010-03-30 21:47:33 +00002836 NamedDecl *FoundDecl,
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00002837 CXXMethodDecl *Method) {
John McCall16df1e52010-03-30 21:47:33 +00002838 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
2839 FoundDecl, Method))
Eli Friedmanf7195532009-12-09 04:53:56 +00002840 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
2841
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00002842 MemberExpr *ME =
2843 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2844 SourceLocation(), Method->getType());
Eli Friedmanf7195532009-12-09 04:53:56 +00002845 QualType ResultType = Method->getResultType().getNonReferenceType();
Douglas Gregor27381f32009-11-23 12:27:39 +00002846 MarkDeclarationReferenced(Exp->getLocStart(), Method);
2847 CXXMemberCallExpr *CE =
2848 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
2849 Exp->getLocEnd());
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00002850 return CE;
2851}
2852
Anders Carlssone9766d52009-09-09 21:33:21 +00002853Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2854 QualType Ty,
2855 CastExpr::CastKind Kind,
2856 CXXMethodDecl *Method,
2857 ExprArg Arg) {
2858 Expr *From = Arg.takeAs<Expr>();
2859
2860 switch (Kind) {
2861 default: assert(0 && "Unhandled cast kind!");
2862 case CastExpr::CK_ConstructorConversion: {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00002863 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2864
2865 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2866 MultiExprArg(*this, (void **)&From, 1),
2867 CastLoc, ConstructorArgs))
2868 return ExprError();
Anders Carlsson8f741bf2009-10-18 21:20:14 +00002869
2870 OwningExprResult Result =
2871 BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2872 move_arg(ConstructorArgs));
2873 if (Result.isInvalid())
2874 return ExprError();
2875
2876 return MaybeBindToTemporary(Result.takeAs<Expr>());
Anders Carlssone9766d52009-09-09 21:33:21 +00002877 }
2878
2879 case CastExpr::CK_UserDefinedConversion: {
Anders Carlsson6b2737d2009-09-15 07:42:44 +00002880 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
Eli Friedmanf7195532009-12-09 04:53:56 +00002881
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00002882 // Create an implicit call expr that calls it.
John McCall16df1e52010-03-30 21:47:33 +00002883 // FIXME: pass the FoundDecl for the user-defined conversion here
2884 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method, Method);
Anders Carlsson8f741bf2009-10-18 21:20:14 +00002885 return MaybeBindToTemporary(CE);
Anders Carlssone9766d52009-09-09 21:33:21 +00002886 }
Anders Carlssone9766d52009-09-09 21:33:21 +00002887 }
2888}
2889
Anders Carlsson85a307d2009-05-17 18:41:29 +00002890Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2891 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002892 if (FullExpr)
Anders Carlsson6e997b22009-12-15 20:51:39 +00002893 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Anders Carlsson7e3f0e42009-08-25 23:46:41 +00002894
Anders Carlsson85a307d2009-05-17 18:41:29 +00002895 return Owned(FullExpr);
2896}