blob: 8aa8ba57d9947b15afc3cfac772a039a64315609 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
Douglas Gregore737f502010-08-12 20:07:10 +000014#include "clang/Sema/Sema.h"
15#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
Steve Naroff210679c2007-08-25 14:02:58 +000017#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000019#include "clang/AST/ExprCXX.h"
Fariborz Jahaniand4266622010-06-16 18:56:04 +000020#include "clang/AST/ExprObjC.h"
Douglas Gregorb57fb492010-02-24 22:38:50 +000021#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000022#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000023#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000024#include "clang/Lex/Preprocessor.h"
John McCall19510852010-08-20 18:27:03 +000025#include "clang/Sema/DeclSpec.h"
26#include "clang/Sema/ParsedTemplate.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000027#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000028using namespace clang;
29
John McCallb3d87482010-08-24 05:47:05 +000030ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
31 IdentifierInfo &II,
32 SourceLocation NameLoc,
33 Scope *S, CXXScopeSpec &SS,
34 ParsedType ObjectTypePtr,
35 bool EnteringContext) {
Douglas Gregor124b8782010-02-16 19:09:40 +000036 // Determine where to perform name lookup.
37
38 // FIXME: This area of the standard is very messy, and the current
39 // wording is rather unclear about which scopes we search for the
40 // destructor name; see core issues 399 and 555. Issue 399 in
41 // particular shows where the current description of destructor name
42 // lookup is completely out of line with existing practice, e.g.,
43 // this appears to be ill-formed:
44 //
45 // namespace N {
46 // template <typename T> struct S {
47 // ~S();
48 // };
49 // }
50 //
51 // void f(N::S<int>* s) {
52 // s->N::S<int>::~S();
53 // }
54 //
Douglas Gregor93649fd2010-02-23 00:15:22 +000055 // See also PR6358 and PR6359.
Sebastian Redlc0fee502010-07-07 23:17:38 +000056 // For this reason, we're currently only doing the C++03 version of this
57 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregor124b8782010-02-16 19:09:40 +000058 QualType SearchType;
59 DeclContext *LookupCtx = 0;
60 bool isDependent = false;
61 bool LookInScope = false;
62
63 // If we have an object type, it's because we are in a
64 // pseudo-destructor-expression or a member access expression, and
65 // we know what type we're looking for.
66 if (ObjectTypePtr)
67 SearchType = GetTypeFromParser(ObjectTypePtr);
68
69 if (SS.isSet()) {
Douglas Gregor93649fd2010-02-23 00:15:22 +000070 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
71
72 bool AlreadySearched = false;
73 bool LookAtPrefix = true;
Sebastian Redlc0fee502010-07-07 23:17:38 +000074 // C++ [basic.lookup.qual]p6:
75 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
76 // the type-names are looked up as types in the scope designated by the
77 // nested-name-specifier. In a qualified-id of the form:
78 //
79 // ::[opt] nested-name-specifier ̃ class-name
80 //
81 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth5e895a82010-02-21 10:19:54 +000082 // a qualified-id of the form:
Douglas Gregor124b8782010-02-16 19:09:40 +000083 //
Sebastian Redlc0fee502010-07-07 23:17:38 +000084 // ::opt nested-name-specifier class-name :: ̃ class-name
Douglas Gregor124b8782010-02-16 19:09:40 +000085 //
Sebastian Redlc0fee502010-07-07 23:17:38 +000086 // the class-names are looked up as types in the scope designated by
87 // the nested-name-specifier.
Douglas Gregor124b8782010-02-16 19:09:40 +000088 //
Sebastian Redlc0fee502010-07-07 23:17:38 +000089 // Here, we check the first case (completely) and determine whether the
90 // code below is permitted to look at the prefix of the
91 // nested-name-specifier.
92 DeclContext *DC = computeDeclContext(SS, EnteringContext);
93 if (DC && DC->isFileContext()) {
94 AlreadySearched = true;
95 LookupCtx = DC;
96 isDependent = false;
97 } else if (DC && isa<CXXRecordDecl>(DC))
98 LookAtPrefix = false;
99
100 // The second case from the C++03 rules quoted further above.
Douglas Gregor93649fd2010-02-23 00:15:22 +0000101 NestedNameSpecifier *Prefix = 0;
102 if (AlreadySearched) {
103 // Nothing left to do.
104 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
105 CXXScopeSpec PrefixSS;
106 PrefixSS.setScopeRep(Prefix);
107 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
108 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000109 } else if (ObjectTypePtr) {
Douglas Gregor124b8782010-02-16 19:09:40 +0000110 LookupCtx = computeDeclContext(SearchType);
111 isDependent = SearchType->isDependentType();
112 } else {
113 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000114 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregor124b8782010-02-16 19:09:40 +0000115 }
Douglas Gregor93649fd2010-02-23 00:15:22 +0000116
Douglas Gregoredc90502010-02-25 04:46:04 +0000117 LookInScope = false;
Douglas Gregor124b8782010-02-16 19:09:40 +0000118 } else if (ObjectTypePtr) {
119 // C++ [basic.lookup.classref]p3:
120 // If the unqualified-id is ~type-name, the type-name is looked up
121 // in the context of the entire postfix-expression. If the type T
122 // of the object expression is of a class type C, the type-name is
123 // also looked up in the scope of class C. At least one of the
124 // lookups shall find a name that refers to (possibly
125 // cv-qualified) T.
126 LookupCtx = computeDeclContext(SearchType);
127 isDependent = SearchType->isDependentType();
128 assert((isDependent || !SearchType->isIncompleteType()) &&
129 "Caller should have completed object type");
130
131 LookInScope = true;
132 } else {
133 // Perform lookup into the current scope (only).
134 LookInScope = true;
135 }
136
137 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
138 for (unsigned Step = 0; Step != 2; ++Step) {
139 // Look for the name first in the computed lookup context (if we
140 // have one) and, if that fails to find a match, in the sope (if
141 // we're allowed to look there).
142 Found.clear();
143 if (Step == 0 && LookupCtx)
144 LookupQualifiedName(Found, LookupCtx);
Douglas Gregora2e7dd22010-02-25 01:56:36 +0000145 else if (Step == 1 && LookInScope && S)
Douglas Gregor124b8782010-02-16 19:09:40 +0000146 LookupName(Found, S);
147 else
148 continue;
149
150 // FIXME: Should we be suppressing ambiguities here?
151 if (Found.isAmbiguous())
John McCallb3d87482010-08-24 05:47:05 +0000152 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000153
154 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
155 QualType T = Context.getTypeDeclType(Type);
Douglas Gregor124b8782010-02-16 19:09:40 +0000156
157 if (SearchType.isNull() || SearchType->isDependentType() ||
158 Context.hasSameUnqualifiedType(T, SearchType)) {
159 // We found our type!
160
John McCallb3d87482010-08-24 05:47:05 +0000161 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000162 }
163 }
164
165 // If the name that we found is a class template name, and it is
166 // the same name as the template name in the last part of the
167 // nested-name-specifier (if present) or the object type, then
168 // this is the destructor for that class.
169 // FIXME: This is a workaround until we get real drafting for core
170 // issue 399, for which there isn't even an obvious direction.
171 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
172 QualType MemberOfType;
173 if (SS.isSet()) {
174 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
175 // Figure out the type of the context, if it has one.
John McCall3cb0ebd2010-03-10 03:28:59 +0000176 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
177 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregor124b8782010-02-16 19:09:40 +0000178 }
179 }
180 if (MemberOfType.isNull())
181 MemberOfType = SearchType;
182
183 if (MemberOfType.isNull())
184 continue;
185
186 // We're referring into a class template specialization. If the
187 // class template we found is the same as the template being
188 // specialized, we found what we are looking for.
189 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
190 if (ClassTemplateSpecializationDecl *Spec
191 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
192 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
193 Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000194 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000195 }
196
197 continue;
198 }
199
200 // We're referring to an unresolved class template
201 // specialization. Determine whether we class template we found
202 // is the same as the template being specialized or, if we don't
203 // know which template is being specialized, that it at least
204 // has the same name.
205 if (const TemplateSpecializationType *SpecType
206 = MemberOfType->getAs<TemplateSpecializationType>()) {
207 TemplateName SpecName = SpecType->getTemplateName();
208
209 // The class template we found is the same template being
210 // specialized.
211 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
212 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000213 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000214
215 continue;
216 }
217
218 // The class template we found has the same name as the
219 // (dependent) template name being specialized.
220 if (DependentTemplateName *DepTemplate
221 = SpecName.getAsDependentTemplateName()) {
222 if (DepTemplate->isIdentifier() &&
223 DepTemplate->getIdentifier() == Template->getIdentifier())
John McCallb3d87482010-08-24 05:47:05 +0000224 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000225
226 continue;
227 }
228 }
229 }
230 }
231
232 if (isDependent) {
233 // We didn't find our type, but that's okay: it's dependent
234 // anyway.
235 NestedNameSpecifier *NNS = 0;
236 SourceRange Range;
237 if (SS.isSet()) {
238 NNS = (NestedNameSpecifier *)SS.getScopeRep();
239 Range = SourceRange(SS.getRange().getBegin(), NameLoc);
240 } else {
241 NNS = NestedNameSpecifier::Create(Context, &II);
242 Range = SourceRange(NameLoc);
243 }
244
John McCallb3d87482010-08-24 05:47:05 +0000245 QualType T = CheckTypenameType(ETK_None, NNS, II,
246 SourceLocation(),
247 Range, NameLoc);
248 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000249 }
250
251 if (ObjectTypePtr)
252 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
253 << &II;
254 else
255 Diag(NameLoc, diag::err_destructor_class_name);
256
John McCallb3d87482010-08-24 05:47:05 +0000257 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000258}
259
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000260/// \brief Build a C++ typeid expression with a type operand.
261Sema::OwningExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
262 SourceLocation TypeidLoc,
263 TypeSourceInfo *Operand,
264 SourceLocation RParenLoc) {
265 // C++ [expr.typeid]p4:
266 // The top-level cv-qualifiers of the lvalue expression or the type-id
267 // that is the operand of typeid are always ignored.
268 // If the type of the type-id is a class type or a reference to a class
269 // type, the class shall be completely-defined.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000270 Qualifiers Quals;
271 QualType T
272 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
273 Quals);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000274 if (T->getAs<RecordType>() &&
275 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
276 return ExprError();
Daniel Dunbar380c2132010-05-11 21:32:35 +0000277
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000278 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
279 Operand,
280 SourceRange(TypeidLoc, RParenLoc)));
281}
282
283/// \brief Build a C++ typeid expression with an expression operand.
284Sema::OwningExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
285 SourceLocation TypeidLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000286 Expr *E,
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000287 SourceLocation RParenLoc) {
288 bool isUnevaluatedOperand = true;
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000289 if (E && !E->isTypeDependent()) {
290 QualType T = E->getType();
291 if (const RecordType *RecordT = T->getAs<RecordType>()) {
292 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
293 // C++ [expr.typeid]p3:
294 // [...] If the type of the expression is a class type, the class
295 // shall be completely-defined.
296 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
297 return ExprError();
298
299 // C++ [expr.typeid]p3:
Sebastian Redl906082e2010-07-20 04:20:21 +0000300 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000301 // polymorphic class type [...] [the] expression is an unevaluated
302 // operand. [...]
Sebastian Redl906082e2010-07-20 04:20:21 +0000303 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000304 isUnevaluatedOperand = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000305
306 // We require a vtable to query the type at run time.
307 MarkVTableUsed(TypeidLoc, RecordD);
308 }
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000309 }
310
311 // C++ [expr.typeid]p4:
312 // [...] If the type of the type-id is a reference to a possibly
313 // cv-qualified type, the result of the typeid expression refers to a
314 // std::type_info object representing the cv-unqualified referenced
315 // type.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000316 Qualifiers Quals;
317 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
318 if (!Context.hasSameType(T, UnqualT)) {
319 T = UnqualT;
Sebastian Redl906082e2010-07-20 04:20:21 +0000320 ImpCastExprToType(E, UnqualT, CastExpr::CK_NoOp, CastCategory(E));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000321 }
322 }
323
324 // If this is an unevaluated operand, clear out the set of
325 // declaration references we have been computing and eliminate any
326 // temporaries introduced in its computation.
327 if (isUnevaluatedOperand)
328 ExprEvalContexts.back().Context = Unevaluated;
329
330 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCall9ae2f072010-08-23 23:25:46 +0000331 E,
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000332 SourceRange(TypeidLoc, RParenLoc)));
333}
334
335/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000336Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000337Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
338 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000339 // Find the std::type_info type.
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000340 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000341 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000342
Chris Lattner572af492008-11-20 05:51:55 +0000343 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCalla24dc2e2009-11-17 02:14:36 +0000344 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +0000345 LookupQualifiedName(R, getStdNamespace());
John McCall1bcee0a2009-12-02 08:25:40 +0000346 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
Chris Lattner572af492008-11-20 05:51:55 +0000347 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000348 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000349
Sebastian Redlc42e1182008-11-11 11:37:55 +0000350 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000351
352 if (isType) {
353 // The operand is a type; handle it as such.
354 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +0000355 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
356 &TInfo);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000357 if (T.isNull())
358 return ExprError();
359
360 if (!TInfo)
361 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000362
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000363 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000364 }
Mike Stump1eb44332009-09-09 15:08:12 +0000365
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000366 // The operand is an expression.
John McCall9ae2f072010-08-23 23:25:46 +0000367 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000368}
369
Steve Naroff1b273c42007-09-16 14:56:35 +0000370/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000371Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000372Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000373 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000374 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000375 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
376 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000377}
Chris Lattner50dd2892008-02-26 00:51:44 +0000378
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000379/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
380Action::OwningExprResult
381Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
382 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
383}
384
Chris Lattner50dd2892008-02-26 00:51:44 +0000385/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000386Action::OwningExprResult
John McCall9ae2f072010-08-23 23:25:46 +0000387Sema::ActOnCXXThrow(SourceLocation OpLoc, Expr *Ex) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000388 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
389 return ExprError();
390 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
391}
392
393/// CheckCXXThrowOperand - Validate the operand of a throw.
394bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
395 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000396 // A throw-expression initializes a temporary object, called the exception
397 // object, the type of which is determined by removing any top-level
398 // cv-qualifiers from the static type of the operand of throw and adjusting
399 // the type from "array of T" or "function returning T" to "pointer to T"
400 // or "pointer to function returning T", [...]
401 if (E->getType().hasQualifiers())
402 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp,
Sebastian Redl906082e2010-07-20 04:20:21 +0000403 CastCategory(E));
Douglas Gregor154fe982009-12-23 22:04:40 +0000404
Sebastian Redl972041f2009-04-27 20:27:31 +0000405 DefaultFunctionArrayConversion(E);
406
407 // If the type of the exception would be an incomplete type or a pointer
408 // to an incomplete type other than (cv) void the program is ill-formed.
409 QualType Ty = E->getType();
John McCallac418162010-04-22 01:10:34 +0000410 bool isPointer = false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000411 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000412 Ty = Ptr->getPointeeType();
John McCallac418162010-04-22 01:10:34 +0000413 isPointer = true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000414 }
415 if (!isPointer || !Ty->isVoidType()) {
416 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000417 PDiag(isPointer ? diag::err_throw_incomplete_ptr
418 : diag::err_throw_incomplete)
419 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000420 return true;
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000421
Douglas Gregorbf422f92010-04-15 18:05:39 +0000422 if (RequireNonAbstractType(ThrowLoc, E->getType(),
423 PDiag(diag::err_throw_abstract_type)
424 << E->getSourceRange()))
425 return true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000426 }
427
John McCallac418162010-04-22 01:10:34 +0000428 // Initialize the exception result. This implicitly weeds out
429 // abstract types or types with inaccessible copy constructors.
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000430 // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p34.
John McCallac418162010-04-22 01:10:34 +0000431 InitializedEntity Entity =
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000432 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
433 /*NRVO=*/false);
John McCallac418162010-04-22 01:10:34 +0000434 OwningExprResult Res = PerformCopyInitialization(Entity,
435 SourceLocation(),
436 Owned(E));
437 if (Res.isInvalid())
438 return true;
439 E = Res.takeAs<Expr>();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000440
Eli Friedman5ed9b932010-06-03 20:39:03 +0000441 // If the exception has class type, we need additional handling.
442 const RecordType *RecordTy = Ty->getAs<RecordType>();
443 if (!RecordTy)
444 return false;
445 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
446
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000447 // If we are throwing a polymorphic class type or pointer thereof,
448 // exception handling will make use of the vtable.
Eli Friedman5ed9b932010-06-03 20:39:03 +0000449 MarkVTableUsed(ThrowLoc, RD);
450
451 // If the class has a non-trivial destructor, we must be able to call it.
452 if (RD->hasTrivialDestructor())
453 return false;
454
Douglas Gregor1d110e02010-07-01 14:13:13 +0000455 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +0000456 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman5ed9b932010-06-03 20:39:03 +0000457 if (!Destructor)
458 return false;
459
460 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
461 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregored8abf12010-07-08 06:14:04 +0000462 PDiag(diag::err_access_dtor_exception) << Ty);
Sebastian Redl972041f2009-04-27 20:27:31 +0000463 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000464}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000465
Sebastian Redlf53597f2009-03-15 17:47:39 +0000466Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000467 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
468 /// is a non-lvalue expression whose value is the address of the object for
469 /// which the function is called.
470
John McCallea1471e2010-05-20 01:18:31 +0000471 DeclContext *DC = getFunctionLevelDeclContext();
472 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000473 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000474 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000475 MD->getThisType(Context),
476 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000477
Sebastian Redlf53597f2009-03-15 17:47:39 +0000478 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000479}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000480
481/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
482/// Can be interpreted either as function-style casting ("int(x)")
483/// or class type construction ("ClassType(x,y,z)")
484/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000485Action::OwningExprResult
John McCallb3d87482010-08-24 05:47:05 +0000486Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, ParsedType TypeRep,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000487 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000488 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000489 SourceLocation *CommaLocs,
490 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000491 if (!TypeRep)
492 return ExprError();
493
John McCall9d125032010-01-15 18:39:57 +0000494 TypeSourceInfo *TInfo;
495 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
496 if (!TInfo)
497 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000498 unsigned NumExprs = exprs.size();
499 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000500 SourceLocation TyBeginLoc = TypeRange.getBegin();
501 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
502
Sebastian Redlf53597f2009-03-15 17:47:39 +0000503 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000504 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000505 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000506
507 return Owned(CXXUnresolvedConstructExpr::Create(Context,
508 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000509 LParenLoc,
510 Exprs, NumExprs,
511 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000512 }
513
Anders Carlssonbb60a502009-08-27 03:53:50 +0000514 if (Ty->isArrayType())
515 return ExprError(Diag(TyBeginLoc,
516 diag::err_value_init_for_array_type) << FullRange);
517 if (!Ty->isVoidType() &&
518 RequireCompleteType(TyBeginLoc, Ty,
519 PDiag(diag::err_invalid_incomplete_type_use)
520 << FullRange))
521 return ExprError();
Fariborz Jahanianf071e9b2009-10-23 21:01:39 +0000522
Anders Carlssonbb60a502009-08-27 03:53:50 +0000523 if (RequireNonAbstractType(TyBeginLoc, Ty,
524 diag::err_allocation_of_abstract_type))
525 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000526
527
Douglas Gregor506ae412009-01-16 18:33:17 +0000528 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000529 // If the expression list is a single expression, the type conversion
530 // expression is equivalent (in definedness, and if defined in meaning) to the
531 // corresponding cast expression.
532 //
533 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000534 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
John McCallf871d0c2010-08-07 06:22:56 +0000535 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000536 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, BasePath,
537 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000538 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000539
540 exprs.release();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000541
John McCallf871d0c2010-08-07 06:22:56 +0000542 return Owned(CXXFunctionalCastExpr::Create(Context,
Douglas Gregor63982352010-07-13 18:40:04 +0000543 Ty.getNonLValueExprType(Context),
John McCallf871d0c2010-08-07 06:22:56 +0000544 TInfo, TyBeginLoc, Kind,
545 Exprs[0], &BasePath,
546 RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000547 }
548
Douglas Gregored8abf12010-07-08 06:14:04 +0000549 if (Ty->isRecordType()) {
550 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
551 InitializationKind Kind
552 = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
553 LParenLoc, RParenLoc)
554 : InitializationKind::CreateValue(TypeRange.getBegin(),
555 LParenLoc, RParenLoc);
556 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
557 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
558 move(exprs));
Sebastian Redlf53597f2009-03-15 17:47:39 +0000559
Douglas Gregored8abf12010-07-08 06:14:04 +0000560 // FIXME: Improve AST representation?
561 return move(Result);
Douglas Gregor506ae412009-01-16 18:33:17 +0000562 }
563
564 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000565 // If the expression list specifies more than a single value, the type shall
566 // be a class with a suitably declared constructor.
567 //
568 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000569 return ExprError(Diag(CommaLocs[0],
570 diag::err_builtin_func_cast_more_than_one_arg)
571 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000572
573 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregor506ae412009-01-16 18:33:17 +0000574 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000575 // The expression T(), where T is a simple-type-specifier for a non-array
576 // complete object type or the (possibly cv-qualified) void type, creates an
577 // rvalue of the specified type, which is value-initialized.
578 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000579 exprs.release();
Douglas Gregored8abf12010-07-08 06:14:04 +0000580 return Owned(new (Context) CXXScalarValueInitExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000581}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000582
583
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000584/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
585/// @code new (memory) int[size][4] @endcode
586/// or
587/// @code ::new Foo(23, "hello") @endcode
588/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000589Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000590Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000591 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000592 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000593 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000594 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000595 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000596 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000597 // If the specified type is an array, unwrap it and save the expression.
598 if (D.getNumTypeObjects() > 0 &&
599 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
600 DeclaratorChunk &Chunk = D.getTypeObject(0);
601 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000602 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
603 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000604 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000605 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
606 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000607
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000608 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000609 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000610 }
611
Douglas Gregor043cad22009-09-11 00:18:58 +0000612 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000613 if (ArraySize) {
614 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000615 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
616 break;
617
618 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
619 if (Expr *NumElts = (Expr *)Array.NumElts) {
620 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
621 !NumElts->isIntegerConstantExpr(Context)) {
622 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
623 << NumElts->getSourceRange();
624 return ExprError();
625 }
626 }
627 }
628 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000629
John McCalla93c9342009-12-07 02:54:59 +0000630 //FIXME: Store TypeSourceInfo in CXXNew expression.
John McCallbf1a0282010-06-04 23:28:52 +0000631 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
632 QualType AllocType = TInfo->getType();
Chris Lattnereaaebc72009-04-25 08:06:05 +0000633 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000634 return ExprError();
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000635
636 SourceRange R = TInfo->getTypeLoc().getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000637 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000638 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000639 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000640 PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000641 TypeIdParens,
Mike Stump1eb44332009-09-09 15:08:12 +0000642 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000643 D.getSourceRange().getBegin(),
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000644 R,
John McCall9ae2f072010-08-23 23:25:46 +0000645 ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000646 ConstructorLParen,
647 move(ConstructorArgs),
648 ConstructorRParen);
649}
650
Mike Stump1eb44332009-09-09 15:08:12 +0000651Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000652Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
653 SourceLocation PlacementLParen,
654 MultiExprArg PlacementArgs,
655 SourceLocation PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000656 SourceRange TypeIdParens,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000657 QualType AllocType,
658 SourceLocation TypeLoc,
659 SourceRange TypeRange,
John McCall9ae2f072010-08-23 23:25:46 +0000660 Expr *ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000661 SourceLocation ConstructorLParen,
662 MultiExprArg ConstructorArgs,
663 SourceLocation ConstructorRParen) {
664 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000665 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000666
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000667 // Per C++0x [expr.new]p5, the type being constructed may be a
668 // typedef of an array type.
John McCall9ae2f072010-08-23 23:25:46 +0000669 if (!ArraySize) {
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000670 if (const ConstantArrayType *Array
671 = Context.getAsConstantArrayType(AllocType)) {
John McCall9ae2f072010-08-23 23:25:46 +0000672 ArraySize = new (Context) IntegerLiteral(Array->getSize(),
673 Context.getSizeType(),
674 TypeRange.getEnd());
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000675 AllocType = Array->getElementType();
676 }
677 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000678
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000679 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000680
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000681 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
682 // or enumeration type with a non-negative value."
Sebastian Redl28507842009-02-26 14:39:58 +0000683 if (ArraySize && !ArraySize->isTypeDependent()) {
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000684
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000685 QualType SizeType = ArraySize->getType();
Douglas Gregorc30614b2010-06-29 23:17:37 +0000686
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000687 OwningExprResult ConvertedSize
John McCall9ae2f072010-08-23 23:25:46 +0000688 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000689 PDiag(diag::err_array_size_not_integral),
690 PDiag(diag::err_array_size_incomplete_type)
691 << ArraySize->getSourceRange(),
692 PDiag(diag::err_array_size_explicit_conversion),
693 PDiag(diag::note_array_size_conversion),
694 PDiag(diag::err_array_size_ambiguous_conversion),
695 PDiag(diag::note_array_size_conversion),
696 PDiag(getLangOptions().CPlusPlus0x? 0
697 : diag::ext_array_size_conversion));
698 if (ConvertedSize.isInvalid())
699 return ExprError();
700
John McCall9ae2f072010-08-23 23:25:46 +0000701 ArraySize = ConvertedSize.take();
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000702 SizeType = ArraySize->getType();
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000703 if (!SizeType->isIntegralOrEnumerationType())
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000704 return ExprError();
705
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000706 // Let's see if this is a constant < 0. If so, we reject it out of hand.
707 // We don't care about special rules, so we tell the machinery it's not
708 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000709 if (!ArraySize->isValueDependent()) {
710 llvm::APSInt Value;
711 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
712 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000713 llvm::APInt::getNullValue(Value.getBitWidth()),
714 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000715 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +0000716 diag::err_typecheck_negative_array_size)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000717 << ArraySize->getSourceRange());
Douglas Gregor2767ce22010-08-18 00:39:00 +0000718
719 if (!AllocType->isDependentType()) {
720 unsigned ActiveSizeBits
721 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
722 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
723 Diag(ArraySize->getSourceRange().getBegin(),
724 diag::err_array_too_large)
725 << Value.toString(10)
726 << ArraySize->getSourceRange();
727 return ExprError();
728 }
729 }
Douglas Gregor4bd40312010-07-13 15:54:32 +0000730 } else if (TypeIdParens.isValid()) {
731 // Can't have dynamic array size when the type-id is in parentheses.
732 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
733 << ArraySize->getSourceRange()
734 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
735 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
736
737 TypeIdParens = SourceRange();
Sebastian Redl28507842009-02-26 14:39:58 +0000738 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000739 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000740
Eli Friedman73c39ab2009-10-20 08:27:19 +0000741 ImpCastExprToType(ArraySize, Context.getSizeType(),
742 CastExpr::CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000743 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000744
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000745 FunctionDecl *OperatorNew = 0;
746 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000747 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
748 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000749
Sebastian Redl28507842009-02-26 14:39:58 +0000750 if (!AllocType->isDependentType() &&
751 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
752 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000753 SourceRange(PlacementLParen, PlacementRParen),
754 UseGlobal, AllocType, ArraySize, PlaceArgs,
755 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000756 return ExprError();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000757 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000758 if (OperatorNew) {
759 // Add default arguments, if any.
760 const FunctionProtoType *Proto =
761 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000762 VariadicCallType CallType =
763 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Anders Carlsson28e94832010-05-03 02:07:56 +0000764
765 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
766 Proto, 1, PlaceArgs, NumPlaceArgs,
767 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000768 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000769
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000770 NumPlaceArgs = AllPlaceArgs.size();
771 if (NumPlaceArgs > 0)
772 PlaceArgs = &AllPlaceArgs[0];
773 }
774
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000775 bool Init = ConstructorLParen.isValid();
776 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000777 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000778 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
779 unsigned NumConsArgs = ConstructorArgs.size();
John McCallca0408f2010-08-23 06:44:23 +0000780 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000781
Anders Carlsson48c95012010-05-03 15:45:23 +0000782 // Array 'new' can't have any initializers.
Anders Carlsson55cbd6e2010-05-16 16:24:20 +0000783 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlsson48c95012010-05-03 15:45:23 +0000784 SourceRange InitRange(ConsArgs[0]->getLocStart(),
785 ConsArgs[NumConsArgs - 1]->getLocEnd());
786
787 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
788 return ExprError();
789 }
790
Douglas Gregor99a2e602009-12-16 01:38:02 +0000791 if (!AllocType->isDependentType() &&
792 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
793 // C++0x [expr.new]p15:
794 // A new-expression that creates an object of type T initializes that
795 // object as follows:
796 InitializationKind Kind
797 // - If the new-initializer is omitted, the object is default-
798 // initialized (8.5); if no initialization is performed,
799 // the object has indeterminate value
800 = !Init? InitializationKind::CreateDefault(TypeLoc)
801 // - Otherwise, the new-initializer is interpreted according to the
802 // initialization rules of 8.5 for direct-initialization.
803 : InitializationKind::CreateDirect(TypeLoc,
804 ConstructorLParen,
805 ConstructorRParen);
806
Douglas Gregor99a2e602009-12-16 01:38:02 +0000807 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +0000808 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000809 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000810 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
811 move(ConstructorArgs));
812 if (FullInit.isInvalid())
813 return ExprError();
814
815 // FullInit is our initializer; walk through it to determine if it's a
816 // constructor call, which CXXNewExpr handles directly.
817 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
818 if (CXXBindTemporaryExpr *Binder
819 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
820 FullInitExpr = Binder->getSubExpr();
821 if (CXXConstructExpr *Construct
822 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
823 Constructor = Construct->getConstructor();
824 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
825 AEnd = Construct->arg_end();
826 A != AEnd; ++A)
827 ConvertedConstructorArgs.push_back(A->Retain());
828 } else {
829 // Take the converted initializer.
830 ConvertedConstructorArgs.push_back(FullInit.release());
831 }
832 } else {
833 // No initialization required.
834 }
835
836 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +0000837 NumConsArgs = ConvertedConstructorArgs.size();
838 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000839 }
Douglas Gregor99a2e602009-12-16 01:38:02 +0000840
Douglas Gregor6d908702010-02-26 05:06:18 +0000841 // Mark the new and delete operators as referenced.
842 if (OperatorNew)
843 MarkDeclarationReferenced(StartLoc, OperatorNew);
844 if (OperatorDelete)
845 MarkDeclarationReferenced(StartLoc, OperatorDelete);
846
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000847 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000848
Sebastian Redlf53597f2009-03-15 17:47:39 +0000849 PlacementArgs.release();
850 ConstructorArgs.release();
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000851
852 // FIXME: The TypeSourceInfo should also be included in CXXNewExpr.
Ted Kremenekad7fe862010-02-11 22:51:03 +0000853 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000854 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenekad7fe862010-02-11 22:51:03 +0000855 ArraySize, Constructor, Init,
856 ConsArgs, NumConsArgs, OperatorDelete,
857 ResultType, StartLoc,
858 Init ? ConstructorRParen :
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000859 TypeRange.getEnd()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000860}
861
862/// CheckAllocatedType - Checks that a type is suitable as the allocated type
863/// in a new-expression.
864/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000865bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000866 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000867 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
868 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000869 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000870 return Diag(Loc, diag::err_bad_new_type)
871 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000872 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000873 return Diag(Loc, diag::err_bad_new_type)
874 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000875 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000876 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000877 PDiag(diag::err_new_incomplete_type)
878 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000879 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000880 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000881 diag::err_allocation_of_abstract_type))
882 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000883
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000884 return false;
885}
886
Douglas Gregor6d908702010-02-26 05:06:18 +0000887/// \brief Determine whether the given function is a non-placement
888/// deallocation function.
889static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
890 if (FD->isInvalidDecl())
891 return false;
892
893 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
894 return Method->isUsualDeallocationFunction();
895
896 return ((FD->getOverloadedOperator() == OO_Delete ||
897 FD->getOverloadedOperator() == OO_Array_Delete) &&
898 FD->getNumParams() == 1);
899}
900
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000901/// FindAllocationFunctions - Finds the overloads of operator new and delete
902/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000903bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
904 bool UseGlobal, QualType AllocType,
905 bool IsArray, Expr **PlaceArgs,
906 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000907 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000908 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000909 // --- Choosing an allocation function ---
910 // C++ 5.3.4p8 - 14 & 18
911 // 1) If UseGlobal is true, only look in the global scope. Else, also look
912 // in the scope of the allocated class.
913 // 2) If an array size is given, look for operator new[], else look for
914 // operator new.
915 // 3) The first argument is always size_t. Append the arguments from the
916 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000917
918 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
919 // We don't care about the actual value of this argument.
920 // FIXME: Should the Sema create the expression and embed it in the syntax
921 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000922 IntegerLiteral Size(llvm::APInt::getNullValue(
923 Context.Target.getPointerWidth(0)),
924 Context.getSizeType(),
925 SourceLocation());
926 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000927 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
928
Douglas Gregor6d908702010-02-26 05:06:18 +0000929 // C++ [expr.new]p8:
930 // If the allocated type is a non-array type, the allocation
931 // function’s name is operator new and the deallocation function’s
932 // name is operator delete. If the allocated type is an array
933 // type, the allocation function’s name is operator new[] and the
934 // deallocation function’s name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000935 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
936 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +0000937 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
938 IsArray ? OO_Array_Delete : OO_Delete);
939
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000940 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000941 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000942 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +0000943 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000944 AllocArgs.size(), Record, /*AllowMissing=*/true,
945 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000946 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000947 }
948 if (!OperatorNew) {
949 // Didn't find a member overload. Look for a global one.
950 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000951 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000952 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000953 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
954 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000955 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000956 }
957
John McCall9c82afc2010-04-20 02:18:25 +0000958 // We don't need an operator delete if we're running under
959 // -fno-exceptions.
960 if (!getLangOptions().Exceptions) {
961 OperatorDelete = 0;
962 return false;
963 }
964
Anders Carlssond9583892009-05-31 20:26:12 +0000965 // FindAllocationOverload can change the passed in arguments, so we need to
966 // copy them back.
967 if (NumPlaceArgs > 0)
968 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000969
Douglas Gregor6d908702010-02-26 05:06:18 +0000970 // C++ [expr.new]p19:
971 //
972 // If the new-expression begins with a unary :: operator, the
973 // deallocation function’s name is looked up in the global
974 // scope. Otherwise, if the allocated type is a class type T or an
975 // array thereof, the deallocation function’s name is looked up in
976 // the scope of T. If this lookup fails to find the name, or if
977 // the allocated type is not a class type or array thereof, the
978 // deallocation function’s name is looked up in the global scope.
979 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
980 if (AllocType->isRecordType() && !UseGlobal) {
981 CXXRecordDecl *RD
982 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
983 LookupQualifiedName(FoundDelete, RD);
984 }
John McCall90c8c572010-03-18 08:19:33 +0000985 if (FoundDelete.isAmbiguous())
986 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +0000987
988 if (FoundDelete.empty()) {
989 DeclareGlobalNewDelete();
990 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
991 }
992
993 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +0000994
995 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
996
John McCall90c8c572010-03-18 08:19:33 +0000997 if (NumPlaceArgs > 0) {
Douglas Gregor6d908702010-02-26 05:06:18 +0000998 // C++ [expr.new]p20:
999 // A declaration of a placement deallocation function matches the
1000 // declaration of a placement allocation function if it has the
1001 // same number of parameters and, after parameter transformations
1002 // (8.3.5), all parameter types except the first are
1003 // identical. [...]
1004 //
1005 // To perform this comparison, we compute the function type that
1006 // the deallocation function should have, and use that type both
1007 // for template argument deduction and for comparison purposes.
1008 QualType ExpectedFunctionType;
1009 {
1010 const FunctionProtoType *Proto
1011 = OperatorNew->getType()->getAs<FunctionProtoType>();
1012 llvm::SmallVector<QualType, 4> ArgTypes;
1013 ArgTypes.push_back(Context.VoidPtrTy);
1014 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1015 ArgTypes.push_back(Proto->getArgType(I));
1016
1017 ExpectedFunctionType
1018 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
1019 ArgTypes.size(),
1020 Proto->isVariadic(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001021 0, false, false, 0, 0,
1022 FunctionType::ExtInfo());
Douglas Gregor6d908702010-02-26 05:06:18 +00001023 }
1024
1025 for (LookupResult::iterator D = FoundDelete.begin(),
1026 DEnd = FoundDelete.end();
1027 D != DEnd; ++D) {
1028 FunctionDecl *Fn = 0;
1029 if (FunctionTemplateDecl *FnTmpl
1030 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1031 // Perform template argument deduction to try to match the
1032 // expected function type.
1033 TemplateDeductionInfo Info(Context, StartLoc);
1034 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1035 continue;
1036 } else
1037 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1038
1039 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001040 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001041 }
1042 } else {
1043 // C++ [expr.new]p20:
1044 // [...] Any non-placement deallocation function matches a
1045 // non-placement allocation function. [...]
1046 for (LookupResult::iterator D = FoundDelete.begin(),
1047 DEnd = FoundDelete.end();
1048 D != DEnd; ++D) {
1049 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1050 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001051 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001052 }
1053 }
1054
1055 // C++ [expr.new]p20:
1056 // [...] If the lookup finds a single matching deallocation
1057 // function, that function will be called; otherwise, no
1058 // deallocation function will be called.
1059 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001060 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001061
1062 // C++0x [expr.new]p20:
1063 // If the lookup finds the two-parameter form of a usual
1064 // deallocation function (3.7.4.2) and that function, considered
1065 // as a placement deallocation function, would have been
1066 // selected as a match for the allocation function, the program
1067 // is ill-formed.
1068 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1069 isNonPlacementDeallocationFunction(OperatorDelete)) {
1070 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1071 << SourceRange(PlaceArgs[0]->getLocStart(),
1072 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1073 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1074 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001075 } else {
1076 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001077 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001078 }
1079 }
1080
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001081 return false;
1082}
1083
Sebastian Redl7f662392008-12-04 22:20:51 +00001084/// FindAllocationOverload - Find an fitting overload for the allocation
1085/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001086bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1087 DeclarationName Name, Expr** Args,
1088 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +00001089 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001090 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1091 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001092 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001093 if (AllowMissing)
1094 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001095 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001096 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001097 }
1098
John McCall90c8c572010-03-18 08:19:33 +00001099 if (R.isAmbiguous())
1100 return true;
1101
1102 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001103
John McCall5769d612010-02-08 23:07:23 +00001104 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001105 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1106 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001107 // Even member operator new/delete are implicitly treated as
1108 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001109 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001110
John McCall9aa472c2010-03-19 07:35:19 +00001111 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1112 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001113 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1114 Candidates,
1115 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001116 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001117 }
1118
John McCall9aa472c2010-03-19 07:35:19 +00001119 FunctionDecl *Fn = cast<FunctionDecl>(D);
1120 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001121 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001122 }
1123
1124 // Do the resolution.
1125 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001126 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001127 case OR_Success: {
1128 // Got one!
1129 FunctionDecl *FnDecl = Best->Function;
1130 // The first argument is size_t, and the first parameter must be size_t,
1131 // too. This is checked on declaration and can be assumed. (It can't be
1132 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001133 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001134 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1135 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001136 OwningExprResult Result
1137 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
1138 FnDecl->getParamDecl(i)),
1139 SourceLocation(),
1140 Owned(Args[i]->Retain()));
1141 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001142 return true;
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001143
1144 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001145 }
1146 Operator = FnDecl;
John McCall9aa472c2010-03-19 07:35:19 +00001147 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001148 return false;
1149 }
1150
1151 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +00001152 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001153 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001154 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001155 return true;
1156
1157 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +00001158 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +00001159 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001160 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001161 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001162
1163 case OR_Deleted:
1164 Diag(StartLoc, diag::err_ovl_deleted_call)
1165 << Best->Function->isDeleted()
1166 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001167 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001168 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001169 }
1170 assert(false && "Unreachable, bad result from BestViableFunction");
1171 return true;
1172}
1173
1174
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001175/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1176/// delete. These are:
1177/// @code
1178/// void* operator new(std::size_t) throw(std::bad_alloc);
1179/// void* operator new[](std::size_t) throw(std::bad_alloc);
1180/// void operator delete(void *) throw();
1181/// void operator delete[](void *) throw();
1182/// @endcode
1183/// Note that the placement and nothrow forms of new are *not* implicitly
1184/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001185void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001186 if (GlobalNewDeleteDeclared)
1187 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001188
1189 // C++ [basic.std.dynamic]p2:
1190 // [...] The following allocation and deallocation functions (18.4) are
1191 // implicitly declared in global scope in each translation unit of a
1192 // program
1193 //
1194 // void* operator new(std::size_t) throw(std::bad_alloc);
1195 // void* operator new[](std::size_t) throw(std::bad_alloc);
1196 // void operator delete(void*) throw();
1197 // void operator delete[](void*) throw();
1198 //
1199 // These implicit declarations introduce only the function names operator
1200 // new, operator new[], operator delete, operator delete[].
1201 //
1202 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1203 // "std" or "bad_alloc" as necessary to form the exception specification.
1204 // However, we do not make these implicit declarations visible to name
1205 // lookup.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001206 if (!StdBadAlloc) {
1207 // The "std::bad_alloc" class has not yet been declared, so build it
1208 // implicitly.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001209 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00001210 getOrCreateStdNamespace(),
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001211 SourceLocation(),
1212 &PP.getIdentifierTable().get("bad_alloc"),
1213 SourceLocation(), 0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001214 getStdBadAlloc()->setImplicit(true);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001215 }
1216
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001217 GlobalNewDeleteDeclared = true;
1218
1219 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1220 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001221 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001222
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001223 DeclareGlobalAllocationFunction(
1224 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001225 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001226 DeclareGlobalAllocationFunction(
1227 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001228 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001229 DeclareGlobalAllocationFunction(
1230 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1231 Context.VoidTy, VoidPtr);
1232 DeclareGlobalAllocationFunction(
1233 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1234 Context.VoidTy, VoidPtr);
1235}
1236
1237/// DeclareGlobalAllocationFunction - Declares a single implicit global
1238/// allocation function if it doesn't already exist.
1239void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001240 QualType Return, QualType Argument,
1241 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001242 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1243
1244 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001245 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001246 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001247 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001248 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001249 // Only look at non-template functions, as it is the predefined,
1250 // non-templated allocation function we are trying to declare here.
1251 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1252 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001253 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001254 Func->getParamDecl(0)->getType().getUnqualifiedType());
1255 // FIXME: Do we need to check for default arguments here?
Douglas Gregor7b868622010-08-18 15:06:25 +00001256 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1257 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00001258 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001259 return;
Douglas Gregor7b868622010-08-18 15:06:25 +00001260 }
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001261 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001262 }
1263 }
1264
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001265 QualType BadAllocType;
1266 bool HasBadAllocExceptionSpec
1267 = (Name.getCXXOverloadedOperator() == OO_New ||
1268 Name.getCXXOverloadedOperator() == OO_Array_New);
1269 if (HasBadAllocExceptionSpec) {
1270 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001271 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001272 }
1273
1274 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1275 true, false,
1276 HasBadAllocExceptionSpec? 1 : 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00001277 &BadAllocType,
1278 FunctionType::ExtInfo());
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001279 FunctionDecl *Alloc =
1280 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001281 FnType, /*TInfo=*/0, FunctionDecl::None,
1282 FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001283 Alloc->setImplicit();
Nuno Lopesfc284482009-12-16 16:59:22 +00001284
1285 if (AddMallocAttr)
Sean Huntcf807c42010-08-18 23:23:40 +00001286 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Nuno Lopesfc284482009-12-16 16:59:22 +00001287
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001288 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00001289 0, Argument, /*TInfo=*/0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001290 VarDecl::None,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001291 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00001292 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001293
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001294 // FIXME: Also add this declaration to the IdentifierResolver, but
1295 // make sure it is at the end of the chain to coincide with the
1296 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001297 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001298}
1299
Anders Carlsson78f74552009-11-15 18:45:20 +00001300bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1301 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00001302 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001303 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001304 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001305 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +00001306
John McCalla24dc2e2009-11-17 02:14:36 +00001307 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001308 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001309
Chandler Carruth23893242010-06-28 00:30:51 +00001310 Found.suppressDiagnostics();
1311
John McCall046a7462010-08-04 00:31:26 +00001312 llvm::SmallVector<DeclAccessPair,4> Matches;
Anders Carlsson78f74552009-11-15 18:45:20 +00001313 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1314 F != FEnd; ++F) {
Chandler Carruth09556fd2010-08-08 07:04:00 +00001315 NamedDecl *ND = (*F)->getUnderlyingDecl();
1316
1317 // Ignore template operator delete members from the check for a usual
1318 // deallocation function.
1319 if (isa<FunctionTemplateDecl>(ND))
1320 continue;
1321
1322 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall046a7462010-08-04 00:31:26 +00001323 Matches.push_back(F.getPair());
1324 }
1325
1326 // There's exactly one suitable operator; pick it.
1327 if (Matches.size() == 1) {
1328 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
1329 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1330 Matches[0]);
1331 return false;
1332
1333 // We found multiple suitable operators; complain about the ambiguity.
1334 } else if (!Matches.empty()) {
1335 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1336 << Name << RD;
1337
1338 for (llvm::SmallVectorImpl<DeclAccessPair>::iterator
1339 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1340 Diag((*F)->getUnderlyingDecl()->getLocation(),
1341 diag::note_member_declared_here) << Name;
1342 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001343 }
1344
1345 // We did find operator delete/operator delete[] declarations, but
1346 // none of them were suitable.
1347 if (!Found.empty()) {
1348 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1349 << Name << RD;
1350
1351 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
John McCall046a7462010-08-04 00:31:26 +00001352 F != FEnd; ++F)
1353 Diag((*F)->getUnderlyingDecl()->getLocation(),
1354 diag::note_member_declared_here) << Name;
Anders Carlsson78f74552009-11-15 18:45:20 +00001355
1356 return true;
1357 }
1358
1359 // Look for a global declaration.
1360 DeclareGlobalNewDelete();
1361 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1362
1363 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1364 Expr* DeallocArgs[1];
1365 DeallocArgs[0] = &Null;
1366 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1367 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1368 Operator))
1369 return true;
1370
1371 assert(Operator && "Did not find a deallocation function!");
1372 return false;
1373}
1374
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001375/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1376/// @code ::delete ptr; @endcode
1377/// or
1378/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +00001379Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001380Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John McCall9ae2f072010-08-23 23:25:46 +00001381 bool ArrayForm, Expr *Ex) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001382 // C++ [expr.delete]p1:
1383 // The operand shall have a pointer type, or a class type having a single
1384 // conversion function to a pointer type. The result has type void.
1385 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001386 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1387
Anders Carlssond67c4c32009-08-16 20:29:29 +00001388 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001389
Sebastian Redl28507842009-02-26 14:39:58 +00001390 if (!Ex->isTypeDependent()) {
1391 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001392
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001393 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor254a9422010-07-29 14:44:35 +00001394 if (RequireCompleteType(StartLoc, Type,
1395 PDiag(diag::err_delete_incomplete_class_type)))
1396 return ExprError();
1397
John McCall32daa422010-03-31 01:36:47 +00001398 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1399
Fariborz Jahanian53462782009-09-11 21:44:33 +00001400 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCall32daa422010-03-31 01:36:47 +00001401 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001402 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001403 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001404 NamedDecl *D = I.getDecl();
1405 if (isa<UsingShadowDecl>(D))
1406 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1407
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001408 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001409 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001410 continue;
1411
John McCall32daa422010-03-31 01:36:47 +00001412 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001413
1414 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1415 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedman13578692010-08-05 02:49:48 +00001416 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001417 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001418 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001419 if (ObjectPtrConversions.size() == 1) {
1420 // We have a single conversion to a pointer-to-object type. Perform
1421 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001422 // TODO: don't redo the conversion calculation.
John McCall32daa422010-03-31 01:36:47 +00001423 if (!PerformImplicitConversion(Ex,
1424 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +00001425 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001426 Type = Ex->getType();
1427 }
1428 }
1429 else if (ObjectPtrConversions.size() > 1) {
1430 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1431 << Type << Ex->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001432 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1433 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001434 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001435 }
Sebastian Redl28507842009-02-26 14:39:58 +00001436 }
1437
Sebastian Redlf53597f2009-03-15 17:47:39 +00001438 if (!Type->isPointerType())
1439 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1440 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001441
Ted Kremenek6217b802009-07-29 21:53:49 +00001442 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor94a61572010-05-24 17:01:56 +00001443 if (Pointee->isVoidType() && !isSFINAEContext()) {
1444 // The C++ standard bans deleting a pointer to a non-object type, which
1445 // effectively bans deletion of "void*". However, most compilers support
1446 // this, so we treat it as a warning unless we're in a SFINAE context.
1447 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1448 << Type << Ex->getSourceRange();
1449 } else if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001450 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1451 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001452 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001453 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +00001454 PDiag(diag::warn_delete_incomplete)
1455 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001456 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +00001457
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001458 // C++ [expr.delete]p2:
1459 // [Note: a pointer to a const type can be the operand of a
1460 // delete-expression; it is not necessary to cast away the constness
1461 // (5.2.11) of the pointer expression before it is used as the operand
1462 // of the delete-expression. ]
1463 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
1464 CastExpr::CK_NoOp);
1465
Anders Carlssond67c4c32009-08-16 20:29:29 +00001466 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1467 ArrayForm ? OO_Array_Delete : OO_Delete);
1468
Anders Carlsson78f74552009-11-15 18:45:20 +00001469 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
1470 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1471
1472 if (!UseGlobal &&
1473 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001474 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001475
Anders Carlsson78f74552009-11-15 18:45:20 +00001476 if (!RD->hasTrivialDestructor())
Douglas Gregordb89f282010-07-01 22:47:18 +00001477 if (const CXXDestructorDecl *Dtor = LookupDestructor(RD))
Mike Stump1eb44332009-09-09 15:08:12 +00001478 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001479 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +00001480 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001481
Anders Carlssond67c4c32009-08-16 20:29:29 +00001482 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001483 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001484 DeclareGlobalNewDelete();
1485 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001486 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +00001487 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001488 OperatorDelete))
1489 return ExprError();
1490 }
Mike Stump1eb44332009-09-09 15:08:12 +00001491
John McCall9c82afc2010-04-20 02:18:25 +00001492 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1493
Sebastian Redl28507842009-02-26 14:39:58 +00001494 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001495 }
1496
Sebastian Redlf53597f2009-03-15 17:47:39 +00001497 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001498 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001499}
1500
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001501/// \brief Check the use of the given variable as a C++ condition in an if,
1502/// while, do-while, or switch statement.
Douglas Gregor586596f2010-05-06 17:25:47 +00001503Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
1504 SourceLocation StmtLoc,
1505 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001506 QualType T = ConditionVar->getType();
1507
1508 // C++ [stmt.select]p2:
1509 // The declarator shall not specify a function or an array.
1510 if (T->isFunctionType())
1511 return ExprError(Diag(ConditionVar->getLocation(),
1512 diag::err_invalid_use_of_function_type)
1513 << ConditionVar->getSourceRange());
1514 else if (T->isArrayType())
1515 return ExprError(Diag(ConditionVar->getLocation(),
1516 diag::err_invalid_use_of_array_type)
1517 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001518
Douglas Gregor586596f2010-05-06 17:25:47 +00001519 Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1520 ConditionVar->getLocation(),
1521 ConditionVar->getType().getNonReferenceType());
Douglas Gregorff331c12010-07-25 18:17:45 +00001522 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc))
Douglas Gregor586596f2010-05-06 17:25:47 +00001523 return ExprError();
Douglas Gregor586596f2010-05-06 17:25:47 +00001524
1525 return Owned(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001526}
1527
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001528/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1529bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1530 // C++ 6.4p4:
1531 // The value of a condition that is an initialized declaration in a statement
1532 // other than a switch statement is the value of the declared variable
1533 // implicitly converted to type bool. If that conversion is ill-formed, the
1534 // program is ill-formed.
1535 // The value of a condition that is an expression is the value of the
1536 // expression, implicitly converted to bool.
1537 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001538 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001539}
Douglas Gregor77a52232008-09-12 00:47:35 +00001540
1541/// Helper function to determine whether this is the (deprecated) C++
1542/// conversion from a string literal to a pointer to non-const char or
1543/// non-const wchar_t (for narrow and wide string literals,
1544/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001545bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001546Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1547 // Look inside the implicit cast, if it exists.
1548 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1549 From = Cast->getSubExpr();
1550
1551 // A string literal (2.13.4) that is not a wide string literal can
1552 // be converted to an rvalue of type "pointer to char"; a wide
1553 // string literal can be converted to an rvalue of type "pointer
1554 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00001555 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00001556 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001557 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001558 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001559 // This conversion is considered only when there is an
1560 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001561 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001562 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1563 (!StrLit->isWide() &&
1564 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1565 ToPointeeType->getKind() == BuiltinType::Char_S))))
1566 return true;
1567 }
1568
1569 return false;
1570}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001571
Douglas Gregorba70ab62010-04-16 22:17:36 +00001572static Sema::OwningExprResult BuildCXXCastArgument(Sema &S,
1573 SourceLocation CastLoc,
1574 QualType Ty,
1575 CastExpr::CastKind Kind,
1576 CXXMethodDecl *Method,
John McCall9ae2f072010-08-23 23:25:46 +00001577 Expr *From) {
Douglas Gregorba70ab62010-04-16 22:17:36 +00001578 switch (Kind) {
1579 default: assert(0 && "Unhandled cast kind!");
1580 case CastExpr::CK_ConstructorConversion: {
John McCallca0408f2010-08-23 06:44:23 +00001581 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregorba70ab62010-04-16 22:17:36 +00001582
1583 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
John McCallca0408f2010-08-23 06:44:23 +00001584 Sema::MultiExprArg(S, &From, 1),
Douglas Gregorba70ab62010-04-16 22:17:36 +00001585 CastLoc, ConstructorArgs))
1586 return S.ExprError();
1587
1588 Sema::OwningExprResult Result =
1589 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
1590 move_arg(ConstructorArgs));
1591 if (Result.isInvalid())
1592 return S.ExprError();
1593
1594 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1595 }
1596
1597 case CastExpr::CK_UserDefinedConversion: {
1598 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1599
1600 // Create an implicit call expr that calls it.
1601 // FIXME: pass the FoundDecl for the user-defined conversion here
1602 CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method);
1603 return S.MaybeBindToTemporary(CE);
1604 }
1605 }
1606}
1607
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001608/// PerformImplicitConversion - Perform an implicit conversion of the
1609/// expression From to the type ToType using the pre-computed implicit
1610/// conversion sequence ICS. Returns true if there was an error, false
1611/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001612/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001613/// used in the error message.
1614bool
1615Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1616 const ImplicitConversionSequence &ICS,
Douglas Gregor68647482009-12-16 03:45:30 +00001617 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall1d318332010-01-12 00:44:57 +00001618 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001619 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001620 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001621 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001622 return true;
1623 break;
1624
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001625 case ImplicitConversionSequence::UserDefinedConversion: {
1626
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001627 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1628 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001629 QualType BeforeToType;
1630 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001631 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001632
1633 // If the user-defined conversion is specified by a conversion function,
1634 // the initial standard conversion sequence converts the source type to
1635 // the implicit object parameter of the conversion function.
1636 BeforeToType = Context.getTagDeclType(Conv->getParent());
1637 } else if (const CXXConstructorDecl *Ctor =
1638 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001639 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001640 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001641 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001642 // If the user-defined conversion is specified by a constructor, the
1643 // initial standard conversion sequence converts the source type to the
1644 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001645 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1646 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001647 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001648 else
1649 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001650 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001651 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001652 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001653 ICS.UserDefined.Before, AA_Converting,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001654 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001655 return true;
1656 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001657
Anders Carlsson0aebc812009-09-09 21:33:21 +00001658 OwningExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00001659 = BuildCXXCastArgument(*this,
1660 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00001661 ToType.getNonReferenceType(),
1662 CastKind, cast<CXXMethodDecl>(FD),
John McCall9ae2f072010-08-23 23:25:46 +00001663 From);
Anders Carlsson0aebc812009-09-09 21:33:21 +00001664
1665 if (CastArg.isInvalid())
1666 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001667
1668 From = CastArg.takeAs<Expr>();
1669
Eli Friedmand8889622009-11-27 04:41:50 +00001670 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor68647482009-12-16 03:45:30 +00001671 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001672 }
John McCall1d318332010-01-12 00:44:57 +00001673
1674 case ImplicitConversionSequence::AmbiguousConversion:
1675 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1676 PDiag(diag::err_typecheck_ambiguous_condition)
1677 << From->getSourceRange());
1678 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001679
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001680 case ImplicitConversionSequence::EllipsisConversion:
1681 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001682 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001683
1684 case ImplicitConversionSequence::BadConversion:
1685 return true;
1686 }
1687
1688 // Everything went well.
1689 return false;
1690}
1691
1692/// PerformImplicitConversion - Perform an implicit conversion of the
1693/// expression From to the type ToType by following the standard
1694/// conversion sequence SCS. Returns true if there was an error, false
1695/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001696/// expression. Flavor is the context in which we're performing this
1697/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001698bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001699Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001700 const StandardConversionSequence& SCS,
Douglas Gregor68647482009-12-16 03:45:30 +00001701 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001702 // Overall FIXME: we are recomputing too many types here and doing far too
1703 // much extra work. What this means is that we need to keep track of more
1704 // information that is computed when we try the implicit conversion initially,
1705 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001706 QualType FromType = From->getType();
1707
Douglas Gregor225c41e2008-11-03 19:09:14 +00001708 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001709 // FIXME: When can ToType be a reference type?
1710 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001711 if (SCS.Second == ICK_Derived_To_Base) {
John McCallca0408f2010-08-23 06:44:23 +00001712 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001713 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCallca0408f2010-08-23 06:44:23 +00001714 MultiExprArg(*this, &From, 1),
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001715 /*FIXME:ConstructLoc*/SourceLocation(),
1716 ConstructorArgs))
1717 return true;
1718 OwningExprResult FromResult =
1719 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1720 ToType, SCS.CopyConstructor,
1721 move_arg(ConstructorArgs));
1722 if (FromResult.isInvalid())
1723 return true;
1724 From = FromResult.takeAs<Expr>();
1725 return false;
1726 }
Mike Stump1eb44332009-09-09 15:08:12 +00001727 OwningExprResult FromResult =
1728 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1729 ToType, SCS.CopyConstructor,
John McCallca0408f2010-08-23 06:44:23 +00001730 MultiExprArg(*this, &From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001731
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001732 if (FromResult.isInvalid())
1733 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001734
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001735 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001736 return false;
1737 }
1738
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001739 // Resolve overloaded function references.
1740 if (Context.hasSameType(FromType, Context.OverloadTy)) {
1741 DeclAccessPair Found;
1742 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1743 true, Found);
1744 if (!Fn)
1745 return true;
1746
1747 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1748 return true;
1749
1750 From = FixOverloadedFunctionReference(From, Found, Fn);
1751 FromType = From->getType();
1752 }
1753
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001754 // Perform the first implicit conversion.
1755 switch (SCS.First) {
1756 case ICK_Identity:
1757 case ICK_Lvalue_To_Rvalue:
1758 // Nothing to do.
1759 break;
1760
1761 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001762 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001763 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001764 break;
1765
1766 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001767 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001768 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001769 break;
1770
1771 default:
1772 assert(false && "Improper first standard conversion");
1773 break;
1774 }
1775
1776 // Perform the second implicit conversion
1777 switch (SCS.Second) {
1778 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001779 // If both sides are functions (or pointers/references to them), there could
1780 // be incompatible exception declarations.
1781 if (CheckExceptionSpecCompatibility(From, ToType))
1782 return true;
1783 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001784 break;
1785
Douglas Gregor43c79c22009-12-09 00:47:37 +00001786 case ICK_NoReturn_Adjustment:
1787 // If both sides are functions (or pointers/references to them), there could
1788 // be incompatible exception declarations.
1789 if (CheckExceptionSpecCompatibility(From, ToType))
1790 return true;
1791
1792 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1793 CastExpr::CK_NoOp);
1794 break;
1795
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001796 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001797 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001798 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1799 break;
1800
1801 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001802 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001803 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1804 break;
1805
1806 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001807 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001808 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1809 break;
1810
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001811 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001812 if (ToType->isRealFloatingType())
Eli Friedman73c39ab2009-10-20 08:27:19 +00001813 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1814 else
1815 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1816 break;
1817
Douglas Gregorf9201e02009-02-11 23:02:49 +00001818 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001819 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001820 break;
1821
Anders Carlsson61faec12009-09-12 04:46:44 +00001822 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001823 if (SCS.IncompatibleObjC) {
1824 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001825 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001826 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00001827 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00001828 << From->getSourceRange();
1829 }
1830
Anders Carlsson61faec12009-09-12 04:46:44 +00001831
1832 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
John McCallf871d0c2010-08-07 06:22:56 +00001833 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001834 if (CheckPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001835 return true;
John McCallf871d0c2010-08-07 06:22:56 +00001836 ImpCastExprToType(From, ToType, Kind, ImplicitCastExpr::RValue, &BasePath);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001837 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001838 }
1839
1840 case ICK_Pointer_Member: {
1841 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
John McCallf871d0c2010-08-07 06:22:56 +00001842 CXXCastPath BasePath;
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001843 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath,
1844 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001845 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001846 if (CheckExceptionSpecCompatibility(From, ToType))
1847 return true;
John McCallf871d0c2010-08-07 06:22:56 +00001848 ImpCastExprToType(From, ToType, Kind, ImplicitCastExpr::RValue, &BasePath);
Anders Carlsson61faec12009-09-12 04:46:44 +00001849 break;
1850 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001851 case ICK_Boolean_Conversion: {
1852 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1853 if (FromType->isMemberPointerType())
1854 Kind = CastExpr::CK_MemberPointerToBoolean;
1855
1856 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001857 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001858 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001859
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001860 case ICK_Derived_To_Base: {
John McCallf871d0c2010-08-07 06:22:56 +00001861 CXXCastPath BasePath;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001862 if (CheckDerivedToBaseConversion(From->getType(),
1863 ToType.getNonReferenceType(),
1864 From->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001865 From->getSourceRange(),
1866 &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001867 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001868 return true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001869
Sebastian Redl906082e2010-07-20 04:20:21 +00001870 ImpCastExprToType(From, ToType.getNonReferenceType(),
John McCallf871d0c2010-08-07 06:22:56 +00001871 CastExpr::CK_DerivedToBase, CastCategory(From),
1872 &BasePath);
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001873 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001874 }
1875
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001876 case ICK_Vector_Conversion:
1877 ImpCastExprToType(From, ToType, CastExpr::CK_BitCast);
1878 break;
1879
1880 case ICK_Vector_Splat:
1881 ImpCastExprToType(From, ToType, CastExpr::CK_VectorSplat);
1882 break;
1883
1884 case ICK_Complex_Real:
1885 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1886 break;
1887
1888 case ICK_Lvalue_To_Rvalue:
1889 case ICK_Array_To_Pointer:
1890 case ICK_Function_To_Pointer:
1891 case ICK_Qualification:
1892 case ICK_Num_Conversion_Kinds:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001893 assert(false && "Improper second standard conversion");
1894 break;
1895 }
1896
1897 switch (SCS.Third) {
1898 case ICK_Identity:
1899 // Nothing to do.
1900 break;
1901
Sebastian Redl906082e2010-07-20 04:20:21 +00001902 case ICK_Qualification: {
1903 // The qualification keeps the category of the inner expression, unless the
1904 // target type isn't a reference.
1905 ImplicitCastExpr::ResultCategory Category = ToType->isReferenceType() ?
1906 CastCategory(From) : ImplicitCastExpr::RValue;
Douglas Gregor63982352010-07-13 18:40:04 +00001907 ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
Sebastian Redl906082e2010-07-20 04:20:21 +00001908 CastExpr::CK_NoOp, Category);
Douglas Gregora9bff302010-02-28 18:30:25 +00001909
1910 if (SCS.DeprecatedStringLiteralToCharPtr)
1911 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
1912 << ToType.getNonReferenceType();
1913
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001914 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00001915 }
1916
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001917 default:
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001918 assert(false && "Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001919 break;
1920 }
1921
1922 return false;
1923}
1924
Sebastian Redl64b45f72009-01-05 20:52:13 +00001925Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1926 SourceLocation KWLoc,
1927 SourceLocation LParen,
John McCallb3d87482010-08-24 05:47:05 +00001928 ParsedType Ty,
Sebastian Redl64b45f72009-01-05 20:52:13 +00001929 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001930 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001931
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001932 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1933 // all traits except __is_class, __is_enum and __is_union require a the type
1934 // to be complete.
1935 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001936 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001937 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001938 return ExprError();
1939 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001940
1941 // There is no point in eagerly computing the value. The traits are designed
1942 // to be used from type trait templates, so Ty will be a template parameter
1943 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001944 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1945 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001946}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001947
1948QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001949 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001950 const char *OpSpelling = isIndirect ? "->*" : ".*";
1951 // C++ 5.5p2
1952 // The binary operator .* [p3: ->*] binds its second operand, which shall
1953 // be of type "pointer to member of T" (where T is a completely-defined
1954 // class type) [...]
1955 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001956 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001957 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001958 Diag(Loc, diag::err_bad_memptr_rhs)
1959 << OpSpelling << RType << rex->getSourceRange();
1960 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001961 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001962
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001963 QualType Class(MemPtr->getClass(), 0);
1964
Sebastian Redl59fc2692010-04-10 10:14:54 +00001965 if (RequireCompleteType(Loc, Class, diag::err_memptr_rhs_to_incomplete))
1966 return QualType();
1967
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001968 // C++ 5.5p2
1969 // [...] to its first operand, which shall be of class T or of a class of
1970 // which T is an unambiguous and accessible base class. [p3: a pointer to
1971 // such a class]
1972 QualType LType = lex->getType();
1973 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001974 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001975 LType = Ptr->getPointeeType().getNonReferenceType();
1976 else {
1977 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001978 << OpSpelling << 1 << LType
Douglas Gregor849b2432010-03-31 17:46:05 +00001979 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001980 return QualType();
1981 }
1982 }
1983
Douglas Gregora4923eb2009-11-16 21:35:15 +00001984 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00001985 // If we want to check the hierarchy, we need a complete type.
1986 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
1987 << OpSpelling << (int)isIndirect)) {
1988 return QualType();
1989 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001990 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001991 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001992 // FIXME: Would it be useful to print full ambiguity paths, or is that
1993 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001994 if (!IsDerivedFrom(LType, Class, Paths) ||
1995 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1996 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00001997 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001998 return QualType();
1999 }
Eli Friedman3005efe2010-01-16 00:00:48 +00002000 // Cast LHS to type of use.
2001 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Sebastian Redl906082e2010-07-20 04:20:21 +00002002 ImplicitCastExpr::ResultCategory Category =
2003 isIndirect ? ImplicitCastExpr::RValue : CastCategory(lex);
2004
John McCallf871d0c2010-08-07 06:22:56 +00002005 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002006 BuildBasePathArray(Paths, BasePath);
Sebastian Redl906082e2010-07-20 04:20:21 +00002007 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, Category,
John McCallf871d0c2010-08-07 06:22:56 +00002008 &BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002009 }
2010
Douglas Gregored8abf12010-07-08 06:14:04 +00002011 if (isa<CXXScalarValueInitExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00002012 // Diagnose use of pointer-to-member type which when used as
2013 // the functional cast in a pointer-to-member expression.
2014 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
2015 return QualType();
2016 }
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002017 // C++ 5.5p2
2018 // The result is an object or a function of the type specified by the
2019 // second operand.
2020 // The cv qualifiers are the union of those in the pointer and the left side,
2021 // in accordance with 5.5p5 and 5.2.5.
2022 // FIXME: This returns a dereferenced member function pointer as a normal
2023 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00002024 // calling them. There's also a GCC extension to get a function pointer to the
2025 // thing, which is another complication, because this type - unlike the type
2026 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002027 // argument.
2028 // We probably need a "MemberFunctionClosureType" or something like that.
2029 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00002030 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002031 return Result;
2032}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002033
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002034/// \brief Try to convert a type to another according to C++0x 5.16p3.
2035///
2036/// This is part of the parameter validation for the ? operator. If either
2037/// value operand is a class type, the two operands are attempted to be
2038/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002039/// It returns true if the program is ill-formed and has already been diagnosed
2040/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002041static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
2042 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00002043 bool &HaveConversion,
2044 QualType &ToType) {
2045 HaveConversion = false;
2046 ToType = To->getType();
2047
2048 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
2049 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002050 // C++0x 5.16p3
2051 // The process for determining whether an operand expression E1 of type T1
2052 // can be converted to match an operand expression E2 of type T2 is defined
2053 // as follows:
2054 // -- If E2 is an lvalue:
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002055 bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid);
2056 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002057 // E1 can be converted to match E2 if E1 can be implicitly converted to
2058 // type "lvalue reference to T2", subject to the constraint that in the
2059 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002060 QualType T = Self.Context.getLValueReferenceType(ToType);
2061 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2062
2063 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2064 if (InitSeq.isDirectReferenceBinding()) {
2065 ToType = T;
2066 HaveConversion = true;
2067 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002068 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002069
2070 if (InitSeq.isAmbiguous())
2071 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002072 }
John McCallb1bdc622010-02-25 01:37:24 +00002073
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002074 // -- If E2 is an rvalue, or if the conversion above cannot be done:
2075 // -- if E1 and E2 have class type, and the underlying class types are
2076 // the same or one is a base class of the other:
2077 QualType FTy = From->getType();
2078 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002079 const RecordType *FRec = FTy->getAs<RecordType>();
2080 const RecordType *TRec = TTy->getAs<RecordType>();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002081 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
2082 Self.IsDerivedFrom(FTy, TTy);
2083 if (FRec && TRec &&
2084 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002085 // E1 can be converted to match E2 if the class of T2 is the
2086 // same type as, or a base class of, the class of T1, and
2087 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00002088 if (FRec == TRec || FDerivedFromT) {
2089 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002090 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2091 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2092 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2093 HaveConversion = true;
2094 return false;
2095 }
2096
2097 if (InitSeq.isAmbiguous())
2098 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2099 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002100 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002101
2102 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002103 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002104
2105 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2106 // implicitly converted to the type that expression E2 would have
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002107 // if E2 were converted to an rvalue (or the type it has, if E2 is
2108 // an rvalue).
2109 //
2110 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2111 // to the array-to-pointer or function-to-pointer conversions.
2112 if (!TTy->getAs<TagType>())
2113 TTy = TTy.getUnqualifiedType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002114
2115 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2116 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2117 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
2118 ToType = TTy;
2119 if (InitSeq.isAmbiguous())
2120 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2121
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002122 return false;
2123}
2124
2125/// \brief Try to find a common type for two according to C++0x 5.16p5.
2126///
2127/// This is part of the parameter validation for the ? operator. If either
2128/// value operand is a class type, overload resolution is used to find a
2129/// conversion to a common type.
2130static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2131 SourceLocation Loc) {
2132 Expr *Args[2] = { LHS, RHS };
John McCall5769d612010-02-08 23:07:23 +00002133 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor573d9c32009-10-21 23:19:44 +00002134 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002135
2136 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00002137 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002138 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002139 // We found a match. Perform the conversions on the arguments and move on.
2140 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00002141 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002142 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00002143 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002144 break;
2145 return false;
2146
Douglas Gregor20093b42009-12-09 23:02:17 +00002147 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002148 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2149 << LHS->getType() << RHS->getType()
2150 << LHS->getSourceRange() << RHS->getSourceRange();
2151 return true;
2152
Douglas Gregor20093b42009-12-09 23:02:17 +00002153 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002154 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2155 << LHS->getType() << RHS->getType()
2156 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00002157 // FIXME: Print the possible common types by printing the return types of
2158 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002159 break;
2160
Douglas Gregor20093b42009-12-09 23:02:17 +00002161 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002162 assert(false && "Conditional operator has only built-in overloads");
2163 break;
2164 }
2165 return true;
2166}
2167
Sebastian Redl76458502009-04-17 16:30:52 +00002168/// \brief Perform an "extended" implicit conversion as returned by
2169/// TryClassUnification.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002170static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2171 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2172 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2173 SourceLocation());
2174 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
2175 Sema::OwningExprResult Result = InitSeq.Perform(Self, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00002176 Sema::MultiExprArg(Self, &E, 1));
Douglas Gregorb70cf442010-03-26 20:14:36 +00002177 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00002178 return true;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002179
2180 E = Result.takeAs<Expr>();
Sebastian Redl76458502009-04-17 16:30:52 +00002181 return false;
2182}
2183
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002184/// \brief Check the operands of ?: under C++ semantics.
2185///
2186/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2187/// extension. In this case, LHS == Cond. (But they're not aliases.)
2188QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2189 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002190 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2191 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002192
2193 // C++0x 5.16p1
2194 // The first expression is contextually converted to bool.
2195 if (!Cond->isTypeDependent()) {
2196 if (CheckCXXBooleanCondition(Cond))
2197 return QualType();
2198 }
2199
2200 // Either of the arguments dependent?
2201 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2202 return Context.DependentTy;
2203
2204 // C++0x 5.16p2
2205 // If either the second or the third operand has type (cv) void, ...
2206 QualType LTy = LHS->getType();
2207 QualType RTy = RHS->getType();
2208 bool LVoid = LTy->isVoidType();
2209 bool RVoid = RTy->isVoidType();
2210 if (LVoid || RVoid) {
2211 // ... then the [l2r] conversions are performed on the second and third
2212 // operands ...
Douglas Gregora873dfc2010-02-03 00:27:59 +00002213 DefaultFunctionArrayLvalueConversion(LHS);
2214 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002215 LTy = LHS->getType();
2216 RTy = RHS->getType();
2217
2218 // ... and one of the following shall hold:
2219 // -- The second or the third operand (but not both) is a throw-
2220 // expression; the result is of the type of the other and is an rvalue.
2221 bool LThrow = isa<CXXThrowExpr>(LHS);
2222 bool RThrow = isa<CXXThrowExpr>(RHS);
2223 if (LThrow && !RThrow)
2224 return RTy;
2225 if (RThrow && !LThrow)
2226 return LTy;
2227
2228 // -- Both the second and third operands have type void; the result is of
2229 // type void and is an rvalue.
2230 if (LVoid && RVoid)
2231 return Context.VoidTy;
2232
2233 // Neither holds, error.
2234 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2235 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2236 << LHS->getSourceRange() << RHS->getSourceRange();
2237 return QualType();
2238 }
2239
2240 // Neither is void.
2241
2242 // C++0x 5.16p3
2243 // Otherwise, if the second and third operand have different types, and
2244 // either has (cv) class type, and attempt is made to convert each of those
2245 // operands to the other.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002246 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002247 (LTy->isRecordType() || RTy->isRecordType())) {
2248 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2249 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002250 QualType L2RType, R2LType;
2251 bool HaveL2R, HaveR2L;
2252 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002253 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002254 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002255 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002256
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002257 // If both can be converted, [...] the program is ill-formed.
2258 if (HaveL2R && HaveR2L) {
2259 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2260 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2261 return QualType();
2262 }
2263
2264 // If exactly one conversion is possible, that conversion is applied to
2265 // the chosen operand and the converted operands are used in place of the
2266 // original operands for the remainder of this section.
2267 if (HaveL2R) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002268 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002269 return QualType();
2270 LTy = LHS->getType();
2271 } else if (HaveR2L) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002272 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002273 return QualType();
2274 RTy = RHS->getType();
2275 }
2276 }
2277
2278 // C++0x 5.16p4
2279 // If the second and third operands are lvalues and have the same type,
2280 // the result is of that type [...]
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002281 bool Same = Context.hasSameType(LTy, RTy);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002282 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
2283 RHS->isLvalue(Context) == Expr::LV_Valid)
2284 return LTy;
2285
2286 // C++0x 5.16p5
2287 // Otherwise, the result is an rvalue. If the second and third operands
2288 // do not have the same type, and either has (cv) class type, ...
2289 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2290 // ... overload resolution is used to determine the conversions (if any)
2291 // to be applied to the operands. If the overload resolution fails, the
2292 // program is ill-formed.
2293 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2294 return QualType();
2295 }
2296
2297 // C++0x 5.16p6
2298 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2299 // conversions are performed on the second and third operands.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002300 DefaultFunctionArrayLvalueConversion(LHS);
2301 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002302 LTy = LHS->getType();
2303 RTy = RHS->getType();
2304
2305 // After those conversions, one of the following shall hold:
2306 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00002307 // is of that type. If the operands have class type, the result
2308 // is a prvalue temporary of the result type, which is
2309 // copy-initialized from either the second operand or the third
2310 // operand depending on the value of the first operand.
2311 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
2312 if (LTy->isRecordType()) {
2313 // The operands have class type. Make a temporary copy.
2314 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
2315 OwningExprResult LHSCopy = PerformCopyInitialization(Entity,
2316 SourceLocation(),
2317 Owned(LHS));
2318 if (LHSCopy.isInvalid())
2319 return QualType();
2320
2321 OwningExprResult RHSCopy = PerformCopyInitialization(Entity,
2322 SourceLocation(),
2323 Owned(RHS));
2324 if (RHSCopy.isInvalid())
2325 return QualType();
2326
2327 LHS = LHSCopy.takeAs<Expr>();
2328 RHS = RHSCopy.takeAs<Expr>();
2329 }
2330
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002331 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00002332 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002333
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002334 // Extension: conditional operator involving vector types.
2335 if (LTy->isVectorType() || RTy->isVectorType())
2336 return CheckVectorOperands(QuestionLoc, LHS, RHS);
2337
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002338 // -- The second and third operands have arithmetic or enumeration type;
2339 // the usual arithmetic conversions are performed to bring them to a
2340 // common type, and the result is of that type.
2341 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2342 UsualArithmeticConversions(LHS, RHS);
2343 return LHS->getType();
2344 }
2345
2346 // -- The second and third operands have pointer type, or one has pointer
2347 // type and the other is a null pointer constant; pointer conversions
2348 // and qualification conversions are performed to bring them to their
2349 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00002350 // -- The second and third operands have pointer to member type, or one has
2351 // pointer to member type and the other is a null pointer constant;
2352 // pointer to member conversions and qualification conversions are
2353 // performed to bring them to a common type, whose cv-qualification
2354 // shall match the cv-qualification of either the second or the third
2355 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002356 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002357 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002358 isSFINAEContext()? 0 : &NonStandardCompositeType);
2359 if (!Composite.isNull()) {
2360 if (NonStandardCompositeType)
2361 Diag(QuestionLoc,
2362 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2363 << LTy << RTy << Composite
2364 << LHS->getSourceRange() << RHS->getSourceRange();
2365
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002366 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002367 }
Fariborz Jahanian55016362009-12-10 20:46:08 +00002368
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002369 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00002370 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2371 if (!Composite.isNull())
2372 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002373
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002374 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2375 << LHS->getType() << RHS->getType()
2376 << LHS->getSourceRange() << RHS->getSourceRange();
2377 return QualType();
2378}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002379
2380/// \brief Find a merged pointer type and convert the two expressions to it.
2381///
Douglas Gregor20b3e992009-08-24 17:42:35 +00002382/// This finds the composite pointer type (or member pointer type) for @p E1
2383/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2384/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002385/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002386///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002387/// \param Loc The location of the operator requiring these two expressions to
2388/// be converted to the composite pointer type.
2389///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002390/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2391/// a non-standard (but still sane) composite type to which both expressions
2392/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2393/// will be set true.
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002394QualType Sema::FindCompositePointerType(SourceLocation Loc,
2395 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002396 bool *NonStandardCompositeType) {
2397 if (NonStandardCompositeType)
2398 *NonStandardCompositeType = false;
2399
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002400 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2401 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002402
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00002403 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2404 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00002405 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002406
2407 // C++0x 5.9p2
2408 // Pointer conversions and qualification conversions are performed on
2409 // pointer operands to bring them to their composite pointer type. If
2410 // one operand is a null pointer constant, the composite pointer type is
2411 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00002412 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002413 if (T2->isMemberPointerType())
2414 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
2415 else
2416 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002417 return T2;
2418 }
Douglas Gregorce940492009-09-25 04:25:58 +00002419 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002420 if (T1->isMemberPointerType())
2421 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
2422 else
2423 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002424 return T1;
2425 }
Mike Stump1eb44332009-09-09 15:08:12 +00002426
Douglas Gregor20b3e992009-08-24 17:42:35 +00002427 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002428 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2429 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002430 return QualType();
2431
2432 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2433 // the other has type "pointer to cv2 T" and the composite pointer type is
2434 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2435 // Otherwise, the composite pointer type is a pointer type similar to the
2436 // type of one of the operands, with a cv-qualification signature that is
2437 // the union of the cv-qualification signatures of the operand types.
2438 // In practice, the first part here is redundant; it's subsumed by the second.
2439 // What we do here is, we build the two possible composite types, and try the
2440 // conversions in both directions. If only one works, or if the two composite
2441 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00002442 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00002443 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2444 QualifierVector QualifierUnion;
2445 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2446 ContainingClassVector;
2447 ContainingClassVector MemberOfClass;
2448 QualType Composite1 = Context.getCanonicalType(T1),
2449 Composite2 = Context.getCanonicalType(T2);
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002450 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00002451 do {
2452 const PointerType *Ptr1, *Ptr2;
2453 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2454 (Ptr2 = Composite2->getAs<PointerType>())) {
2455 Composite1 = Ptr1->getPointeeType();
2456 Composite2 = Ptr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002457
2458 // If we're allowed to create a non-standard composite type, keep track
2459 // of where we need to fill in additional 'const' qualifiers.
2460 if (NonStandardCompositeType &&
2461 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2462 NeedConstBefore = QualifierUnion.size();
2463
Douglas Gregor20b3e992009-08-24 17:42:35 +00002464 QualifierUnion.push_back(
2465 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2466 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2467 continue;
2468 }
Mike Stump1eb44332009-09-09 15:08:12 +00002469
Douglas Gregor20b3e992009-08-24 17:42:35 +00002470 const MemberPointerType *MemPtr1, *MemPtr2;
2471 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2472 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2473 Composite1 = MemPtr1->getPointeeType();
2474 Composite2 = MemPtr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002475
2476 // If we're allowed to create a non-standard composite type, keep track
2477 // of where we need to fill in additional 'const' qualifiers.
2478 if (NonStandardCompositeType &&
2479 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2480 NeedConstBefore = QualifierUnion.size();
2481
Douglas Gregor20b3e992009-08-24 17:42:35 +00002482 QualifierUnion.push_back(
2483 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2484 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2485 MemPtr2->getClass()));
2486 continue;
2487 }
Mike Stump1eb44332009-09-09 15:08:12 +00002488
Douglas Gregor20b3e992009-08-24 17:42:35 +00002489 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00002490
Douglas Gregor20b3e992009-08-24 17:42:35 +00002491 // Cannot unwrap any more types.
2492 break;
2493 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00002494
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002495 if (NeedConstBefore && NonStandardCompositeType) {
2496 // Extension: Add 'const' to qualifiers that come before the first qualifier
2497 // mismatch, so that our (non-standard!) composite type meets the
2498 // requirements of C++ [conv.qual]p4 bullet 3.
2499 for (unsigned I = 0; I != NeedConstBefore; ++I) {
2500 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
2501 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
2502 *NonStandardCompositeType = true;
2503 }
2504 }
2505 }
2506
Douglas Gregor20b3e992009-08-24 17:42:35 +00002507 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002508 ContainingClassVector::reverse_iterator MOC
2509 = MemberOfClass.rbegin();
2510 for (QualifierVector::reverse_iterator
2511 I = QualifierUnion.rbegin(),
2512 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00002513 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00002514 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002515 if (MOC->first && MOC->second) {
2516 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00002517 Composite1 = Context.getMemberPointerType(
2518 Context.getQualifiedType(Composite1, Quals),
2519 MOC->first);
2520 Composite2 = Context.getMemberPointerType(
2521 Context.getQualifiedType(Composite2, Quals),
2522 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002523 } else {
2524 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00002525 Composite1
2526 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2527 Composite2
2528 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00002529 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002530 }
2531
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002532 // Try to convert to the first composite pointer type.
2533 InitializedEntity Entity1
2534 = InitializedEntity::InitializeTemporary(Composite1);
2535 InitializationKind Kind
2536 = InitializationKind::CreateCopy(Loc, SourceLocation());
2537 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
2538 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00002539
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002540 if (E1ToC1 && E2ToC1) {
2541 // Conversion to Composite1 is viable.
2542 if (!Context.hasSameType(Composite1, Composite2)) {
2543 // Composite2 is a different type from Composite1. Check whether
2544 // Composite2 is also viable.
2545 InitializedEntity Entity2
2546 = InitializedEntity::InitializeTemporary(Composite2);
2547 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2548 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2549 if (E1ToC2 && E2ToC2) {
2550 // Both Composite1 and Composite2 are viable and are different;
2551 // this is an ambiguity.
2552 return QualType();
2553 }
2554 }
2555
2556 // Convert E1 to Composite1
2557 OwningExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00002558 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002559 if (E1Result.isInvalid())
2560 return QualType();
2561 E1 = E1Result.takeAs<Expr>();
2562
2563 // Convert E2 to Composite1
2564 OwningExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00002565 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002566 if (E2Result.isInvalid())
2567 return QualType();
2568 E2 = E2Result.takeAs<Expr>();
2569
2570 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002571 }
2572
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002573 // Check whether Composite2 is viable.
2574 InitializedEntity Entity2
2575 = InitializedEntity::InitializeTemporary(Composite2);
2576 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2577 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2578 if (!E1ToC2 || !E2ToC2)
2579 return QualType();
2580
2581 // Convert E1 to Composite2
2582 OwningExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00002583 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002584 if (E1Result.isInvalid())
2585 return QualType();
2586 E1 = E1Result.takeAs<Expr>();
2587
2588 // Convert E2 to Composite2
2589 OwningExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00002590 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002591 if (E2Result.isInvalid())
2592 return QualType();
2593 E2 = E2Result.takeAs<Expr>();
2594
2595 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002596}
Anders Carlsson165a0a02009-05-17 18:41:29 +00002597
Anders Carlssondef11992009-05-30 20:36:53 +00002598Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00002599 if (!Context.getLangOptions().CPlusPlus)
2600 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002601
Douglas Gregor51326552009-12-24 18:51:59 +00002602 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2603
Ted Kremenek6217b802009-07-29 21:53:49 +00002604 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00002605 if (!RT)
2606 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002607
Anders Carlsson0ea4dfd2010-07-16 21:18:37 +00002608 // If this is the result of a call or an Objective-C message send expression,
2609 // our source might actually be a reference, in which case we shouldn't bind.
Anders Carlsson283e4d52009-09-14 01:30:44 +00002610 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
Anders Carlsson0ea4dfd2010-07-16 21:18:37 +00002611 if (CE->getCallReturnType()->isReferenceType())
Anders Carlsson283e4d52009-09-14 01:30:44 +00002612 return Owned(E);
Anders Carlsson0ea4dfd2010-07-16 21:18:37 +00002613 } else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
2614 if (const ObjCMethodDecl *MD = ME->getMethodDecl()) {
2615 if (MD->getResultType()->isReferenceType())
2616 return Owned(E);
2617 }
Anders Carlsson283e4d52009-09-14 01:30:44 +00002618 }
John McCall86ff3082010-02-04 22:26:26 +00002619
2620 // That should be enough to guarantee that this type is complete.
2621 // If it has a trivial destructor, we can avoid the extra copy.
2622 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall507384f2010-08-12 02:40:37 +00002623 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall86ff3082010-02-04 22:26:26 +00002624 return Owned(E);
2625
Douglas Gregordb89f282010-07-01 22:47:18 +00002626 CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD));
Anders Carlsson860306e2009-05-30 21:21:49 +00002627 ExprTemporaries.push_back(Temp);
Douglas Gregordb89f282010-07-01 22:47:18 +00002628 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002629 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00002630 CheckDestructorAccess(E->getExprLoc(), Destructor,
2631 PDiag(diag::err_access_dtor_temp)
2632 << E->getType());
2633 }
Anders Carlssondef11992009-05-30 20:36:53 +00002634 // FIXME: Add the temporary to the temporaries vector.
2635 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2636}
2637
Anders Carlsson0ece4912009-12-15 20:51:39 +00002638Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002639 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002640
John McCall323ed742010-05-06 08:58:33 +00002641 // Check any implicit conversions within the expression.
2642 CheckImplicitConversions(SubExpr);
2643
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002644 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2645 assert(ExprTemporaries.size() >= FirstTemporary);
2646 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002647 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002648
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002649 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002650 &ExprTemporaries[FirstTemporary],
Anders Carlsson0ece4912009-12-15 20:51:39 +00002651 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002652 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2653 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002654
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002655 return E;
2656}
2657
Douglas Gregor90f93822009-12-22 22:17:25 +00002658Sema::OwningExprResult
2659Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2660 if (SubExpr.isInvalid())
2661 return ExprError();
2662
2663 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2664}
2665
Anders Carlsson5ee56e92009-12-16 02:09:40 +00002666FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2667 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2668 assert(ExprTemporaries.size() >= FirstTemporary);
2669
2670 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2671 CXXTemporary **Temporaries =
2672 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2673
2674 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2675
2676 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2677 ExprTemporaries.end());
2678
2679 return E;
2680}
2681
Mike Stump1eb44332009-09-09 15:08:12 +00002682Sema::OwningExprResult
John McCall9ae2f072010-08-23 23:25:46 +00002683Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallb3d87482010-08-24 05:47:05 +00002684 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00002685 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002686 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall9ae2f072010-08-23 23:25:46 +00002687 OwningExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
2688 if (Result.isInvalid()) return ExprError();
2689 Base = Result.get();
Mike Stump1eb44332009-09-09 15:08:12 +00002690
John McCall9ae2f072010-08-23 23:25:46 +00002691 QualType BaseType = Base->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00002692 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002693 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002694 // If we have a pointer to a dependent type and are using the -> operator,
2695 // the object type is the type that the pointer points to. We might still
2696 // have enough information about that type to do something useful.
2697 if (OpKind == tok::arrow)
2698 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2699 BaseType = Ptr->getPointeeType();
2700
John McCallb3d87482010-08-24 05:47:05 +00002701 ObjectType = ParsedType::make(BaseType);
Douglas Gregord4dca082010-02-24 18:44:31 +00002702 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00002703 return Owned(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002704 }
Mike Stump1eb44332009-09-09 15:08:12 +00002705
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002706 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002707 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002708 // returned, with the original second operand.
2709 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002710 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002711 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002712 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002713 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002714
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002715 while (BaseType->isRecordType()) {
John McCall9ae2f072010-08-23 23:25:46 +00002716 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
2717 if (Result.isInvalid())
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002718 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00002719 Base = Result.get();
2720 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonde699e52009-10-13 22:55:59 +00002721 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCall9ae2f072010-08-23 23:25:46 +00002722 BaseType = Base->getType();
John McCallc4e83212009-09-30 01:01:30 +00002723 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002724 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002725 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002726 for (unsigned i = 0; i < Locations.size(); i++)
2727 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002728 return ExprError();
2729 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002730 }
Mike Stump1eb44332009-09-09 15:08:12 +00002731
Douglas Gregor31658df2009-11-20 19:58:21 +00002732 if (BaseType->isPointerType())
2733 BaseType = BaseType->getPointeeType();
2734 }
Mike Stump1eb44332009-09-09 15:08:12 +00002735
2736 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002737 // vector types or Objective-C interfaces. Just return early and let
2738 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002739 if (!BaseType->isRecordType()) {
2740 // C++ [basic.lookup.classref]p2:
2741 // [...] If the type of the object expression is of pointer to scalar
2742 // type, the unqualified-id is looked up in the context of the complete
2743 // postfix-expression.
Douglas Gregord4dca082010-02-24 18:44:31 +00002744 //
2745 // This also indicates that we should be parsing a
2746 // pseudo-destructor-name.
John McCallb3d87482010-08-24 05:47:05 +00002747 ObjectType = ParsedType();
Douglas Gregord4dca082010-02-24 18:44:31 +00002748 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00002749 return Owned(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002750 }
Mike Stump1eb44332009-09-09 15:08:12 +00002751
Douglas Gregor03c57052009-11-17 05:17:33 +00002752 // The object type must be complete (or dependent).
2753 if (!BaseType->isDependentType() &&
2754 RequireCompleteType(OpLoc, BaseType,
2755 PDiag(diag::err_incomplete_member_access)))
2756 return ExprError();
2757
Douglas Gregorc68afe22009-09-03 21:38:09 +00002758 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002759 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00002760 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00002761 // type C (or of pointer to a class type C), the unqualified-id is looked
2762 // up in the scope of class C. [...]
John McCallb3d87482010-08-24 05:47:05 +00002763 ObjectType = ParsedType::make(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00002764 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002765}
2766
Douglas Gregor77549082010-02-24 21:29:12 +00002767Sema::OwningExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCall9ae2f072010-08-23 23:25:46 +00002768 Expr *MemExpr) {
Douglas Gregor77549082010-02-24 21:29:12 +00002769 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCall9ae2f072010-08-23 23:25:46 +00002770 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
2771 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregor849b2432010-03-31 17:46:05 +00002772 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
Douglas Gregor77549082010-02-24 21:29:12 +00002773
2774 return ActOnCallExpr(/*Scope*/ 0,
John McCall9ae2f072010-08-23 23:25:46 +00002775 MemExpr,
Douglas Gregor77549082010-02-24 21:29:12 +00002776 /*LPLoc*/ ExpectedLParenLoc,
2777 Sema::MultiExprArg(*this, 0, 0),
2778 /*CommaLocs*/ 0,
2779 /*RPLoc*/ ExpectedLParenLoc);
2780}
Douglas Gregord4dca082010-02-24 18:44:31 +00002781
John McCall9ae2f072010-08-23 23:25:46 +00002782Sema::OwningExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002783 SourceLocation OpLoc,
2784 tok::TokenKind OpKind,
2785 const CXXScopeSpec &SS,
Douglas Gregor26d4ac92010-02-24 23:40:28 +00002786 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002787 SourceLocation CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002788 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002789 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002790 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002791 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
Douglas Gregorb57fb492010-02-24 22:38:50 +00002792
2793 // C++ [expr.pseudo]p2:
2794 // The left-hand side of the dot operator shall be of scalar type. The
2795 // left-hand side of the arrow operator shall be of pointer to scalar type.
2796 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00002797 QualType ObjectType = Base->getType();
Douglas Gregorb57fb492010-02-24 22:38:50 +00002798 if (OpKind == tok::arrow) {
2799 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2800 ObjectType = Ptr->getPointeeType();
John McCall9ae2f072010-08-23 23:25:46 +00002801 } else if (!Base->isTypeDependent()) {
Douglas Gregorb57fb492010-02-24 22:38:50 +00002802 // The user wrote "p->" when she probably meant "p."; fix it.
2803 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2804 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00002805 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb57fb492010-02-24 22:38:50 +00002806 if (isSFINAEContext())
2807 return ExprError();
2808
2809 OpKind = tok::period;
2810 }
2811 }
2812
2813 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
2814 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
John McCall9ae2f072010-08-23 23:25:46 +00002815 << ObjectType << Base->getSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00002816 return ExprError();
2817 }
2818
2819 // C++ [expr.pseudo]p2:
2820 // [...] The cv-unqualified versions of the object type and of the type
2821 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002822 if (DestructedTypeInfo) {
2823 QualType DestructedType = DestructedTypeInfo->getType();
2824 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002825 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002826 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
2827 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
2828 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00002829 << ObjectType << DestructedType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002830 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002831
2832 // Recover by setting the destructed type to the object type.
2833 DestructedType = ObjectType;
2834 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
2835 DestructedTypeStart);
2836 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2837 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00002838 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002839
Douglas Gregorb57fb492010-02-24 22:38:50 +00002840 // C++ [expr.pseudo]p2:
2841 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
2842 // form
2843 //
2844 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
2845 //
2846 // shall designate the same scalar type.
2847 if (ScopeTypeInfo) {
2848 QualType ScopeType = ScopeTypeInfo->getType();
2849 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00002850 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
Douglas Gregorb57fb492010-02-24 22:38:50 +00002851
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002852 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00002853 diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00002854 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002855 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00002856
2857 ScopeType = QualType();
2858 ScopeTypeInfo = 0;
2859 }
2860 }
2861
John McCall9ae2f072010-08-23 23:25:46 +00002862 Expr *Result
2863 = new (Context) CXXPseudoDestructorExpr(Context, Base,
2864 OpKind == tok::arrow, OpLoc,
2865 SS.getScopeRep(), SS.getRange(),
2866 ScopeTypeInfo,
2867 CCLoc,
2868 TildeLoc,
2869 Destructed);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002870
Douglas Gregorb57fb492010-02-24 22:38:50 +00002871 if (HasTrailingLParen)
John McCall9ae2f072010-08-23 23:25:46 +00002872 return Owned(Result);
Douglas Gregorb57fb492010-02-24 22:38:50 +00002873
John McCall9ae2f072010-08-23 23:25:46 +00002874 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor77549082010-02-24 21:29:12 +00002875}
2876
John McCall9ae2f072010-08-23 23:25:46 +00002877Sema::OwningExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
Douglas Gregor77549082010-02-24 21:29:12 +00002878 SourceLocation OpLoc,
2879 tok::TokenKind OpKind,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002880 CXXScopeSpec &SS,
Douglas Gregor77549082010-02-24 21:29:12 +00002881 UnqualifiedId &FirstTypeName,
2882 SourceLocation CCLoc,
2883 SourceLocation TildeLoc,
2884 UnqualifiedId &SecondTypeName,
2885 bool HasTrailingLParen) {
2886 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2887 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2888 "Invalid first type name in pseudo-destructor");
2889 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2890 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2891 "Invalid second type name in pseudo-destructor");
2892
Douglas Gregor77549082010-02-24 21:29:12 +00002893 // C++ [expr.pseudo]p2:
2894 // The left-hand side of the dot operator shall be of scalar type. The
2895 // left-hand side of the arrow operator shall be of pointer to scalar type.
2896 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00002897 QualType ObjectType = Base->getType();
Douglas Gregor77549082010-02-24 21:29:12 +00002898 if (OpKind == tok::arrow) {
2899 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2900 ObjectType = Ptr->getPointeeType();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002901 } else if (!ObjectType->isDependentType()) {
Douglas Gregor77549082010-02-24 21:29:12 +00002902 // The user wrote "p->" when she probably meant "p."; fix it.
2903 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002904 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00002905 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor77549082010-02-24 21:29:12 +00002906 if (isSFINAEContext())
2907 return ExprError();
2908
2909 OpKind = tok::period;
2910 }
2911 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002912
2913 // Compute the object type that we should use for name lookup purposes. Only
2914 // record types and dependent types matter.
John McCallb3d87482010-08-24 05:47:05 +00002915 ParsedType ObjectTypePtrForLookup;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002916 if (!SS.isSet()) {
John McCallb3d87482010-08-24 05:47:05 +00002917 if (const Type *T = ObjectType->getAs<RecordType>())
2918 ObjectTypePtrForLookup = ParsedType::make(QualType(T, 0));
2919 else if (ObjectType->isDependentType())
2920 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002921 }
Douglas Gregor77549082010-02-24 21:29:12 +00002922
Douglas Gregorb57fb492010-02-24 22:38:50 +00002923 // Convert the name of the type being destructed (following the ~) into a
2924 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00002925 QualType DestructedType;
2926 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002927 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00002928 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
John McCallb3d87482010-08-24 05:47:05 +00002929 ParsedType T = getTypeName(*SecondTypeName.Identifier,
2930 SecondTypeName.StartLocation,
2931 S, &SS, true, ObjectTypePtrForLookup);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002932 if (!T &&
2933 ((SS.isSet() && !computeDeclContext(SS, false)) ||
2934 (!SS.isSet() && ObjectType->isDependentType()))) {
2935 // The name of the type being destroyed is a dependent name, and we
2936 // couldn't find anything useful in scope. Just store the identifier and
2937 // it's location, and we'll perform (qualified) name lookup again at
2938 // template instantiation time.
2939 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
2940 SecondTypeName.StartLocation);
2941 } else if (!T) {
Douglas Gregor77549082010-02-24 21:29:12 +00002942 Diag(SecondTypeName.StartLocation,
2943 diag::err_pseudo_dtor_destructor_non_type)
2944 << SecondTypeName.Identifier << ObjectType;
2945 if (isSFINAEContext())
2946 return ExprError();
2947
2948 // Recover by assuming we had the right type all along.
2949 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002950 } else
Douglas Gregor77549082010-02-24 21:29:12 +00002951 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002952 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00002953 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00002954 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002955 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2956 TemplateId->getTemplateArgs(),
2957 TemplateId->NumArgs);
John McCall2b5289b2010-08-23 07:28:44 +00002958 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002959 TemplateId->TemplateNameLoc,
2960 TemplateId->LAngleLoc,
2961 TemplateArgsPtr,
2962 TemplateId->RAngleLoc);
2963 if (T.isInvalid() || !T.get()) {
2964 // Recover by assuming we had the right type all along.
2965 DestructedType = ObjectType;
2966 } else
2967 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002968 }
2969
Douglas Gregorb57fb492010-02-24 22:38:50 +00002970 // If we've performed some kind of recovery, (re-)build the type source
2971 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002972 if (!DestructedType.isNull()) {
2973 if (!DestructedTypeInfo)
2974 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002975 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002976 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2977 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00002978
2979 // Convert the name of the scope type (the type prior to '::') into a type.
2980 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00002981 QualType ScopeType;
2982 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2983 FirstTypeName.Identifier) {
2984 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
John McCallb3d87482010-08-24 05:47:05 +00002985 ParsedType T = getTypeName(*FirstTypeName.Identifier,
2986 FirstTypeName.StartLocation,
2987 S, &SS, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00002988 if (!T) {
2989 Diag(FirstTypeName.StartLocation,
2990 diag::err_pseudo_dtor_destructor_non_type)
2991 << FirstTypeName.Identifier << ObjectType;
Douglas Gregor77549082010-02-24 21:29:12 +00002992
Douglas Gregorb57fb492010-02-24 22:38:50 +00002993 if (isSFINAEContext())
2994 return ExprError();
2995
2996 // Just drop this type. It's unnecessary anyway.
2997 ScopeType = QualType();
2998 } else
2999 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003000 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003001 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00003002 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003003 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3004 TemplateId->getTemplateArgs(),
3005 TemplateId->NumArgs);
John McCall2b5289b2010-08-23 07:28:44 +00003006 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003007 TemplateId->TemplateNameLoc,
3008 TemplateId->LAngleLoc,
3009 TemplateArgsPtr,
3010 TemplateId->RAngleLoc);
3011 if (T.isInvalid() || !T.get()) {
3012 // Recover by dropping this type.
3013 ScopeType = QualType();
3014 } else
3015 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003016 }
3017 }
Douglas Gregorb4a418f2010-02-24 23:02:30 +00003018
3019 if (!ScopeType.isNull() && !ScopeTypeInfo)
3020 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
3021 FirstTypeName.StartLocation);
3022
3023
John McCall9ae2f072010-08-23 23:25:46 +00003024 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00003025 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003026 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00003027}
3028
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003029CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
John McCall6bb80172010-03-30 21:47:33 +00003030 NamedDecl *FoundDecl,
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003031 CXXMethodDecl *Method) {
John McCall6bb80172010-03-30 21:47:33 +00003032 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
3033 FoundDecl, Method))
Eli Friedman772fffa2009-12-09 04:53:56 +00003034 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
3035
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003036 MemberExpr *ME =
Abramo Bagnara25777432010-08-11 22:01:17 +00003037 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003038 SourceLocation(), Method->getType());
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003039 QualType ResultType = Method->getCallResultType();
Douglas Gregor7edfb692009-11-23 12:27:39 +00003040 MarkDeclarationReferenced(Exp->getLocStart(), Method);
3041 CXXMemberCallExpr *CE =
3042 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
3043 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003044 return CE;
3045}
3046
John McCall9ae2f072010-08-23 23:25:46 +00003047Sema::OwningExprResult Sema::ActOnFinishFullExpr(Expr *FullExpr) {
3048 if (!FullExpr) return ExprError();
3049 return MaybeCreateCXXExprWithTemporaries(FullExpr);
Anders Carlsson165a0a02009-05-17 18:41:29 +00003050}