blob: acdc15fdf2836fbef96bf4c923d76db899021f41 [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
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall2a7fb272010-08-25 05:32:35 +000015#include "clang/Sema/DeclSpec.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
John McCall2a7fb272010-08-25 05:32:35 +000018#include "clang/Sema/ParsedTemplate.h"
19#include "clang/Sema/TemplateDeduction.h"
Steve Naroff210679c2007-08-25 14:02:58 +000020#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000021#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000023#include "clang/AST/ExprCXX.h"
Fariborz Jahaniand4266622010-06-16 18:56:04 +000024#include "clang/AST/ExprObjC.h"
Douglas Gregorb57fb492010-02-24 22:38:50 +000025#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000026#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000027#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000028#include "clang/Lex/Preprocessor.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000029#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000030using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000031using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000032
John McCallb3d87482010-08-24 05:47:05 +000033ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
34 IdentifierInfo &II,
35 SourceLocation NameLoc,
36 Scope *S, CXXScopeSpec &SS,
37 ParsedType ObjectTypePtr,
38 bool EnteringContext) {
Douglas Gregor124b8782010-02-16 19:09:40 +000039 // Determine where to perform name lookup.
40
41 // FIXME: This area of the standard is very messy, and the current
42 // wording is rather unclear about which scopes we search for the
43 // destructor name; see core issues 399 and 555. Issue 399 in
44 // particular shows where the current description of destructor name
45 // lookup is completely out of line with existing practice, e.g.,
46 // this appears to be ill-formed:
47 //
48 // namespace N {
49 // template <typename T> struct S {
50 // ~S();
51 // };
52 // }
53 //
54 // void f(N::S<int>* s) {
55 // s->N::S<int>::~S();
56 // }
57 //
Douglas Gregor93649fd2010-02-23 00:15:22 +000058 // See also PR6358 and PR6359.
Sebastian Redlc0fee502010-07-07 23:17:38 +000059 // For this reason, we're currently only doing the C++03 version of this
60 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregor124b8782010-02-16 19:09:40 +000061 QualType SearchType;
62 DeclContext *LookupCtx = 0;
63 bool isDependent = false;
64 bool LookInScope = false;
65
66 // If we have an object type, it's because we are in a
67 // pseudo-destructor-expression or a member access expression, and
68 // we know what type we're looking for.
69 if (ObjectTypePtr)
70 SearchType = GetTypeFromParser(ObjectTypePtr);
71
72 if (SS.isSet()) {
Douglas Gregor93649fd2010-02-23 00:15:22 +000073 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
74
75 bool AlreadySearched = false;
76 bool LookAtPrefix = true;
Sebastian Redlc0fee502010-07-07 23:17:38 +000077 // C++ [basic.lookup.qual]p6:
78 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
79 // the type-names are looked up as types in the scope designated by the
80 // nested-name-specifier. In a qualified-id of the form:
81 //
82 // ::[opt] nested-name-specifier ̃ class-name
83 //
84 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth5e895a82010-02-21 10:19:54 +000085 // a qualified-id of the form:
Douglas Gregor124b8782010-02-16 19:09:40 +000086 //
Sebastian Redlc0fee502010-07-07 23:17:38 +000087 // ::opt nested-name-specifier class-name :: ̃ class-name
Douglas Gregor124b8782010-02-16 19:09:40 +000088 //
Sebastian Redlc0fee502010-07-07 23:17:38 +000089 // the class-names are looked up as types in the scope designated by
90 // the nested-name-specifier.
Douglas Gregor124b8782010-02-16 19:09:40 +000091 //
Sebastian Redlc0fee502010-07-07 23:17:38 +000092 // Here, we check the first case (completely) and determine whether the
93 // code below is permitted to look at the prefix of the
94 // nested-name-specifier.
95 DeclContext *DC = computeDeclContext(SS, EnteringContext);
96 if (DC && DC->isFileContext()) {
97 AlreadySearched = true;
98 LookupCtx = DC;
99 isDependent = false;
100 } else if (DC && isa<CXXRecordDecl>(DC))
101 LookAtPrefix = false;
102
103 // The second case from the C++03 rules quoted further above.
Douglas Gregor93649fd2010-02-23 00:15:22 +0000104 NestedNameSpecifier *Prefix = 0;
105 if (AlreadySearched) {
106 // Nothing left to do.
107 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
108 CXXScopeSpec PrefixSS;
109 PrefixSS.setScopeRep(Prefix);
110 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
111 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000112 } else if (ObjectTypePtr) {
Douglas Gregor124b8782010-02-16 19:09:40 +0000113 LookupCtx = computeDeclContext(SearchType);
114 isDependent = SearchType->isDependentType();
115 } else {
116 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000117 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregor124b8782010-02-16 19:09:40 +0000118 }
Douglas Gregor93649fd2010-02-23 00:15:22 +0000119
Douglas Gregoredc90502010-02-25 04:46:04 +0000120 LookInScope = false;
Douglas Gregor124b8782010-02-16 19:09:40 +0000121 } else if (ObjectTypePtr) {
122 // C++ [basic.lookup.classref]p3:
123 // If the unqualified-id is ~type-name, the type-name is looked up
124 // in the context of the entire postfix-expression. If the type T
125 // of the object expression is of a class type C, the type-name is
126 // also looked up in the scope of class C. At least one of the
127 // lookups shall find a name that refers to (possibly
128 // cv-qualified) T.
129 LookupCtx = computeDeclContext(SearchType);
130 isDependent = SearchType->isDependentType();
131 assert((isDependent || !SearchType->isIncompleteType()) &&
132 "Caller should have completed object type");
133
134 LookInScope = true;
135 } else {
136 // Perform lookup into the current scope (only).
137 LookInScope = true;
138 }
139
140 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
141 for (unsigned Step = 0; Step != 2; ++Step) {
142 // Look for the name first in the computed lookup context (if we
143 // have one) and, if that fails to find a match, in the sope (if
144 // we're allowed to look there).
145 Found.clear();
146 if (Step == 0 && LookupCtx)
147 LookupQualifiedName(Found, LookupCtx);
Douglas Gregora2e7dd22010-02-25 01:56:36 +0000148 else if (Step == 1 && LookInScope && S)
Douglas Gregor124b8782010-02-16 19:09:40 +0000149 LookupName(Found, S);
150 else
151 continue;
152
153 // FIXME: Should we be suppressing ambiguities here?
154 if (Found.isAmbiguous())
John McCallb3d87482010-08-24 05:47:05 +0000155 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000156
157 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
158 QualType T = Context.getTypeDeclType(Type);
Douglas Gregor124b8782010-02-16 19:09:40 +0000159
160 if (SearchType.isNull() || SearchType->isDependentType() ||
161 Context.hasSameUnqualifiedType(T, SearchType)) {
162 // We found our type!
163
John McCallb3d87482010-08-24 05:47:05 +0000164 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000165 }
166 }
167
168 // If the name that we found is a class template name, and it is
169 // the same name as the template name in the last part of the
170 // nested-name-specifier (if present) or the object type, then
171 // this is the destructor for that class.
172 // FIXME: This is a workaround until we get real drafting for core
173 // issue 399, for which there isn't even an obvious direction.
174 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
175 QualType MemberOfType;
176 if (SS.isSet()) {
177 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
178 // Figure out the type of the context, if it has one.
John McCall3cb0ebd2010-03-10 03:28:59 +0000179 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
180 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregor124b8782010-02-16 19:09:40 +0000181 }
182 }
183 if (MemberOfType.isNull())
184 MemberOfType = SearchType;
185
186 if (MemberOfType.isNull())
187 continue;
188
189 // We're referring into a class template specialization. If the
190 // class template we found is the same as the template being
191 // specialized, we found what we are looking for.
192 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
193 if (ClassTemplateSpecializationDecl *Spec
194 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
195 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
196 Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000197 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000198 }
199
200 continue;
201 }
202
203 // We're referring to an unresolved class template
204 // specialization. Determine whether we class template we found
205 // is the same as the template being specialized or, if we don't
206 // know which template is being specialized, that it at least
207 // has the same name.
208 if (const TemplateSpecializationType *SpecType
209 = MemberOfType->getAs<TemplateSpecializationType>()) {
210 TemplateName SpecName = SpecType->getTemplateName();
211
212 // The class template we found is the same template being
213 // specialized.
214 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
215 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000216 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000217
218 continue;
219 }
220
221 // The class template we found has the same name as the
222 // (dependent) template name being specialized.
223 if (DependentTemplateName *DepTemplate
224 = SpecName.getAsDependentTemplateName()) {
225 if (DepTemplate->isIdentifier() &&
226 DepTemplate->getIdentifier() == Template->getIdentifier())
John McCallb3d87482010-08-24 05:47:05 +0000227 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000228
229 continue;
230 }
231 }
232 }
233 }
234
235 if (isDependent) {
236 // We didn't find our type, but that's okay: it's dependent
237 // anyway.
238 NestedNameSpecifier *NNS = 0;
239 SourceRange Range;
240 if (SS.isSet()) {
241 NNS = (NestedNameSpecifier *)SS.getScopeRep();
242 Range = SourceRange(SS.getRange().getBegin(), NameLoc);
243 } else {
244 NNS = NestedNameSpecifier::Create(Context, &II);
245 Range = SourceRange(NameLoc);
246 }
247
John McCallb3d87482010-08-24 05:47:05 +0000248 QualType T = CheckTypenameType(ETK_None, NNS, II,
249 SourceLocation(),
250 Range, NameLoc);
251 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000252 }
253
254 if (ObjectTypePtr)
255 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
256 << &II;
257 else
258 Diag(NameLoc, diag::err_destructor_class_name);
259
John McCallb3d87482010-08-24 05:47:05 +0000260 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000261}
262
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000263/// \brief Build a C++ typeid expression with a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000264ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000265 SourceLocation TypeidLoc,
266 TypeSourceInfo *Operand,
267 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000268 // C++ [expr.typeid]p4:
269 // The top-level cv-qualifiers of the lvalue expression or the type-id
270 // that is the operand of typeid are always ignored.
271 // If the type of the type-id is a class type or a reference to a class
272 // type, the class shall be completely-defined.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000273 Qualifiers Quals;
274 QualType T
275 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
276 Quals);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000277 if (T->getAs<RecordType>() &&
278 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
279 return ExprError();
Daniel Dunbar380c2132010-05-11 21:32:35 +0000280
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000281 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
282 Operand,
283 SourceRange(TypeidLoc, RParenLoc)));
284}
285
286/// \brief Build a C++ typeid expression with an expression operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000287ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000288 SourceLocation TypeidLoc,
289 Expr *E,
290 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000291 bool isUnevaluatedOperand = true;
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000292 if (E && !E->isTypeDependent()) {
293 QualType T = E->getType();
294 if (const RecordType *RecordT = T->getAs<RecordType>()) {
295 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
296 // C++ [expr.typeid]p3:
297 // [...] If the type of the expression is a class type, the class
298 // shall be completely-defined.
299 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
300 return ExprError();
301
302 // C++ [expr.typeid]p3:
Sebastian Redl906082e2010-07-20 04:20:21 +0000303 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000304 // polymorphic class type [...] [the] expression is an unevaluated
305 // operand. [...]
Sebastian Redl906082e2010-07-20 04:20:21 +0000306 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000307 isUnevaluatedOperand = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000308
309 // We require a vtable to query the type at run time.
310 MarkVTableUsed(TypeidLoc, RecordD);
311 }
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000312 }
313
314 // C++ [expr.typeid]p4:
315 // [...] If the type of the type-id is a reference to a possibly
316 // cv-qualified type, the result of the typeid expression refers to a
317 // std::type_info object representing the cv-unqualified referenced
318 // type.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000319 Qualifiers Quals;
320 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
321 if (!Context.hasSameType(T, UnqualT)) {
322 T = UnqualT;
John McCall2de56d12010-08-25 11:45:40 +0000323 ImpCastExprToType(E, UnqualT, CK_NoOp, CastCategory(E));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000324 }
325 }
326
327 // If this is an unevaluated operand, clear out the set of
328 // declaration references we have been computing and eliminate any
329 // temporaries introduced in its computation.
330 if (isUnevaluatedOperand)
331 ExprEvalContexts.back().Context = Unevaluated;
332
333 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCall9ae2f072010-08-23 23:25:46 +0000334 E,
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000335 SourceRange(TypeidLoc, RParenLoc)));
336}
337
338/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCall60d7b3a2010-08-24 06:29:42 +0000339ExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000340Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
341 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000342 // Find the std::type_info type.
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000343 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000344 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000345
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000346 if (!CXXTypeInfoDecl) {
347 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
348 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
349 LookupQualifiedName(R, getStdNamespace());
350 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
351 if (!CXXTypeInfoDecl)
352 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
353 }
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000354
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000355 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000356
357 if (isType) {
358 // The operand is a type; handle it as such.
359 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +0000360 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
361 &TInfo);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000362 if (T.isNull())
363 return ExprError();
364
365 if (!TInfo)
366 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000367
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000368 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000369 }
Mike Stump1eb44332009-09-09 15:08:12 +0000370
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000371 // The operand is an expression.
John McCall9ae2f072010-08-23 23:25:46 +0000372 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000373}
374
Francois Pichet6915c522010-12-27 01:32:00 +0000375/// Retrieve the UuidAttr associated with QT.
376static UuidAttr *GetUuidAttrOfType(QualType QT) {
377 // Optionally remove one level of pointer, reference or array indirection.
John McCallf4c73712011-01-19 06:33:43 +0000378 const Type *Ty = QT.getTypePtr();;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000379 if (QT->isPointerType() || QT->isReferenceType())
380 Ty = QT->getPointeeType().getTypePtr();
381 else if (QT->isArrayType())
382 Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
383
Francois Pichet6915c522010-12-27 01:32:00 +0000384 // Loop all class definition and declaration looking for an uuid attribute.
385 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
386 while (RD) {
387 if (UuidAttr *Uuid = RD->getAttr<UuidAttr>())
388 return Uuid;
389 RD = RD->getPreviousDeclaration();
390 }
391 return 0;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000392}
393
Francois Pichet01b7c302010-09-08 12:20:18 +0000394/// \brief Build a Microsoft __uuidof expression with a type operand.
395ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
396 SourceLocation TypeidLoc,
397 TypeSourceInfo *Operand,
398 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000399 if (!Operand->getType()->isDependentType()) {
400 if (!GetUuidAttrOfType(Operand->getType()))
401 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
402 }
403
Francois Pichet01b7c302010-09-08 12:20:18 +0000404 // FIXME: add __uuidof semantic analysis for type operand.
405 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
406 Operand,
407 SourceRange(TypeidLoc, RParenLoc)));
408}
409
410/// \brief Build a Microsoft __uuidof expression with an expression operand.
411ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
412 SourceLocation TypeidLoc,
413 Expr *E,
414 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000415 if (!E->getType()->isDependentType()) {
416 if (!GetUuidAttrOfType(E->getType()) &&
417 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
418 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
419 }
420 // FIXME: add __uuidof semantic analysis for type operand.
Francois Pichet01b7c302010-09-08 12:20:18 +0000421 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
422 E,
423 SourceRange(TypeidLoc, RParenLoc)));
424}
425
426/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
427ExprResult
428Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
429 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
430 // If MSVCGuidDecl has not been cached, do the lookup.
431 if (!MSVCGuidDecl) {
432 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
433 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
434 LookupQualifiedName(R, Context.getTranslationUnitDecl());
435 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
436 if (!MSVCGuidDecl)
437 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
438 }
439
440 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
441
442 if (isType) {
443 // The operand is a type; handle it as such.
444 TypeSourceInfo *TInfo = 0;
445 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
446 &TInfo);
447 if (T.isNull())
448 return ExprError();
449
450 if (!TInfo)
451 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
452
453 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
454 }
455
456 // The operand is an expression.
457 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
458}
459
Steve Naroff1b273c42007-09-16 14:56:35 +0000460/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCall60d7b3a2010-08-24 06:29:42 +0000461ExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000462Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000463 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000464 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000465 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
466 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000467}
Chris Lattner50dd2892008-02-26 00:51:44 +0000468
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000469/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCall60d7b3a2010-08-24 06:29:42 +0000470ExprResult
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000471Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
472 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
473}
474
Chris Lattner50dd2892008-02-26 00:51:44 +0000475/// ActOnCXXThrow - Parse throw expressions.
John McCall60d7b3a2010-08-24 06:29:42 +0000476ExprResult
John McCall9ae2f072010-08-23 23:25:46 +0000477Sema::ActOnCXXThrow(SourceLocation OpLoc, Expr *Ex) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000478 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
479 return ExprError();
480 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
481}
482
483/// CheckCXXThrowOperand - Validate the operand of a throw.
484bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
485 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000486 // A throw-expression initializes a temporary object, called the exception
487 // object, the type of which is determined by removing any top-level
488 // cv-qualifiers from the static type of the operand of throw and adjusting
489 // the type from "array of T" or "function returning T" to "pointer to T"
490 // or "pointer to function returning T", [...]
491 if (E->getType().hasQualifiers())
John McCall2de56d12010-08-25 11:45:40 +0000492 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
Sebastian Redl906082e2010-07-20 04:20:21 +0000493 CastCategory(E));
Douglas Gregor154fe982009-12-23 22:04:40 +0000494
Sebastian Redl972041f2009-04-27 20:27:31 +0000495 DefaultFunctionArrayConversion(E);
496
497 // If the type of the exception would be an incomplete type or a pointer
498 // to an incomplete type other than (cv) void the program is ill-formed.
499 QualType Ty = E->getType();
John McCallac418162010-04-22 01:10:34 +0000500 bool isPointer = false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000501 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000502 Ty = Ptr->getPointeeType();
John McCallac418162010-04-22 01:10:34 +0000503 isPointer = true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000504 }
505 if (!isPointer || !Ty->isVoidType()) {
506 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000507 PDiag(isPointer ? diag::err_throw_incomplete_ptr
508 : diag::err_throw_incomplete)
509 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000510 return true;
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000511
Douglas Gregorbf422f92010-04-15 18:05:39 +0000512 if (RequireNonAbstractType(ThrowLoc, E->getType(),
513 PDiag(diag::err_throw_abstract_type)
514 << E->getSourceRange()))
515 return true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000516 }
517
John McCallac418162010-04-22 01:10:34 +0000518 // Initialize the exception result. This implicitly weeds out
519 // abstract types or types with inaccessible copy constructors.
Douglas Gregor72dfa272011-01-21 22:46:35 +0000520 const VarDecl *NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
521
Douglas Gregorf5d8f462011-01-21 18:05:27 +0000522 // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p32.
John McCallac418162010-04-22 01:10:34 +0000523 InitializedEntity Entity =
Douglas Gregor72dfa272011-01-21 22:46:35 +0000524 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
525 /*NRVO=*/false);
526 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
527 QualType(), E);
John McCallac418162010-04-22 01:10:34 +0000528 if (Res.isInvalid())
529 return true;
530 E = Res.takeAs<Expr>();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000531
Eli Friedman5ed9b932010-06-03 20:39:03 +0000532 // If the exception has class type, we need additional handling.
533 const RecordType *RecordTy = Ty->getAs<RecordType>();
534 if (!RecordTy)
535 return false;
536 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
537
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000538 // If we are throwing a polymorphic class type or pointer thereof,
539 // exception handling will make use of the vtable.
Eli Friedman5ed9b932010-06-03 20:39:03 +0000540 MarkVTableUsed(ThrowLoc, RD);
541
Eli Friedman98efb9f2010-10-12 20:32:36 +0000542 // If a pointer is thrown, the referenced object will not be destroyed.
543 if (isPointer)
544 return false;
545
Eli Friedman5ed9b932010-06-03 20:39:03 +0000546 // If the class has a non-trivial destructor, we must be able to call it.
547 if (RD->hasTrivialDestructor())
548 return false;
549
Douglas Gregor1d110e02010-07-01 14:13:13 +0000550 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +0000551 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman5ed9b932010-06-03 20:39:03 +0000552 if (!Destructor)
553 return false;
554
555 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
556 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregored8abf12010-07-08 06:14:04 +0000557 PDiag(diag::err_access_dtor_exception) << Ty);
Sebastian Redl972041f2009-04-27 20:27:31 +0000558 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000559}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000560
John McCall60d7b3a2010-08-24 06:29:42 +0000561ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000562 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
563 /// is a non-lvalue expression whose value is the address of the object for
564 /// which the function is called.
565
John McCallea1471e2010-05-20 01:18:31 +0000566 DeclContext *DC = getFunctionLevelDeclContext();
567 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000568 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000569 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000570 MD->getThisType(Context),
571 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000572
Sebastian Redlf53597f2009-03-15 17:47:39 +0000573 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000574}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000575
John McCall60d7b3a2010-08-24 06:29:42 +0000576ExprResult
Douglas Gregorab6677e2010-09-08 00:15:04 +0000577Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000578 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000579 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000580 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000581 if (!TypeRep)
582 return ExprError();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000583
John McCall9d125032010-01-15 18:39:57 +0000584 TypeSourceInfo *TInfo;
585 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
586 if (!TInfo)
587 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregorab6677e2010-09-08 00:15:04 +0000588
589 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
590}
591
592/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
593/// Can be interpreted either as function-style casting ("int(x)")
594/// or class type construction ("ClassType(x,y,z)")
595/// or creation of a value-initialized type ("int()").
596ExprResult
597Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
598 SourceLocation LParenLoc,
599 MultiExprArg exprs,
600 SourceLocation RParenLoc) {
601 QualType Ty = TInfo->getType();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000602 unsigned NumExprs = exprs.size();
603 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000604 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000605 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
606
Sebastian Redlf53597f2009-03-15 17:47:39 +0000607 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000608 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000609 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000610
Douglas Gregorab6677e2010-09-08 00:15:04 +0000611 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000612 LParenLoc,
613 Exprs, NumExprs,
614 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000615 }
616
Anders Carlssonbb60a502009-08-27 03:53:50 +0000617 if (Ty->isArrayType())
618 return ExprError(Diag(TyBeginLoc,
619 diag::err_value_init_for_array_type) << FullRange);
620 if (!Ty->isVoidType() &&
621 RequireCompleteType(TyBeginLoc, Ty,
622 PDiag(diag::err_invalid_incomplete_type_use)
623 << FullRange))
624 return ExprError();
Fariborz Jahanianf071e9b2009-10-23 21:01:39 +0000625
Anders Carlssonbb60a502009-08-27 03:53:50 +0000626 if (RequireNonAbstractType(TyBeginLoc, Ty,
627 diag::err_allocation_of_abstract_type))
628 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000629
630
Douglas Gregor506ae412009-01-16 18:33:17 +0000631 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000632 // If the expression list is a single expression, the type conversion
633 // expression is equivalent (in definedness, and if defined in meaning) to the
634 // corresponding cast expression.
635 //
636 if (NumExprs == 1) {
John McCalldaa8e4e2010-11-15 09:13:47 +0000637 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +0000638 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +0000639 CXXCastPath BasePath;
Douglas Gregorab6677e2010-09-08 00:15:04 +0000640 if (CheckCastTypes(TInfo->getTypeLoc().getSourceRange(), Ty, Exprs[0],
John McCallf89e55a2010-11-18 06:31:45 +0000641 Kind, VK, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000642 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000643 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000644
645 exprs.release();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000646
John McCallf871d0c2010-08-07 06:22:56 +0000647 return Owned(CXXFunctionalCastExpr::Create(Context,
Douglas Gregorab6677e2010-09-08 00:15:04 +0000648 Ty.getNonLValueExprType(Context),
John McCallf89e55a2010-11-18 06:31:45 +0000649 VK, TInfo, TyBeginLoc, Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000650 Exprs[0], &BasePath,
651 RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000652 }
653
Douglas Gregor19311e72010-09-08 21:40:08 +0000654 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
655 InitializationKind Kind
656 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
657 LParenLoc, RParenLoc)
658 : InitializationKind::CreateValue(TyBeginLoc,
659 LParenLoc, RParenLoc);
660 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
661 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redlf53597f2009-03-15 17:47:39 +0000662
Douglas Gregor19311e72010-09-08 21:40:08 +0000663 // FIXME: Improve AST representation?
664 return move(Result);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000665}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000666
667
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000668/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
669/// @code new (memory) int[size][4] @endcode
670/// or
671/// @code ::new Foo(23, "hello") @endcode
672/// For the interpretation of this heap of arguments, consult the base version.
John McCall60d7b3a2010-08-24 06:29:42 +0000673ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000674Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000675 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000676 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000677 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000678 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000679 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000680 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000681 // If the specified type is an array, unwrap it and save the expression.
682 if (D.getNumTypeObjects() > 0 &&
683 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
684 DeclaratorChunk &Chunk = D.getTypeObject(0);
685 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000686 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
687 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000688 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000689 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
690 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000691
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000692 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000693 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000694 }
695
Douglas Gregor043cad22009-09-11 00:18:58 +0000696 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000697 if (ArraySize) {
698 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000699 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
700 break;
701
702 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
703 if (Expr *NumElts = (Expr *)Array.NumElts) {
704 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
705 !NumElts->isIntegerConstantExpr(Context)) {
706 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
707 << NumElts->getSourceRange();
708 return ExprError();
709 }
710 }
711 }
712 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000713
John McCallbf1a0282010-06-04 23:28:52 +0000714 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
715 QualType AllocType = TInfo->getType();
Chris Lattnereaaebc72009-04-25 08:06:05 +0000716 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000717 return ExprError();
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000718
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000719 if (!TInfo)
720 TInfo = Context.getTrivialTypeSourceInfo(AllocType);
721
Mike Stump1eb44332009-09-09 15:08:12 +0000722 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000723 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000724 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000725 PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000726 TypeIdParens,
Mike Stump1eb44332009-09-09 15:08:12 +0000727 AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000728 TInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000729 ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000730 ConstructorLParen,
731 move(ConstructorArgs),
732 ConstructorRParen);
733}
734
John McCall60d7b3a2010-08-24 06:29:42 +0000735ExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000736Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
737 SourceLocation PlacementLParen,
738 MultiExprArg PlacementArgs,
739 SourceLocation PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000740 SourceRange TypeIdParens,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000741 QualType AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000742 TypeSourceInfo *AllocTypeInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000743 Expr *ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000744 SourceLocation ConstructorLParen,
745 MultiExprArg ConstructorArgs,
746 SourceLocation ConstructorRParen) {
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000747 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000748
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000749 // Per C++0x [expr.new]p5, the type being constructed may be a
750 // typedef of an array type.
John McCall9ae2f072010-08-23 23:25:46 +0000751 if (!ArraySize) {
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000752 if (const ConstantArrayType *Array
753 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000754 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
755 Context.getSizeType(),
756 TypeRange.getEnd());
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000757 AllocType = Array->getElementType();
758 }
759 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000760
Douglas Gregora0750762010-10-06 16:00:31 +0000761 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
762 return ExprError();
763
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000764 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000765
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000766 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
767 // or enumeration type with a non-negative value."
Sebastian Redl28507842009-02-26 14:39:58 +0000768 if (ArraySize && !ArraySize->isTypeDependent()) {
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000769
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000770 QualType SizeType = ArraySize->getType();
Douglas Gregorc30614b2010-06-29 23:17:37 +0000771
John McCall60d7b3a2010-08-24 06:29:42 +0000772 ExprResult ConvertedSize
John McCall9ae2f072010-08-23 23:25:46 +0000773 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000774 PDiag(diag::err_array_size_not_integral),
775 PDiag(diag::err_array_size_incomplete_type)
776 << ArraySize->getSourceRange(),
777 PDiag(diag::err_array_size_explicit_conversion),
778 PDiag(diag::note_array_size_conversion),
779 PDiag(diag::err_array_size_ambiguous_conversion),
780 PDiag(diag::note_array_size_conversion),
781 PDiag(getLangOptions().CPlusPlus0x? 0
782 : diag::ext_array_size_conversion));
783 if (ConvertedSize.isInvalid())
784 return ExprError();
785
John McCall9ae2f072010-08-23 23:25:46 +0000786 ArraySize = ConvertedSize.take();
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000787 SizeType = ArraySize->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000788 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000789 return ExprError();
790
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000791 // Let's see if this is a constant < 0. If so, we reject it out of hand.
792 // We don't care about special rules, so we tell the machinery it's not
793 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000794 if (!ArraySize->isValueDependent()) {
795 llvm::APSInt Value;
796 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
797 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000798 llvm::APInt::getNullValue(Value.getBitWidth()),
799 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000800 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +0000801 diag::err_typecheck_negative_array_size)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000802 << ArraySize->getSourceRange());
Douglas Gregor2767ce22010-08-18 00:39:00 +0000803
804 if (!AllocType->isDependentType()) {
805 unsigned ActiveSizeBits
806 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
807 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
808 Diag(ArraySize->getSourceRange().getBegin(),
809 diag::err_array_too_large)
810 << Value.toString(10)
811 << ArraySize->getSourceRange();
812 return ExprError();
813 }
814 }
Douglas Gregor4bd40312010-07-13 15:54:32 +0000815 } else if (TypeIdParens.isValid()) {
816 // Can't have dynamic array size when the type-id is in parentheses.
817 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
818 << ArraySize->getSourceRange()
819 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
820 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
821
822 TypeIdParens = SourceRange();
Sebastian Redl28507842009-02-26 14:39:58 +0000823 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000824 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000825
Eli Friedman73c39ab2009-10-20 08:27:19 +0000826 ImpCastExprToType(ArraySize, Context.getSizeType(),
John McCall2de56d12010-08-25 11:45:40 +0000827 CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000828 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000829
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000830 FunctionDecl *OperatorNew = 0;
831 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000832 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
833 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000834
Sebastian Redl28507842009-02-26 14:39:58 +0000835 if (!AllocType->isDependentType() &&
836 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
837 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000838 SourceRange(PlacementLParen, PlacementRParen),
839 UseGlobal, AllocType, ArraySize, PlaceArgs,
840 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000841 return ExprError();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000842 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000843 if (OperatorNew) {
844 // Add default arguments, if any.
845 const FunctionProtoType *Proto =
846 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000847 VariadicCallType CallType =
848 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Anders Carlsson28e94832010-05-03 02:07:56 +0000849
850 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
851 Proto, 1, PlaceArgs, NumPlaceArgs,
852 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000853 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000854
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000855 NumPlaceArgs = AllPlaceArgs.size();
856 if (NumPlaceArgs > 0)
857 PlaceArgs = &AllPlaceArgs[0];
858 }
859
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000860 bool Init = ConstructorLParen.isValid();
861 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000862 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000863 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
864 unsigned NumConsArgs = ConstructorArgs.size();
John McCallca0408f2010-08-23 06:44:23 +0000865 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000866
Anders Carlsson48c95012010-05-03 15:45:23 +0000867 // Array 'new' can't have any initializers.
Anders Carlsson55cbd6e2010-05-16 16:24:20 +0000868 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlsson48c95012010-05-03 15:45:23 +0000869 SourceRange InitRange(ConsArgs[0]->getLocStart(),
870 ConsArgs[NumConsArgs - 1]->getLocEnd());
871
872 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
873 return ExprError();
874 }
875
Douglas Gregor99a2e602009-12-16 01:38:02 +0000876 if (!AllocType->isDependentType() &&
877 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
878 // C++0x [expr.new]p15:
879 // A new-expression that creates an object of type T initializes that
880 // object as follows:
881 InitializationKind Kind
882 // - If the new-initializer is omitted, the object is default-
883 // initialized (8.5); if no initialization is performed,
884 // the object has indeterminate value
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000885 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
Douglas Gregor99a2e602009-12-16 01:38:02 +0000886 // - Otherwise, the new-initializer is interpreted according to the
887 // initialization rules of 8.5 for direct-initialization.
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000888 : InitializationKind::CreateDirect(TypeRange.getBegin(),
Douglas Gregor99a2e602009-12-16 01:38:02 +0000889 ConstructorLParen,
890 ConstructorRParen);
891
Douglas Gregor99a2e602009-12-16 01:38:02 +0000892 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +0000893 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000894 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
John McCall60d7b3a2010-08-24 06:29:42 +0000895 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor99a2e602009-12-16 01:38:02 +0000896 move(ConstructorArgs));
897 if (FullInit.isInvalid())
898 return ExprError();
899
900 // FullInit is our initializer; walk through it to determine if it's a
901 // constructor call, which CXXNewExpr handles directly.
902 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
903 if (CXXBindTemporaryExpr *Binder
904 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
905 FullInitExpr = Binder->getSubExpr();
906 if (CXXConstructExpr *Construct
907 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
908 Constructor = Construct->getConstructor();
909 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
910 AEnd = Construct->arg_end();
911 A != AEnd; ++A)
John McCall3fa5cae2010-10-26 07:05:15 +0000912 ConvertedConstructorArgs.push_back(*A);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000913 } else {
914 // Take the converted initializer.
915 ConvertedConstructorArgs.push_back(FullInit.release());
916 }
917 } else {
918 // No initialization required.
919 }
920
921 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +0000922 NumConsArgs = ConvertedConstructorArgs.size();
923 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000924 }
Douglas Gregor99a2e602009-12-16 01:38:02 +0000925
Douglas Gregor6d908702010-02-26 05:06:18 +0000926 // Mark the new and delete operators as referenced.
927 if (OperatorNew)
928 MarkDeclarationReferenced(StartLoc, OperatorNew);
929 if (OperatorDelete)
930 MarkDeclarationReferenced(StartLoc, OperatorDelete);
931
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000932 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000933
Sebastian Redlf53597f2009-03-15 17:47:39 +0000934 PlacementArgs.release();
935 ConstructorArgs.release();
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000936
Ted Kremenekad7fe862010-02-11 22:51:03 +0000937 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000938 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenekad7fe862010-02-11 22:51:03 +0000939 ArraySize, Constructor, Init,
940 ConsArgs, NumConsArgs, OperatorDelete,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000941 ResultType, AllocTypeInfo,
942 StartLoc,
Ted Kremenekad7fe862010-02-11 22:51:03 +0000943 Init ? ConstructorRParen :
Chandler Carruth428edaf2010-10-25 08:47:36 +0000944 TypeRange.getEnd(),
945 ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000946}
947
948/// CheckAllocatedType - Checks that a type is suitable as the allocated type
949/// in a new-expression.
950/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000951bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000952 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000953 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
954 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000955 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000956 return Diag(Loc, diag::err_bad_new_type)
957 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000958 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000959 return Diag(Loc, diag::err_bad_new_type)
960 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000961 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000962 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000963 PDiag(diag::err_new_incomplete_type)
964 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000965 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000966 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000967 diag::err_allocation_of_abstract_type))
968 return true;
Douglas Gregora0750762010-10-06 16:00:31 +0000969 else if (AllocType->isVariablyModifiedType())
970 return Diag(Loc, diag::err_variably_modified_new_type)
971 << AllocType;
972
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000973 return false;
974}
975
Douglas Gregor6d908702010-02-26 05:06:18 +0000976/// \brief Determine whether the given function is a non-placement
977/// deallocation function.
978static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
979 if (FD->isInvalidDecl())
980 return false;
981
982 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
983 return Method->isUsualDeallocationFunction();
984
985 return ((FD->getOverloadedOperator() == OO_Delete ||
986 FD->getOverloadedOperator() == OO_Array_Delete) &&
987 FD->getNumParams() == 1);
988}
989
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000990/// FindAllocationFunctions - Finds the overloads of operator new and delete
991/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000992bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
993 bool UseGlobal, QualType AllocType,
994 bool IsArray, Expr **PlaceArgs,
995 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000996 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000997 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000998 // --- Choosing an allocation function ---
999 // C++ 5.3.4p8 - 14 & 18
1000 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1001 // in the scope of the allocated class.
1002 // 2) If an array size is given, look for operator new[], else look for
1003 // operator new.
1004 // 3) The first argument is always size_t. Append the arguments from the
1005 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001006
1007 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
1008 // We don't care about the actual value of this argument.
1009 // FIXME: Should the Sema create the expression and embed it in the syntax
1010 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00001011 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Anders Carlssond67c4c32009-08-16 20:29:29 +00001012 Context.Target.getPointerWidth(0)),
1013 Context.getSizeType(),
1014 SourceLocation());
1015 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001016 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1017
Douglas Gregor6d908702010-02-26 05:06:18 +00001018 // C++ [expr.new]p8:
1019 // If the allocated type is a non-array type, the allocation
1020 // function’s name is operator new and the deallocation function’s
1021 // name is operator delete. If the allocated type is an array
1022 // type, the allocation function’s name is operator new[] and the
1023 // deallocation function’s name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001024 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1025 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +00001026 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1027 IsArray ? OO_Array_Delete : OO_Delete);
1028
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001029 QualType AllocElemType = Context.getBaseElementType(AllocType);
1030
1031 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +00001032 CXXRecordDecl *Record
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001033 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +00001034 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001035 AllocArgs.size(), Record, /*AllowMissing=*/true,
1036 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001037 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001038 }
1039 if (!OperatorNew) {
1040 // Didn't find a member overload. Look for a global one.
1041 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +00001042 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +00001043 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001044 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1045 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001046 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001047 }
1048
John McCall9c82afc2010-04-20 02:18:25 +00001049 // We don't need an operator delete if we're running under
1050 // -fno-exceptions.
1051 if (!getLangOptions().Exceptions) {
1052 OperatorDelete = 0;
1053 return false;
1054 }
1055
Anders Carlssond9583892009-05-31 20:26:12 +00001056 // FindAllocationOverload can change the passed in arguments, so we need to
1057 // copy them back.
1058 if (NumPlaceArgs > 0)
1059 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001060
Douglas Gregor6d908702010-02-26 05:06:18 +00001061 // C++ [expr.new]p19:
1062 //
1063 // If the new-expression begins with a unary :: operator, the
1064 // deallocation function’s name is looked up in the global
1065 // scope. Otherwise, if the allocated type is a class type T or an
1066 // array thereof, the deallocation function’s name is looked up in
1067 // the scope of T. If this lookup fails to find the name, or if
1068 // the allocated type is not a class type or array thereof, the
1069 // deallocation function’s name is looked up in the global scope.
1070 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001071 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001072 CXXRecordDecl *RD
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001073 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6d908702010-02-26 05:06:18 +00001074 LookupQualifiedName(FoundDelete, RD);
1075 }
John McCall90c8c572010-03-18 08:19:33 +00001076 if (FoundDelete.isAmbiguous())
1077 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +00001078
1079 if (FoundDelete.empty()) {
1080 DeclareGlobalNewDelete();
1081 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1082 }
1083
1084 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +00001085
1086 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1087
John McCalledeb6c92010-09-14 21:34:24 +00001088 // Whether we're looking for a placement operator delete is dictated
1089 // by whether we selected a placement operator new, not by whether
1090 // we had explicit placement arguments. This matters for things like
1091 // struct A { void *operator new(size_t, int = 0); ... };
1092 // A *a = new A()
1093 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1094
1095 if (isPlacementNew) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001096 // C++ [expr.new]p20:
1097 // A declaration of a placement deallocation function matches the
1098 // declaration of a placement allocation function if it has the
1099 // same number of parameters and, after parameter transformations
1100 // (8.3.5), all parameter types except the first are
1101 // identical. [...]
1102 //
1103 // To perform this comparison, we compute the function type that
1104 // the deallocation function should have, and use that type both
1105 // for template argument deduction and for comparison purposes.
John McCalle23cf432010-12-14 08:05:40 +00001106 //
1107 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6d908702010-02-26 05:06:18 +00001108 QualType ExpectedFunctionType;
1109 {
1110 const FunctionProtoType *Proto
1111 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00001112
Douglas Gregor6d908702010-02-26 05:06:18 +00001113 llvm::SmallVector<QualType, 4> ArgTypes;
1114 ArgTypes.push_back(Context.VoidPtrTy);
1115 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1116 ArgTypes.push_back(Proto->getArgType(I));
1117
John McCalle23cf432010-12-14 08:05:40 +00001118 FunctionProtoType::ExtProtoInfo EPI;
1119 EPI.Variadic = Proto->isVariadic();
1120
Douglas Gregor6d908702010-02-26 05:06:18 +00001121 ExpectedFunctionType
1122 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
John McCalle23cf432010-12-14 08:05:40 +00001123 ArgTypes.size(), EPI);
Douglas Gregor6d908702010-02-26 05:06:18 +00001124 }
1125
1126 for (LookupResult::iterator D = FoundDelete.begin(),
1127 DEnd = FoundDelete.end();
1128 D != DEnd; ++D) {
1129 FunctionDecl *Fn = 0;
1130 if (FunctionTemplateDecl *FnTmpl
1131 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1132 // Perform template argument deduction to try to match the
1133 // expected function type.
1134 TemplateDeductionInfo Info(Context, StartLoc);
1135 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1136 continue;
1137 } else
1138 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1139
1140 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001141 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001142 }
1143 } else {
1144 // C++ [expr.new]p20:
1145 // [...] Any non-placement deallocation function matches a
1146 // non-placement allocation function. [...]
1147 for (LookupResult::iterator D = FoundDelete.begin(),
1148 DEnd = FoundDelete.end();
1149 D != DEnd; ++D) {
1150 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1151 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001152 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001153 }
1154 }
1155
1156 // C++ [expr.new]p20:
1157 // [...] If the lookup finds a single matching deallocation
1158 // function, that function will be called; otherwise, no
1159 // deallocation function will be called.
1160 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001161 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001162
1163 // C++0x [expr.new]p20:
1164 // If the lookup finds the two-parameter form of a usual
1165 // deallocation function (3.7.4.2) and that function, considered
1166 // as a placement deallocation function, would have been
1167 // selected as a match for the allocation function, the program
1168 // is ill-formed.
1169 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1170 isNonPlacementDeallocationFunction(OperatorDelete)) {
1171 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1172 << SourceRange(PlaceArgs[0]->getLocStart(),
1173 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1174 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1175 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001176 } else {
1177 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001178 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001179 }
1180 }
1181
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001182 return false;
1183}
1184
Sebastian Redl7f662392008-12-04 22:20:51 +00001185/// FindAllocationOverload - Find an fitting overload for the allocation
1186/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001187bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1188 DeclarationName Name, Expr** Args,
1189 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +00001190 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001191 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1192 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001193 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001194 if (AllowMissing)
1195 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001196 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001197 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001198 }
1199
John McCall90c8c572010-03-18 08:19:33 +00001200 if (R.isAmbiguous())
1201 return true;
1202
1203 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001204
John McCall5769d612010-02-08 23:07:23 +00001205 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001206 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1207 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001208 // Even member operator new/delete are implicitly treated as
1209 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001210 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001211
John McCall9aa472c2010-03-19 07:35:19 +00001212 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1213 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001214 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1215 Candidates,
1216 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001217 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001218 }
1219
John McCall9aa472c2010-03-19 07:35:19 +00001220 FunctionDecl *Fn = cast<FunctionDecl>(D);
1221 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001222 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001223 }
1224
1225 // Do the resolution.
1226 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00001227 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001228 case OR_Success: {
1229 // Got one!
1230 FunctionDecl *FnDecl = Best->Function;
1231 // The first argument is size_t, and the first parameter must be size_t,
1232 // too. This is checked on declaration and can be assumed. (It can't be
1233 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001234 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001235 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1236 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
John McCall60d7b3a2010-08-24 06:29:42 +00001237 ExprResult Result
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001238 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001239 Context,
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001240 FnDecl->getParamDecl(i)),
1241 SourceLocation(),
John McCall3fa5cae2010-10-26 07:05:15 +00001242 Owned(Args[i]));
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001243 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001244 return true;
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001245
1246 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001247 }
1248 Operator = FnDecl;
John McCall9aa472c2010-03-19 07:35:19 +00001249 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001250 return false;
1251 }
1252
1253 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +00001254 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001255 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001256 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001257 return true;
1258
1259 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +00001260 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +00001261 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001262 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001263 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001264
1265 case OR_Deleted:
1266 Diag(StartLoc, diag::err_ovl_deleted_call)
1267 << Best->Function->isDeleted()
1268 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001269 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001270 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001271 }
1272 assert(false && "Unreachable, bad result from BestViableFunction");
1273 return true;
1274}
1275
1276
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001277/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1278/// delete. These are:
1279/// @code
1280/// void* operator new(std::size_t) throw(std::bad_alloc);
1281/// void* operator new[](std::size_t) throw(std::bad_alloc);
1282/// void operator delete(void *) throw();
1283/// void operator delete[](void *) throw();
1284/// @endcode
1285/// Note that the placement and nothrow forms of new are *not* implicitly
1286/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001287void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001288 if (GlobalNewDeleteDeclared)
1289 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001290
1291 // C++ [basic.std.dynamic]p2:
1292 // [...] The following allocation and deallocation functions (18.4) are
1293 // implicitly declared in global scope in each translation unit of a
1294 // program
1295 //
1296 // void* operator new(std::size_t) throw(std::bad_alloc);
1297 // void* operator new[](std::size_t) throw(std::bad_alloc);
1298 // void operator delete(void*) throw();
1299 // void operator delete[](void*) throw();
1300 //
1301 // These implicit declarations introduce only the function names operator
1302 // new, operator new[], operator delete, operator delete[].
1303 //
1304 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1305 // "std" or "bad_alloc" as necessary to form the exception specification.
1306 // However, we do not make these implicit declarations visible to name
1307 // lookup.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001308 if (!StdBadAlloc) {
1309 // The "std::bad_alloc" class has not yet been declared, so build it
1310 // implicitly.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001311 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00001312 getOrCreateStdNamespace(),
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001313 SourceLocation(),
1314 &PP.getIdentifierTable().get("bad_alloc"),
1315 SourceLocation(), 0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001316 getStdBadAlloc()->setImplicit(true);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001317 }
1318
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001319 GlobalNewDeleteDeclared = true;
1320
1321 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1322 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001323 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001324
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001325 DeclareGlobalAllocationFunction(
1326 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001327 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001328 DeclareGlobalAllocationFunction(
1329 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001330 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001331 DeclareGlobalAllocationFunction(
1332 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1333 Context.VoidTy, VoidPtr);
1334 DeclareGlobalAllocationFunction(
1335 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1336 Context.VoidTy, VoidPtr);
1337}
1338
1339/// DeclareGlobalAllocationFunction - Declares a single implicit global
1340/// allocation function if it doesn't already exist.
1341void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001342 QualType Return, QualType Argument,
1343 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001344 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1345
1346 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001347 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001348 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001349 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001350 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001351 // Only look at non-template functions, as it is the predefined,
1352 // non-templated allocation function we are trying to declare here.
1353 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1354 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001355 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001356 Func->getParamDecl(0)->getType().getUnqualifiedType());
1357 // FIXME: Do we need to check for default arguments here?
Douglas Gregor7b868622010-08-18 15:06:25 +00001358 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1359 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00001360 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001361 return;
Douglas Gregor7b868622010-08-18 15:06:25 +00001362 }
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001363 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001364 }
1365 }
1366
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001367 QualType BadAllocType;
1368 bool HasBadAllocExceptionSpec
1369 = (Name.getCXXOverloadedOperator() == OO_New ||
1370 Name.getCXXOverloadedOperator() == OO_Array_New);
1371 if (HasBadAllocExceptionSpec) {
1372 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001373 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001374 }
John McCalle23cf432010-12-14 08:05:40 +00001375
1376 FunctionProtoType::ExtProtoInfo EPI;
1377 EPI.HasExceptionSpec = true;
1378 if (HasBadAllocExceptionSpec) {
1379 EPI.NumExceptions = 1;
1380 EPI.Exceptions = &BadAllocType;
1381 }
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001382
John McCalle23cf432010-12-14 08:05:40 +00001383 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001384 FunctionDecl *Alloc =
1385 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCalld931b082010-08-26 03:08:43 +00001386 FnType, /*TInfo=*/0, SC_None,
1387 SC_None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001388 Alloc->setImplicit();
Nuno Lopesfc284482009-12-16 16:59:22 +00001389
1390 if (AddMallocAttr)
Sean Huntcf807c42010-08-18 23:23:40 +00001391 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Nuno Lopesfc284482009-12-16 16:59:22 +00001392
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001393 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00001394 0, Argument, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00001395 SC_None,
1396 SC_None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00001397 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001398
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001399 // FIXME: Also add this declaration to the IdentifierResolver, but
1400 // make sure it is at the end of the chain to coincide with the
1401 // global scope.
John McCall5f1e0942010-08-24 08:50:51 +00001402 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001403}
1404
Anders Carlsson78f74552009-11-15 18:45:20 +00001405bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1406 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00001407 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001408 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001409 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001410 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +00001411
John McCalla24dc2e2009-11-17 02:14:36 +00001412 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001413 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001414
Chandler Carruth23893242010-06-28 00:30:51 +00001415 Found.suppressDiagnostics();
1416
John McCall046a7462010-08-04 00:31:26 +00001417 llvm::SmallVector<DeclAccessPair,4> Matches;
Anders Carlsson78f74552009-11-15 18:45:20 +00001418 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1419 F != FEnd; ++F) {
Chandler Carruth09556fd2010-08-08 07:04:00 +00001420 NamedDecl *ND = (*F)->getUnderlyingDecl();
1421
1422 // Ignore template operator delete members from the check for a usual
1423 // deallocation function.
1424 if (isa<FunctionTemplateDecl>(ND))
1425 continue;
1426
1427 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall046a7462010-08-04 00:31:26 +00001428 Matches.push_back(F.getPair());
1429 }
1430
1431 // There's exactly one suitable operator; pick it.
1432 if (Matches.size() == 1) {
1433 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
1434 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1435 Matches[0]);
1436 return false;
1437
1438 // We found multiple suitable operators; complain about the ambiguity.
1439 } else if (!Matches.empty()) {
1440 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1441 << Name << RD;
1442
1443 for (llvm::SmallVectorImpl<DeclAccessPair>::iterator
1444 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1445 Diag((*F)->getUnderlyingDecl()->getLocation(),
1446 diag::note_member_declared_here) << Name;
1447 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001448 }
1449
1450 // We did find operator delete/operator delete[] declarations, but
1451 // none of them were suitable.
1452 if (!Found.empty()) {
1453 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1454 << Name << RD;
1455
1456 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
John McCall046a7462010-08-04 00:31:26 +00001457 F != FEnd; ++F)
1458 Diag((*F)->getUnderlyingDecl()->getLocation(),
1459 diag::note_member_declared_here) << Name;
Anders Carlsson78f74552009-11-15 18:45:20 +00001460
1461 return true;
1462 }
1463
1464 // Look for a global declaration.
1465 DeclareGlobalNewDelete();
1466 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1467
1468 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1469 Expr* DeallocArgs[1];
1470 DeallocArgs[0] = &Null;
1471 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1472 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1473 Operator))
1474 return true;
1475
1476 assert(Operator && "Did not find a deallocation function!");
1477 return false;
1478}
1479
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001480/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1481/// @code ::delete ptr; @endcode
1482/// or
1483/// @code delete [] ptr; @endcode
John McCall60d7b3a2010-08-24 06:29:42 +00001484ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001485Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John McCall9ae2f072010-08-23 23:25:46 +00001486 bool ArrayForm, Expr *Ex) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001487 // C++ [expr.delete]p1:
1488 // The operand shall have a pointer type, or a class type having a single
1489 // conversion function to a pointer type. The result has type void.
1490 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001491 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1492
Anders Carlssond67c4c32009-08-16 20:29:29 +00001493 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001494 bool ArrayFormAsWritten = ArrayForm;
Mike Stump1eb44332009-09-09 15:08:12 +00001495
Sebastian Redl28507842009-02-26 14:39:58 +00001496 if (!Ex->isTypeDependent()) {
1497 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001498
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001499 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor254a9422010-07-29 14:44:35 +00001500 if (RequireCompleteType(StartLoc, Type,
1501 PDiag(diag::err_delete_incomplete_class_type)))
1502 return ExprError();
1503
John McCall32daa422010-03-31 01:36:47 +00001504 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1505
Fariborz Jahanian53462782009-09-11 21:44:33 +00001506 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCall32daa422010-03-31 01:36:47 +00001507 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001508 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001509 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001510 NamedDecl *D = I.getDecl();
1511 if (isa<UsingShadowDecl>(D))
1512 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1513
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001514 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001515 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001516 continue;
1517
John McCall32daa422010-03-31 01:36:47 +00001518 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001519
1520 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1521 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedman13578692010-08-05 02:49:48 +00001522 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001523 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001524 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001525 if (ObjectPtrConversions.size() == 1) {
1526 // We have a single conversion to a pointer-to-object type. Perform
1527 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001528 // TODO: don't redo the conversion calculation.
John McCall32daa422010-03-31 01:36:47 +00001529 if (!PerformImplicitConversion(Ex,
1530 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +00001531 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001532 Type = Ex->getType();
1533 }
1534 }
1535 else if (ObjectPtrConversions.size() > 1) {
1536 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1537 << Type << Ex->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001538 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1539 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001540 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001541 }
Sebastian Redl28507842009-02-26 14:39:58 +00001542 }
1543
Sebastian Redlf53597f2009-03-15 17:47:39 +00001544 if (!Type->isPointerType())
1545 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1546 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001547
Ted Kremenek6217b802009-07-29 21:53:49 +00001548 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor94a61572010-05-24 17:01:56 +00001549 if (Pointee->isVoidType() && !isSFINAEContext()) {
1550 // The C++ standard bans deleting a pointer to a non-object type, which
1551 // effectively bans deletion of "void*". However, most compilers support
1552 // this, so we treat it as a warning unless we're in a SFINAE context.
1553 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1554 << Type << Ex->getSourceRange();
1555 } else if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001556 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1557 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001558 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001559 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +00001560 PDiag(diag::warn_delete_incomplete)
1561 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001562 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +00001563
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001564 // C++ [expr.delete]p2:
1565 // [Note: a pointer to a const type can be the operand of a
1566 // delete-expression; it is not necessary to cast away the constness
1567 // (5.2.11) of the pointer expression before it is used as the operand
1568 // of the delete-expression. ]
1569 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
John McCall2de56d12010-08-25 11:45:40 +00001570 CK_NoOp);
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001571
1572 if (Pointee->isArrayType() && !ArrayForm) {
1573 Diag(StartLoc, diag::warn_delete_array_type)
1574 << Type << Ex->getSourceRange()
1575 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1576 ArrayForm = true;
1577 }
1578
Anders Carlssond67c4c32009-08-16 20:29:29 +00001579 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1580 ArrayForm ? OO_Array_Delete : OO_Delete);
1581
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001582 QualType PointeeElem = Context.getBaseElementType(Pointee);
1583 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001584 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1585
1586 if (!UseGlobal &&
1587 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001588 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001589
Anders Carlsson78f74552009-11-15 18:45:20 +00001590 if (!RD->hasTrivialDestructor())
Douglas Gregor9b623632010-10-12 23:32:35 +00001591 if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001592 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001593 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor9b623632010-10-12 23:32:35 +00001594 DiagnoseUseOfDecl(Dtor, StartLoc);
1595 }
Anders Carlssond67c4c32009-08-16 20:29:29 +00001596 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001597
Anders Carlssond67c4c32009-08-16 20:29:29 +00001598 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001599 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001600 DeclareGlobalNewDelete();
1601 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001602 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +00001603 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001604 OperatorDelete))
1605 return ExprError();
1606 }
Mike Stump1eb44332009-09-09 15:08:12 +00001607
John McCall9c82afc2010-04-20 02:18:25 +00001608 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1609
Sebastian Redl28507842009-02-26 14:39:58 +00001610 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001611 }
1612
Sebastian Redlf53597f2009-03-15 17:47:39 +00001613 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001614 ArrayFormAsWritten, OperatorDelete,
1615 Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001616}
1617
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001618/// \brief Check the use of the given variable as a C++ condition in an if,
1619/// while, do-while, or switch statement.
John McCall60d7b3a2010-08-24 06:29:42 +00001620ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCallf89e55a2010-11-18 06:31:45 +00001621 SourceLocation StmtLoc,
1622 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001623 QualType T = ConditionVar->getType();
1624
1625 // C++ [stmt.select]p2:
1626 // The declarator shall not specify a function or an array.
1627 if (T->isFunctionType())
1628 return ExprError(Diag(ConditionVar->getLocation(),
1629 diag::err_invalid_use_of_function_type)
1630 << ConditionVar->getSourceRange());
1631 else if (T->isArrayType())
1632 return ExprError(Diag(ConditionVar->getLocation(),
1633 diag::err_invalid_use_of_array_type)
1634 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001635
Douglas Gregor586596f2010-05-06 17:25:47 +00001636 Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1637 ConditionVar->getLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00001638 ConditionVar->getType().getNonReferenceType(),
John McCall09431682010-11-18 19:01:18 +00001639 VK_LValue);
Douglas Gregorff331c12010-07-25 18:17:45 +00001640 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc))
Douglas Gregor586596f2010-05-06 17:25:47 +00001641 return ExprError();
Douglas Gregor586596f2010-05-06 17:25:47 +00001642
1643 return Owned(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001644}
1645
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001646/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1647bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1648 // C++ 6.4p4:
1649 // The value of a condition that is an initialized declaration in a statement
1650 // other than a switch statement is the value of the declared variable
1651 // implicitly converted to type bool. If that conversion is ill-formed, the
1652 // program is ill-formed.
1653 // The value of a condition that is an expression is the value of the
1654 // expression, implicitly converted to bool.
1655 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001656 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001657}
Douglas Gregor77a52232008-09-12 00:47:35 +00001658
1659/// Helper function to determine whether this is the (deprecated) C++
1660/// conversion from a string literal to a pointer to non-const char or
1661/// non-const wchar_t (for narrow and wide string literals,
1662/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001663bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001664Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1665 // Look inside the implicit cast, if it exists.
1666 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1667 From = Cast->getSubExpr();
1668
1669 // A string literal (2.13.4) that is not a wide string literal can
1670 // be converted to an rvalue of type "pointer to char"; a wide
1671 // string literal can be converted to an rvalue of type "pointer
1672 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00001673 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00001674 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001675 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001676 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001677 // This conversion is considered only when there is an
1678 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001679 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001680 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1681 (!StrLit->isWide() &&
1682 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1683 ToPointeeType->getKind() == BuiltinType::Char_S))))
1684 return true;
1685 }
1686
1687 return false;
1688}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001689
John McCall60d7b3a2010-08-24 06:29:42 +00001690static ExprResult BuildCXXCastArgument(Sema &S,
John McCall2de56d12010-08-25 11:45:40 +00001691 SourceLocation CastLoc,
1692 QualType Ty,
1693 CastKind Kind,
1694 CXXMethodDecl *Method,
Douglas Gregor83eecbe2011-01-20 01:32:05 +00001695 NamedDecl *FoundDecl,
John McCall2de56d12010-08-25 11:45:40 +00001696 Expr *From) {
Douglas Gregorba70ab62010-04-16 22:17:36 +00001697 switch (Kind) {
1698 default: assert(0 && "Unhandled cast kind!");
John McCall2de56d12010-08-25 11:45:40 +00001699 case CK_ConstructorConversion: {
John McCallca0408f2010-08-23 06:44:23 +00001700 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregorba70ab62010-04-16 22:17:36 +00001701
1702 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
John McCallf312b1e2010-08-26 23:41:50 +00001703 MultiExprArg(&From, 1),
Douglas Gregorba70ab62010-04-16 22:17:36 +00001704 CastLoc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00001705 return ExprError();
Douglas Gregorba70ab62010-04-16 22:17:36 +00001706
John McCall60d7b3a2010-08-24 06:29:42 +00001707 ExprResult Result =
Douglas Gregorba70ab62010-04-16 22:17:36 +00001708 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
John McCall7a1fad32010-08-24 07:32:53 +00001709 move_arg(ConstructorArgs),
Chandler Carruth428edaf2010-10-25 08:47:36 +00001710 /*ZeroInit*/ false, CXXConstructExpr::CK_Complete,
1711 SourceRange());
Douglas Gregorba70ab62010-04-16 22:17:36 +00001712 if (Result.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00001713 return ExprError();
Douglas Gregorba70ab62010-04-16 22:17:36 +00001714
1715 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1716 }
1717
John McCall2de56d12010-08-25 11:45:40 +00001718 case CK_UserDefinedConversion: {
Douglas Gregorba70ab62010-04-16 22:17:36 +00001719 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1720
1721 // Create an implicit call expr that calls it.
Douglas Gregor83eecbe2011-01-20 01:32:05 +00001722 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00001723 if (Result.isInvalid())
1724 return ExprError();
1725
1726 return S.MaybeBindToTemporary(Result.get());
Douglas Gregorba70ab62010-04-16 22:17:36 +00001727 }
1728 }
1729}
1730
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001731/// PerformImplicitConversion - Perform an implicit conversion of the
1732/// expression From to the type ToType using the pre-computed implicit
1733/// conversion sequence ICS. Returns true if there was an error, false
1734/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001735/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001736/// used in the error message.
1737bool
1738Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1739 const ImplicitConversionSequence &ICS,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001740 AssignmentAction Action, bool CStyle) {
John McCall1d318332010-01-12 00:44:57 +00001741 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001742 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001743 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001744 CStyle))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001745 return true;
1746 break;
1747
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001748 case ImplicitConversionSequence::UserDefinedConversion: {
1749
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001750 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCalldaa8e4e2010-11-15 09:13:47 +00001751 CastKind CastKind;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001752 QualType BeforeToType;
1753 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCall2de56d12010-08-25 11:45:40 +00001754 CastKind = CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001755
1756 // If the user-defined conversion is specified by a conversion function,
1757 // the initial standard conversion sequence converts the source type to
1758 // the implicit object parameter of the conversion function.
1759 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCall9ec94452010-12-04 09:57:16 +00001760 } else {
1761 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCall2de56d12010-08-25 11:45:40 +00001762 CastKind = CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001763 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001764 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001765 // If the user-defined conversion is specified by a constructor, the
1766 // initial standard conversion sequence converts the source type to the
1767 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001768 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1769 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001770 }
Douglas Gregora3998bd2010-12-02 21:47:04 +00001771 // Watch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001772 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001773 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001774 ICS.UserDefined.Before, AA_Converting,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001775 CStyle))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001776 return true;
1777 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001778
John McCall60d7b3a2010-08-24 06:29:42 +00001779 ExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00001780 = BuildCXXCastArgument(*this,
1781 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00001782 ToType.getNonReferenceType(),
Douglas Gregor83eecbe2011-01-20 01:32:05 +00001783 CastKind, cast<CXXMethodDecl>(FD),
1784 ICS.UserDefined.FoundConversionFunction,
John McCall9ae2f072010-08-23 23:25:46 +00001785 From);
Anders Carlsson0aebc812009-09-09 21:33:21 +00001786
1787 if (CastArg.isInvalid())
1788 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001789
1790 From = CastArg.takeAs<Expr>();
1791
Eli Friedmand8889622009-11-27 04:41:50 +00001792 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001793 AA_Converting, CStyle);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001794 }
John McCall1d318332010-01-12 00:44:57 +00001795
1796 case ImplicitConversionSequence::AmbiguousConversion:
John McCall120d63c2010-08-24 20:38:10 +00001797 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall1d318332010-01-12 00:44:57 +00001798 PDiag(diag::err_typecheck_ambiguous_condition)
1799 << From->getSourceRange());
1800 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001801
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001802 case ImplicitConversionSequence::EllipsisConversion:
1803 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001804 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001805
1806 case ImplicitConversionSequence::BadConversion:
1807 return true;
1808 }
1809
1810 // Everything went well.
1811 return false;
1812}
1813
1814/// PerformImplicitConversion - Perform an implicit conversion of the
1815/// expression From to the type ToType by following the standard
1816/// conversion sequence SCS. Returns true if there was an error, false
1817/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001818/// expression. Flavor is the context in which we're performing this
1819/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001820bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001821Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001822 const StandardConversionSequence& SCS,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001823 AssignmentAction Action, bool CStyle) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001824 // Overall FIXME: we are recomputing too many types here and doing far too
1825 // much extra work. What this means is that we need to keep track of more
1826 // information that is computed when we try the implicit conversion initially,
1827 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001828 QualType FromType = From->getType();
1829
Douglas Gregor225c41e2008-11-03 19:09:14 +00001830 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001831 // FIXME: When can ToType be a reference type?
1832 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001833 if (SCS.Second == ICK_Derived_To_Base) {
John McCallca0408f2010-08-23 06:44:23 +00001834 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001835 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCallca0408f2010-08-23 06:44:23 +00001836 MultiExprArg(*this, &From, 1),
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001837 /*FIXME:ConstructLoc*/SourceLocation(),
1838 ConstructorArgs))
1839 return true;
John McCall60d7b3a2010-08-24 06:29:42 +00001840 ExprResult FromResult =
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001841 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1842 ToType, SCS.CopyConstructor,
John McCall7a1fad32010-08-24 07:32:53 +00001843 move_arg(ConstructorArgs),
1844 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00001845 CXXConstructExpr::CK_Complete,
1846 SourceRange());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001847 if (FromResult.isInvalid())
1848 return true;
1849 From = FromResult.takeAs<Expr>();
1850 return false;
1851 }
John McCall60d7b3a2010-08-24 06:29:42 +00001852 ExprResult FromResult =
Mike Stump1eb44332009-09-09 15:08:12 +00001853 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1854 ToType, SCS.CopyConstructor,
John McCall7a1fad32010-08-24 07:32:53 +00001855 MultiExprArg(*this, &From, 1),
1856 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00001857 CXXConstructExpr::CK_Complete,
1858 SourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +00001859
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001860 if (FromResult.isInvalid())
1861 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001862
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001863 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001864 return false;
1865 }
1866
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001867 // Resolve overloaded function references.
1868 if (Context.hasSameType(FromType, Context.OverloadTy)) {
1869 DeclAccessPair Found;
1870 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1871 true, Found);
1872 if (!Fn)
1873 return true;
1874
1875 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1876 return true;
Douglas Gregor9b623632010-10-12 23:32:35 +00001877
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001878 From = FixOverloadedFunctionReference(From, Found, Fn);
1879 FromType = From->getType();
1880 }
1881
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001882 // Perform the first implicit conversion.
1883 switch (SCS.First) {
1884 case ICK_Identity:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001885 // Nothing to do.
1886 break;
1887
John McCallf6a16482010-12-04 03:47:34 +00001888 case ICK_Lvalue_To_Rvalue:
1889 // Should this get its own ICK?
1890 if (From->getObjectKind() == OK_ObjCProperty) {
1891 ConvertPropertyForRValue(From);
John McCall241d5582010-12-07 22:54:16 +00001892 if (!From->isGLValue()) break;
John McCallf6a16482010-12-04 03:47:34 +00001893 }
1894
1895 FromType = FromType.getUnqualifiedType();
1896 From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
1897 From, 0, VK_RValue);
1898 break;
1899
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001900 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001901 FromType = Context.getArrayDecayedType(FromType);
John McCall2de56d12010-08-25 11:45:40 +00001902 ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001903 break;
1904
1905 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001906 FromType = Context.getPointerType(FromType);
John McCall2de56d12010-08-25 11:45:40 +00001907 ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001908 break;
1909
1910 default:
1911 assert(false && "Improper first standard conversion");
1912 break;
1913 }
1914
1915 // Perform the second implicit conversion
1916 switch (SCS.Second) {
1917 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001918 // If both sides are functions (or pointers/references to them), there could
1919 // be incompatible exception declarations.
1920 if (CheckExceptionSpecCompatibility(From, ToType))
1921 return true;
1922 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001923 break;
1924
Douglas Gregor43c79c22009-12-09 00:47:37 +00001925 case ICK_NoReturn_Adjustment:
1926 // If both sides are functions (or pointers/references to them), there could
1927 // be incompatible exception declarations.
1928 if (CheckExceptionSpecCompatibility(From, ToType))
1929 return true;
1930
John McCalle6a365d2010-12-19 02:44:49 +00001931 ImpCastExprToType(From, ToType, CK_NoOp);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001932 break;
1933
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001934 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001935 case ICK_Integral_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00001936 ImpCastExprToType(From, ToType, CK_IntegralCast);
Eli Friedman73c39ab2009-10-20 08:27:19 +00001937 break;
1938
1939 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001940 case ICK_Floating_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00001941 ImpCastExprToType(From, ToType, CK_FloatingCast);
Eli Friedman73c39ab2009-10-20 08:27:19 +00001942 break;
1943
1944 case ICK_Complex_Promotion:
John McCalldaa8e4e2010-11-15 09:13:47 +00001945 case ICK_Complex_Conversion: {
1946 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
1947 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
1948 CastKind CK;
1949 if (FromEl->isRealFloatingType()) {
1950 if (ToEl->isRealFloatingType())
1951 CK = CK_FloatingComplexCast;
1952 else
1953 CK = CK_FloatingComplexToIntegralComplex;
1954 } else if (ToEl->isRealFloatingType()) {
1955 CK = CK_IntegralComplexToFloatingComplex;
1956 } else {
1957 CK = CK_IntegralComplexCast;
1958 }
1959 ImpCastExprToType(From, ToType, CK);
Eli Friedman73c39ab2009-10-20 08:27:19 +00001960 break;
John McCalldaa8e4e2010-11-15 09:13:47 +00001961 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00001962
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001963 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001964 if (ToType->isRealFloatingType())
John McCall2de56d12010-08-25 11:45:40 +00001965 ImpCastExprToType(From, ToType, CK_IntegralToFloating);
Eli Friedman73c39ab2009-10-20 08:27:19 +00001966 else
John McCall2de56d12010-08-25 11:45:40 +00001967 ImpCastExprToType(From, ToType, CK_FloatingToIntegral);
Eli Friedman73c39ab2009-10-20 08:27:19 +00001968 break;
1969
Douglas Gregorf9201e02009-02-11 23:02:49 +00001970 case ICK_Compatible_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00001971 ImpCastExprToType(From, ToType, CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001972 break;
1973
Anders Carlsson61faec12009-09-12 04:46:44 +00001974 case ICK_Pointer_Conversion: {
Douglas Gregora3998bd2010-12-02 21:47:04 +00001975 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001976 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001977 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001978 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00001979 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00001980 << From->getSourceRange();
1981 }
Anders Carlsson61faec12009-09-12 04:46:44 +00001982
John McCalldaa8e4e2010-11-15 09:13:47 +00001983 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00001984 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001985 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001986 return true;
John McCall5baba9d2010-08-25 10:28:54 +00001987 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001988 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001989 }
1990
1991 case ICK_Pointer_Member: {
John McCalldaa8e4e2010-11-15 09:13:47 +00001992 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00001993 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001994 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
Anders Carlsson61faec12009-09-12 04:46:44 +00001995 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001996 if (CheckExceptionSpecCompatibility(From, ToType))
1997 return true;
John McCall5baba9d2010-08-25 10:28:54 +00001998 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
Anders Carlsson61faec12009-09-12 04:46:44 +00001999 break;
2000 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00002001 case ICK_Boolean_Conversion: {
John McCalldaa8e4e2010-11-15 09:13:47 +00002002 CastKind Kind = CK_Invalid;
2003 switch (FromType->getScalarTypeKind()) {
2004 case Type::STK_Pointer: Kind = CK_PointerToBoolean; break;
2005 case Type::STK_MemberPointer: Kind = CK_MemberPointerToBoolean; break;
2006 case Type::STK_Bool: llvm_unreachable("bool -> bool conversion?");
2007 case Type::STK_Integral: Kind = CK_IntegralToBoolean; break;
2008 case Type::STK_Floating: Kind = CK_FloatingToBoolean; break;
2009 case Type::STK_IntegralComplex: Kind = CK_IntegralComplexToBoolean; break;
2010 case Type::STK_FloatingComplex: Kind = CK_FloatingComplexToBoolean; break;
2011 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00002012
2013 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002014 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00002015 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002016
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002017 case ICK_Derived_To_Base: {
John McCallf871d0c2010-08-07 06:22:56 +00002018 CXXCastPath BasePath;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002019 if (CheckDerivedToBaseConversion(From->getType(),
2020 ToType.getNonReferenceType(),
2021 From->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002022 From->getSourceRange(),
2023 &BasePath,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002024 CStyle))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002025 return true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002026
Sebastian Redl906082e2010-07-20 04:20:21 +00002027 ImpCastExprToType(From, ToType.getNonReferenceType(),
John McCall2de56d12010-08-25 11:45:40 +00002028 CK_DerivedToBase, CastCategory(From),
John McCallf871d0c2010-08-07 06:22:56 +00002029 &BasePath);
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002030 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002031 }
2032
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002033 case ICK_Vector_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00002034 ImpCastExprToType(From, ToType, CK_BitCast);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002035 break;
2036
2037 case ICK_Vector_Splat:
John McCall2de56d12010-08-25 11:45:40 +00002038 ImpCastExprToType(From, ToType, CK_VectorSplat);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002039 break;
2040
2041 case ICK_Complex_Real:
John McCalldaa8e4e2010-11-15 09:13:47 +00002042 // Case 1. x -> _Complex y
2043 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2044 QualType ElType = ToComplex->getElementType();
2045 bool isFloatingComplex = ElType->isRealFloatingType();
2046
2047 // x -> y
2048 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2049 // do nothing
2050 } else if (From->getType()->isRealFloatingType()) {
2051 ImpCastExprToType(From, ElType,
2052 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral);
2053 } else {
2054 assert(From->getType()->isIntegerType());
2055 ImpCastExprToType(From, ElType,
2056 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast);
2057 }
2058 // y -> _Complex y
2059 ImpCastExprToType(From, ToType,
2060 isFloatingComplex ? CK_FloatingRealToComplex
2061 : CK_IntegralRealToComplex);
2062
2063 // Case 2. _Complex x -> y
2064 } else {
2065 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2066 assert(FromComplex);
2067
2068 QualType ElType = FromComplex->getElementType();
2069 bool isFloatingComplex = ElType->isRealFloatingType();
2070
2071 // _Complex x -> x
2072 ImpCastExprToType(From, ElType,
2073 isFloatingComplex ? CK_FloatingComplexToReal
2074 : CK_IntegralComplexToReal);
2075
2076 // x -> y
2077 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2078 // do nothing
2079 } else if (ToType->isRealFloatingType()) {
2080 ImpCastExprToType(From, ToType,
2081 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating);
2082 } else {
2083 assert(ToType->isIntegerType());
2084 ImpCastExprToType(From, ToType,
2085 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast);
2086 }
2087 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002088 break;
2089
2090 case ICK_Lvalue_To_Rvalue:
2091 case ICK_Array_To_Pointer:
2092 case ICK_Function_To_Pointer:
2093 case ICK_Qualification:
2094 case ICK_Num_Conversion_Kinds:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002095 assert(false && "Improper second standard conversion");
2096 break;
2097 }
2098
2099 switch (SCS.Third) {
2100 case ICK_Identity:
2101 // Nothing to do.
2102 break;
2103
Sebastian Redl906082e2010-07-20 04:20:21 +00002104 case ICK_Qualification: {
2105 // The qualification keeps the category of the inner expression, unless the
2106 // target type isn't a reference.
John McCall5baba9d2010-08-25 10:28:54 +00002107 ExprValueKind VK = ToType->isReferenceType() ?
2108 CastCategory(From) : VK_RValue;
Douglas Gregor63982352010-07-13 18:40:04 +00002109 ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
John McCall2de56d12010-08-25 11:45:40 +00002110 CK_NoOp, VK);
Douglas Gregora9bff302010-02-28 18:30:25 +00002111
2112 if (SCS.DeprecatedStringLiteralToCharPtr)
2113 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2114 << ToType.getNonReferenceType();
2115
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002116 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002117 }
2118
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002119 default:
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002120 assert(false && "Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002121 break;
2122 }
2123
2124 return false;
2125}
2126
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002127ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002128 SourceLocation KWLoc,
2129 ParsedType Ty,
2130 SourceLocation RParen) {
2131 TypeSourceInfo *TSInfo;
2132 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002133
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002134 if (!TSInfo)
2135 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002136 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002137}
2138
Sebastian Redlf8aca862010-09-14 23:40:14 +00002139static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT, QualType T,
2140 SourceLocation KeyLoc) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002141 assert(!T->isDependentType() &&
2142 "Cannot evaluate traits for dependent types.");
2143 ASTContext &C = Self.Context;
2144 switch(UTT) {
2145 default: assert(false && "Unknown type trait or not implemented");
2146 case UTT_IsPOD: return T->isPODType();
2147 case UTT_IsLiteral: return T->isLiteralType();
2148 case UTT_IsClass: // Fallthrough
2149 case UTT_IsUnion:
2150 if (const RecordType *Record = T->getAs<RecordType>()) {
2151 bool Union = Record->getDecl()->isUnion();
2152 return UTT == UTT_IsUnion ? Union : !Union;
2153 }
2154 return false;
2155 case UTT_IsEnum: return T->isEnumeralType();
2156 case UTT_IsPolymorphic:
2157 if (const RecordType *Record = T->getAs<RecordType>()) {
2158 // Type traits are only parsed in C++, so we've got CXXRecords.
2159 return cast<CXXRecordDecl>(Record->getDecl())->isPolymorphic();
2160 }
2161 return false;
2162 case UTT_IsAbstract:
2163 if (const RecordType *RT = T->getAs<RecordType>())
2164 return cast<CXXRecordDecl>(RT->getDecl())->isAbstract();
2165 return false;
2166 case UTT_IsEmpty:
2167 if (const RecordType *Record = T->getAs<RecordType>()) {
2168 return !Record->getDecl()->isUnion()
2169 && cast<CXXRecordDecl>(Record->getDecl())->isEmpty();
2170 }
2171 return false;
2172 case UTT_HasTrivialConstructor:
2173 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2174 // If __is_pod (type) is true then the trait is true, else if type is
2175 // a cv class or union type (or array thereof) with a trivial default
2176 // constructor ([class.ctor]) then the trait is true, else it is false.
2177 if (T->isPODType())
2178 return true;
2179 if (const RecordType *RT =
2180 C.getBaseElementType(T)->getAs<RecordType>())
2181 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialConstructor();
2182 return false;
2183 case UTT_HasTrivialCopy:
2184 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2185 // If __is_pod (type) is true or type is a reference type then
2186 // the trait is true, else if type is a cv class or union type
2187 // with a trivial copy constructor ([class.copy]) then the trait
2188 // is true, else it is false.
2189 if (T->isPODType() || T->isReferenceType())
2190 return true;
2191 if (const RecordType *RT = T->getAs<RecordType>())
2192 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2193 return false;
2194 case UTT_HasTrivialAssign:
2195 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2196 // If type is const qualified or is a reference type then the
2197 // trait is false. Otherwise if __is_pod (type) is true then the
2198 // trait is true, else if type is a cv class or union type with
2199 // a trivial copy assignment ([class.copy]) then the trait is
2200 // true, else it is false.
2201 // Note: the const and reference restrictions are interesting,
2202 // given that const and reference members don't prevent a class
2203 // from having a trivial copy assignment operator (but do cause
2204 // errors if the copy assignment operator is actually used, q.v.
2205 // [class.copy]p12).
2206
2207 if (C.getBaseElementType(T).isConstQualified())
2208 return false;
2209 if (T->isPODType())
2210 return true;
2211 if (const RecordType *RT = T->getAs<RecordType>())
2212 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2213 return false;
2214 case UTT_HasTrivialDestructor:
2215 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2216 // If __is_pod (type) is true or type is a reference type
2217 // then the trait is true, else if type is a cv class or union
2218 // type (or array thereof) with a trivial destructor
2219 // ([class.dtor]) then the trait is true, else it is
2220 // false.
2221 if (T->isPODType() || T->isReferenceType())
2222 return true;
2223 if (const RecordType *RT =
2224 C.getBaseElementType(T)->getAs<RecordType>())
2225 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2226 return false;
2227 // TODO: Propagate nothrowness for implicitly declared special members.
2228 case UTT_HasNothrowAssign:
2229 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2230 // If type is const qualified or is a reference type then the
2231 // trait is false. Otherwise if __has_trivial_assign (type)
2232 // is true then the trait is true, else if type is a cv class
2233 // or union type with copy assignment operators that are known
2234 // not to throw an exception then the trait is true, else it is
2235 // false.
2236 if (C.getBaseElementType(T).isConstQualified())
2237 return false;
2238 if (T->isReferenceType())
2239 return false;
2240 if (T->isPODType())
2241 return true;
2242 if (const RecordType *RT = T->getAs<RecordType>()) {
2243 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2244 if (RD->hasTrivialCopyAssignment())
2245 return true;
2246
2247 bool FoundAssign = false;
2248 bool AllNoThrow = true;
2249 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redlf8aca862010-09-14 23:40:14 +00002250 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2251 Sema::LookupOrdinaryName);
2252 if (Self.LookupQualifiedName(Res, RD)) {
2253 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2254 Op != OpEnd; ++Op) {
2255 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2256 if (Operator->isCopyAssignmentOperator()) {
2257 FoundAssign = true;
2258 const FunctionProtoType *CPT
2259 = Operator->getType()->getAs<FunctionProtoType>();
2260 if (!CPT->hasEmptyExceptionSpec()) {
2261 AllNoThrow = false;
2262 break;
2263 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002264 }
2265 }
2266 }
2267
2268 return FoundAssign && AllNoThrow;
2269 }
2270 return false;
2271 case UTT_HasNothrowCopy:
2272 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2273 // If __has_trivial_copy (type) is true then the trait is true, else
2274 // if type is a cv class or union type with copy constructors that are
2275 // known not to throw an exception then the trait is true, else it is
2276 // false.
2277 if (T->isPODType() || T->isReferenceType())
2278 return true;
2279 if (const RecordType *RT = T->getAs<RecordType>()) {
2280 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2281 if (RD->hasTrivialCopyConstructor())
2282 return true;
2283
2284 bool FoundConstructor = false;
2285 bool AllNoThrow = true;
2286 unsigned FoundTQs;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002287 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl5f4e8992010-09-13 21:10:20 +00002288 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002289 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002290 // A template constructor is never a copy constructor.
2291 // FIXME: However, it may actually be selected at the actual overload
2292 // resolution point.
2293 if (isa<FunctionTemplateDecl>(*Con))
2294 continue;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002295 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2296 if (Constructor->isCopyConstructor(FoundTQs)) {
2297 FoundConstructor = true;
2298 const FunctionProtoType *CPT
2299 = Constructor->getType()->getAs<FunctionProtoType>();
Sebastian Redl751025d2010-09-13 22:02:47 +00002300 // TODO: check whether evaluating default arguments can throw.
2301 // For now, we'll be conservative and assume that they can throw.
2302 if (!CPT->hasEmptyExceptionSpec() || CPT->getNumArgs() > 1) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002303 AllNoThrow = false;
2304 break;
2305 }
2306 }
2307 }
2308
2309 return FoundConstructor && AllNoThrow;
2310 }
2311 return false;
2312 case UTT_HasNothrowConstructor:
2313 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2314 // If __has_trivial_constructor (type) is true then the trait is
2315 // true, else if type is a cv class or union type (or array
2316 // thereof) with a default constructor that is known not to
2317 // throw an exception then the trait is true, else it is false.
2318 if (T->isPODType())
2319 return true;
2320 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
2321 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2322 if (RD->hasTrivialConstructor())
2323 return true;
2324
Sebastian Redl751025d2010-09-13 22:02:47 +00002325 DeclContext::lookup_const_iterator Con, ConEnd;
2326 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2327 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002328 // FIXME: In C++0x, a constructor template can be a default constructor.
2329 if (isa<FunctionTemplateDecl>(*Con))
2330 continue;
Sebastian Redl751025d2010-09-13 22:02:47 +00002331 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2332 if (Constructor->isDefaultConstructor()) {
2333 const FunctionProtoType *CPT
2334 = Constructor->getType()->getAs<FunctionProtoType>();
2335 // TODO: check whether evaluating default arguments can throw.
2336 // For now, we'll be conservative and assume that they can throw.
2337 return CPT->hasEmptyExceptionSpec() && CPT->getNumArgs() == 0;
2338 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002339 }
2340 }
2341 return false;
2342 case UTT_HasVirtualDestructor:
2343 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2344 // If type is a class type with a virtual destructor ([class.dtor])
2345 // then the trait is true, else it is false.
2346 if (const RecordType *Record = T->getAs<RecordType>()) {
2347 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redlf8aca862010-09-14 23:40:14 +00002348 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002349 return Destructor->isVirtual();
2350 }
2351 return false;
2352 }
2353}
2354
2355ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002356 SourceLocation KWLoc,
2357 TypeSourceInfo *TSInfo,
2358 SourceLocation RParen) {
2359 QualType T = TSInfo->getType();
2360
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002361 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
2362 // all traits except __is_class, __is_enum and __is_union require a the type
Sebastian Redl607a1782010-09-08 00:48:43 +00002363 // to be complete, an array of unknown bound, or void.
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002364 if (UTT != UTT_IsClass && UTT != UTT_IsEnum && UTT != UTT_IsUnion) {
Sebastian Redl607a1782010-09-08 00:48:43 +00002365 QualType E = T;
2366 if (T->isIncompleteArrayType())
2367 E = Context.getAsArrayType(T)->getElementType();
2368 if (!T->isVoidType() &&
2369 RequireCompleteType(KWLoc, E,
Anders Carlssond497ba72009-08-26 22:59:12 +00002370 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002371 return ExprError();
2372 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00002373
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002374 bool Value = false;
2375 if (!T->isDependentType())
Sebastian Redlf8aca862010-09-14 23:40:14 +00002376 Value = EvaluateUnaryTypeTrait(*this, UTT, T, KWLoc);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002377
2378 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002379 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00002380}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002381
Francois Pichet6ad6f282010-12-07 00:08:36 +00002382ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
2383 SourceLocation KWLoc,
2384 ParsedType LhsTy,
2385 ParsedType RhsTy,
2386 SourceLocation RParen) {
2387 TypeSourceInfo *LhsTSInfo;
2388 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
2389 if (!LhsTSInfo)
2390 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
2391
2392 TypeSourceInfo *RhsTSInfo;
2393 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
2394 if (!RhsTSInfo)
2395 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
2396
2397 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
2398}
2399
2400static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
2401 QualType LhsT, QualType RhsT,
2402 SourceLocation KeyLoc) {
2403 assert((!LhsT->isDependentType() || RhsT->isDependentType()) &&
2404 "Cannot evaluate traits for dependent types.");
2405
2406 switch(BTT) {
2407 case BTT_IsBaseOf:
2408 // C++0x [meta.rel]p2
2409 // Base is a base class of Derived without regard to cv-qualifiers or
2410 // Base and Derived are not unions and name the same class type without
2411 // regard to cv-qualifiers.
2412 if (Self.IsDerivedFrom(RhsT, LhsT) ||
2413 (!LhsT->isUnionType() && !RhsT->isUnionType()
2414 && LhsT->getAsCXXRecordDecl() == RhsT->getAsCXXRecordDecl()))
2415 return true;
2416
2417 return false;
Francois Pichetf1872372010-12-08 22:35:30 +00002418 case BTT_TypeCompatible:
2419 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
2420 RhsT.getUnqualifiedType());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002421 }
2422 llvm_unreachable("Unknown type trait or not implemented");
2423}
2424
2425ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
2426 SourceLocation KWLoc,
2427 TypeSourceInfo *LhsTSInfo,
2428 TypeSourceInfo *RhsTSInfo,
2429 SourceLocation RParen) {
2430 QualType LhsT = LhsTSInfo->getType();
2431 QualType RhsT = RhsTSInfo->getType();
2432
2433 if (BTT == BTT_IsBaseOf) {
2434 // C++0x [meta.rel]p2
2435 // If Base and Derived are class types and are different types
2436 // (ignoring possible cv-qualifiers) then Derived shall be a complete
2437 // type. []
2438 CXXRecordDecl *LhsDecl = LhsT->getAsCXXRecordDecl();
2439 CXXRecordDecl *RhsDecl = RhsT->getAsCXXRecordDecl();
2440 if (!LhsT->isDependentType() && !RhsT->isDependentType() &&
2441 LhsDecl && RhsDecl && LhsT != RhsT &&
2442 RequireCompleteType(KWLoc, RhsT,
2443 diag::err_incomplete_type_used_in_type_trait_expr))
2444 return ExprError();
Francois Pichetf1872372010-12-08 22:35:30 +00002445 } else if (BTT == BTT_TypeCompatible) {
2446 if (getLangOptions().CPlusPlus) {
2447 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
2448 << SourceRange(KWLoc, RParen);
2449 return ExprError();
2450 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00002451 }
2452
2453 bool Value = false;
2454 if (!LhsT->isDependentType() && !RhsT->isDependentType())
2455 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
2456
Francois Pichetf1872372010-12-08 22:35:30 +00002457 // Select trait result type.
2458 QualType ResultType;
2459 switch (BTT) {
2460 default: llvm_unreachable("Unknown type trait or not implemented");
2461 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
2462 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
2463 }
2464
Francois Pichet6ad6f282010-12-07 00:08:36 +00002465 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
2466 RhsTSInfo, Value, RParen,
Francois Pichetf1872372010-12-08 22:35:30 +00002467 ResultType));
Francois Pichet6ad6f282010-12-07 00:08:36 +00002468}
2469
John McCallf89e55a2010-11-18 06:31:45 +00002470QualType Sema::CheckPointerToMemberOperands(Expr *&lex, Expr *&rex,
2471 ExprValueKind &VK,
2472 SourceLocation Loc,
2473 bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002474 const char *OpSpelling = isIndirect ? "->*" : ".*";
2475 // C++ 5.5p2
2476 // The binary operator .* [p3: ->*] binds its second operand, which shall
2477 // be of type "pointer to member of T" (where T is a completely-defined
2478 // class type) [...]
2479 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002480 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00002481 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002482 Diag(Loc, diag::err_bad_memptr_rhs)
2483 << OpSpelling << RType << rex->getSourceRange();
2484 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00002485 }
Douglas Gregore7450f52009-03-24 19:52:54 +00002486
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002487 QualType Class(MemPtr->getClass(), 0);
2488
Douglas Gregor7d520ba2010-10-13 20:41:14 +00002489 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
2490 // member pointer points must be completely-defined. However, there is no
2491 // reason for this semantic distinction, and the rule is not enforced by
2492 // other compilers. Therefore, we do not check this property, as it is
2493 // likely to be considered a defect.
Sebastian Redl59fc2692010-04-10 10:14:54 +00002494
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002495 // C++ 5.5p2
2496 // [...] to its first operand, which shall be of class T or of a class of
2497 // which T is an unambiguous and accessible base class. [p3: a pointer to
2498 // such a class]
2499 QualType LType = lex->getType();
2500 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002501 if (const PointerType *Ptr = LType->getAs<PointerType>())
John McCallf89e55a2010-11-18 06:31:45 +00002502 LType = Ptr->getPointeeType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002503 else {
2504 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00002505 << OpSpelling << 1 << LType
Douglas Gregor849b2432010-03-31 17:46:05 +00002506 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002507 return QualType();
2508 }
2509 }
2510
Douglas Gregora4923eb2009-11-16 21:35:15 +00002511 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00002512 // If we want to check the hierarchy, we need a complete type.
2513 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
2514 << OpSpelling << (int)isIndirect)) {
2515 return QualType();
2516 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002517 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002518 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00002519 // FIXME: Would it be useful to print full ambiguity paths, or is that
2520 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002521 if (!IsDerivedFrom(LType, Class, Paths) ||
2522 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
2523 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00002524 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002525 return QualType();
2526 }
Eli Friedman3005efe2010-01-16 00:00:48 +00002527 // Cast LHS to type of use.
2528 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
John McCall5baba9d2010-08-25 10:28:54 +00002529 ExprValueKind VK =
2530 isIndirect ? VK_RValue : CastCategory(lex);
Sebastian Redl906082e2010-07-20 04:20:21 +00002531
John McCallf871d0c2010-08-07 06:22:56 +00002532 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002533 BuildBasePathArray(Paths, BasePath);
John McCall5baba9d2010-08-25 10:28:54 +00002534 ImpCastExprToType(lex, UseType, CK_DerivedToBase, VK, &BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002535 }
2536
Douglas Gregored8abf12010-07-08 06:14:04 +00002537 if (isa<CXXScalarValueInitExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00002538 // Diagnose use of pointer-to-member type which when used as
2539 // the functional cast in a pointer-to-member expression.
2540 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
2541 return QualType();
2542 }
John McCallf89e55a2010-11-18 06:31:45 +00002543
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002544 // C++ 5.5p2
2545 // The result is an object or a function of the type specified by the
2546 // second operand.
2547 // The cv qualifiers are the union of those in the pointer and the left side,
2548 // in accordance with 5.5p5 and 5.2.5.
2549 // FIXME: This returns a dereferenced member function pointer as a normal
2550 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00002551 // calling them. There's also a GCC extension to get a function pointer to the
2552 // thing, which is another complication, because this type - unlike the type
2553 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002554 // argument.
2555 // We probably need a "MemberFunctionClosureType" or something like that.
2556 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00002557 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
John McCallf89e55a2010-11-18 06:31:45 +00002558
Douglas Gregor6b4df912011-01-26 16:40:18 +00002559 // C++0x [expr.mptr.oper]p6:
2560 // In a .* expression whose object expression is an rvalue, the program is
2561 // ill-formed if the second operand is a pointer to member function with
2562 // ref-qualifier &. In a ->* expression or in a .* expression whose object
2563 // expression is an lvalue, the program is ill-formed if the second operand
2564 // is a pointer to member function with ref-qualifier &&.
2565 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
2566 switch (Proto->getRefQualifier()) {
2567 case RQ_None:
2568 // Do nothing
2569 break;
2570
2571 case RQ_LValue:
2572 if (!isIndirect && !lex->Classify(Context).isLValue())
2573 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
2574 << RType << 1 << lex->getSourceRange();
2575 break;
2576
2577 case RQ_RValue:
2578 if (isIndirect || !lex->Classify(Context).isRValue())
2579 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
2580 << RType << 0 << lex->getSourceRange();
2581 break;
2582 }
2583 }
2584
John McCallf89e55a2010-11-18 06:31:45 +00002585 // C++ [expr.mptr.oper]p6:
2586 // The result of a .* expression whose second operand is a pointer
2587 // to a data member is of the same value category as its
2588 // first operand. The result of a .* expression whose second
2589 // operand is a pointer to a member function is a prvalue. The
2590 // result of an ->* expression is an lvalue if its second operand
2591 // is a pointer to data member and a prvalue otherwise.
2592 if (Result->isFunctionType())
2593 VK = VK_RValue;
2594 else if (isIndirect)
2595 VK = VK_LValue;
2596 else
2597 VK = lex->getValueKind();
2598
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002599 return Result;
2600}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002601
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002602/// \brief Try to convert a type to another according to C++0x 5.16p3.
2603///
2604/// This is part of the parameter validation for the ? operator. If either
2605/// value operand is a class type, the two operands are attempted to be
2606/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002607/// It returns true if the program is ill-formed and has already been diagnosed
2608/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002609static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
2610 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00002611 bool &HaveConversion,
2612 QualType &ToType) {
2613 HaveConversion = false;
2614 ToType = To->getType();
2615
2616 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
2617 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002618 // C++0x 5.16p3
2619 // The process for determining whether an operand expression E1 of type T1
2620 // can be converted to match an operand expression E2 of type T2 is defined
2621 // as follows:
2622 // -- If E2 is an lvalue:
John McCall7eb0a9e2010-11-24 05:12:34 +00002623 bool ToIsLvalue = To->isLValue();
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002624 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002625 // E1 can be converted to match E2 if E1 can be implicitly converted to
2626 // type "lvalue reference to T2", subject to the constraint that in the
2627 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002628 QualType T = Self.Context.getLValueReferenceType(ToType);
2629 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2630
2631 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2632 if (InitSeq.isDirectReferenceBinding()) {
2633 ToType = T;
2634 HaveConversion = true;
2635 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002636 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002637
2638 if (InitSeq.isAmbiguous())
2639 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002640 }
John McCallb1bdc622010-02-25 01:37:24 +00002641
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002642 // -- If E2 is an rvalue, or if the conversion above cannot be done:
2643 // -- if E1 and E2 have class type, and the underlying class types are
2644 // the same or one is a base class of the other:
2645 QualType FTy = From->getType();
2646 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002647 const RecordType *FRec = FTy->getAs<RecordType>();
2648 const RecordType *TRec = TTy->getAs<RecordType>();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002649 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
2650 Self.IsDerivedFrom(FTy, TTy);
2651 if (FRec && TRec &&
2652 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002653 // E1 can be converted to match E2 if the class of T2 is the
2654 // same type as, or a base class of, the class of T1, and
2655 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00002656 if (FRec == TRec || FDerivedFromT) {
2657 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002658 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2659 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2660 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2661 HaveConversion = true;
2662 return false;
2663 }
2664
2665 if (InitSeq.isAmbiguous())
2666 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2667 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002668 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002669
2670 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002671 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002672
2673 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2674 // implicitly converted to the type that expression E2 would have
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002675 // if E2 were converted to an rvalue (or the type it has, if E2 is
2676 // an rvalue).
2677 //
2678 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2679 // to the array-to-pointer or function-to-pointer conversions.
2680 if (!TTy->getAs<TagType>())
2681 TTy = TTy.getUnqualifiedType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002682
2683 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2684 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2685 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
2686 ToType = TTy;
2687 if (InitSeq.isAmbiguous())
2688 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2689
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002690 return false;
2691}
2692
2693/// \brief Try to find a common type for two according to C++0x 5.16p5.
2694///
2695/// This is part of the parameter validation for the ? operator. If either
2696/// value operand is a class type, overload resolution is used to find a
2697/// conversion to a common type.
2698static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2699 SourceLocation Loc) {
2700 Expr *Args[2] = { LHS, RHS };
John McCall5769d612010-02-08 23:07:23 +00002701 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor573d9c32009-10-21 23:19:44 +00002702 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002703
2704 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00002705 switch (CandidateSet.BestViableFunction(Self, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002706 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002707 // We found a match. Perform the conversions on the arguments and move on.
2708 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00002709 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002710 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00002711 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002712 break;
2713 return false;
2714
Douglas Gregor20093b42009-12-09 23:02:17 +00002715 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002716 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2717 << LHS->getType() << RHS->getType()
2718 << LHS->getSourceRange() << RHS->getSourceRange();
2719 return true;
2720
Douglas Gregor20093b42009-12-09 23:02:17 +00002721 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002722 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2723 << LHS->getType() << RHS->getType()
2724 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00002725 // FIXME: Print the possible common types by printing the return types of
2726 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002727 break;
2728
Douglas Gregor20093b42009-12-09 23:02:17 +00002729 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002730 assert(false && "Conditional operator has only built-in overloads");
2731 break;
2732 }
2733 return true;
2734}
2735
Sebastian Redl76458502009-04-17 16:30:52 +00002736/// \brief Perform an "extended" implicit conversion as returned by
2737/// TryClassUnification.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002738static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2739 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2740 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2741 SourceLocation());
2742 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
John McCallf312b1e2010-08-26 23:41:50 +00002743 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&E, 1));
Douglas Gregorb70cf442010-03-26 20:14:36 +00002744 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00002745 return true;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002746
2747 E = Result.takeAs<Expr>();
Sebastian Redl76458502009-04-17 16:30:52 +00002748 return false;
2749}
2750
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002751/// \brief Check the operands of ?: under C++ semantics.
2752///
2753/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2754/// extension. In this case, LHS == Cond. (But they're not aliases.)
2755QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
John McCallf89e55a2010-11-18 06:31:45 +00002756 Expr *&SAVE, ExprValueKind &VK,
John McCall09431682010-11-18 19:01:18 +00002757 ExprObjectKind &OK,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002758 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002759 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2760 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002761
2762 // C++0x 5.16p1
2763 // The first expression is contextually converted to bool.
2764 if (!Cond->isTypeDependent()) {
Fariborz Jahanian1fb019b2010-09-18 19:38:38 +00002765 if (SAVE && Cond->getType()->isArrayType()) {
2766 QualType CondTy = Cond->getType();
2767 CondTy = Context.getArrayDecayedType(CondTy);
2768 ImpCastExprToType(Cond, CondTy, CK_ArrayToPointerDecay);
2769 SAVE = LHS = Cond;
2770 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002771 if (CheckCXXBooleanCondition(Cond))
2772 return QualType();
2773 }
2774
John McCallf89e55a2010-11-18 06:31:45 +00002775 // Assume r-value.
2776 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00002777 OK = OK_Ordinary;
John McCallf89e55a2010-11-18 06:31:45 +00002778
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002779 // Either of the arguments dependent?
2780 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2781 return Context.DependentTy;
2782
2783 // C++0x 5.16p2
2784 // If either the second or the third operand has type (cv) void, ...
2785 QualType LTy = LHS->getType();
2786 QualType RTy = RHS->getType();
2787 bool LVoid = LTy->isVoidType();
2788 bool RVoid = RTy->isVoidType();
2789 if (LVoid || RVoid) {
2790 // ... then the [l2r] conversions are performed on the second and third
2791 // operands ...
Douglas Gregora873dfc2010-02-03 00:27:59 +00002792 DefaultFunctionArrayLvalueConversion(LHS);
2793 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002794 LTy = LHS->getType();
2795 RTy = RHS->getType();
2796
2797 // ... and one of the following shall hold:
2798 // -- The second or the third operand (but not both) is a throw-
2799 // expression; the result is of the type of the other and is an rvalue.
2800 bool LThrow = isa<CXXThrowExpr>(LHS);
2801 bool RThrow = isa<CXXThrowExpr>(RHS);
2802 if (LThrow && !RThrow)
2803 return RTy;
2804 if (RThrow && !LThrow)
2805 return LTy;
2806
2807 // -- Both the second and third operands have type void; the result is of
2808 // type void and is an rvalue.
2809 if (LVoid && RVoid)
2810 return Context.VoidTy;
2811
2812 // Neither holds, error.
2813 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2814 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2815 << LHS->getSourceRange() << RHS->getSourceRange();
2816 return QualType();
2817 }
2818
2819 // Neither is void.
2820
2821 // C++0x 5.16p3
2822 // Otherwise, if the second and third operand have different types, and
2823 // either has (cv) class type, and attempt is made to convert each of those
2824 // operands to the other.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002825 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002826 (LTy->isRecordType() || RTy->isRecordType())) {
2827 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2828 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002829 QualType L2RType, R2LType;
2830 bool HaveL2R, HaveR2L;
2831 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002832 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002833 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002834 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002835
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002836 // If both can be converted, [...] the program is ill-formed.
2837 if (HaveL2R && HaveR2L) {
2838 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2839 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2840 return QualType();
2841 }
2842
2843 // If exactly one conversion is possible, that conversion is applied to
2844 // the chosen operand and the converted operands are used in place of the
2845 // original operands for the remainder of this section.
2846 if (HaveL2R) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002847 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002848 return QualType();
2849 LTy = LHS->getType();
2850 } else if (HaveR2L) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002851 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002852 return QualType();
2853 RTy = RHS->getType();
2854 }
2855 }
2856
2857 // C++0x 5.16p4
John McCallf89e55a2010-11-18 06:31:45 +00002858 // If the second and third operands are glvalues of the same value
2859 // category and have the same type, the result is of that type and
2860 // value category and it is a bit-field if the second or the third
2861 // operand is a bit-field, or if both are bit-fields.
John McCall09431682010-11-18 19:01:18 +00002862 // We only extend this to bitfields, not to the crazy other kinds of
2863 // l-values.
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002864 bool Same = Context.hasSameType(LTy, RTy);
John McCallf89e55a2010-11-18 06:31:45 +00002865 if (Same &&
2866 LHS->getValueKind() != VK_RValue &&
2867 LHS->getValueKind() == RHS->getValueKind() &&
John McCall09431682010-11-18 19:01:18 +00002868 (LHS->getObjectKind() == OK_Ordinary ||
2869 LHS->getObjectKind() == OK_BitField) &&
2870 (RHS->getObjectKind() == OK_Ordinary ||
2871 RHS->getObjectKind() == OK_BitField)) {
John McCallf89e55a2010-11-18 06:31:45 +00002872 VK = LHS->getValueKind();
John McCall09431682010-11-18 19:01:18 +00002873 if (LHS->getObjectKind() == OK_BitField ||
2874 RHS->getObjectKind() == OK_BitField)
2875 OK = OK_BitField;
John McCallf89e55a2010-11-18 06:31:45 +00002876 return LTy;
Fariborz Jahanian3911a1a2010-09-25 01:08:05 +00002877 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002878
2879 // C++0x 5.16p5
2880 // Otherwise, the result is an rvalue. If the second and third operands
2881 // do not have the same type, and either has (cv) class type, ...
2882 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2883 // ... overload resolution is used to determine the conversions (if any)
2884 // to be applied to the operands. If the overload resolution fails, the
2885 // program is ill-formed.
2886 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2887 return QualType();
2888 }
2889
2890 // C++0x 5.16p6
2891 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2892 // conversions are performed on the second and third operands.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002893 DefaultFunctionArrayLvalueConversion(LHS);
2894 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002895 LTy = LHS->getType();
2896 RTy = RHS->getType();
2897
2898 // After those conversions, one of the following shall hold:
2899 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00002900 // is of that type. If the operands have class type, the result
2901 // is a prvalue temporary of the result type, which is
2902 // copy-initialized from either the second operand or the third
2903 // operand depending on the value of the first operand.
2904 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
2905 if (LTy->isRecordType()) {
2906 // The operands have class type. Make a temporary copy.
2907 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
John McCall60d7b3a2010-08-24 06:29:42 +00002908 ExprResult LHSCopy = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00002909 SourceLocation(),
2910 Owned(LHS));
Douglas Gregorb65a4582010-05-19 23:40:50 +00002911 if (LHSCopy.isInvalid())
2912 return QualType();
2913
John McCall60d7b3a2010-08-24 06:29:42 +00002914 ExprResult RHSCopy = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00002915 SourceLocation(),
2916 Owned(RHS));
Douglas Gregorb65a4582010-05-19 23:40:50 +00002917 if (RHSCopy.isInvalid())
2918 return QualType();
2919
2920 LHS = LHSCopy.takeAs<Expr>();
2921 RHS = RHSCopy.takeAs<Expr>();
2922 }
2923
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002924 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00002925 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002926
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002927 // Extension: conditional operator involving vector types.
2928 if (LTy->isVectorType() || RTy->isVectorType())
2929 return CheckVectorOperands(QuestionLoc, LHS, RHS);
2930
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002931 // -- The second and third operands have arithmetic or enumeration type;
2932 // the usual arithmetic conversions are performed to bring them to a
2933 // common type, and the result is of that type.
2934 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2935 UsualArithmeticConversions(LHS, RHS);
2936 return LHS->getType();
2937 }
2938
2939 // -- The second and third operands have pointer type, or one has pointer
2940 // type and the other is a null pointer constant; pointer conversions
2941 // and qualification conversions are performed to bring them to their
2942 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00002943 // -- The second and third operands have pointer to member type, or one has
2944 // pointer to member type and the other is a null pointer constant;
2945 // pointer to member conversions and qualification conversions are
2946 // performed to bring them to a common type, whose cv-qualification
2947 // shall match the cv-qualification of either the second or the third
2948 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002949 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002950 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002951 isSFINAEContext()? 0 : &NonStandardCompositeType);
2952 if (!Composite.isNull()) {
2953 if (NonStandardCompositeType)
2954 Diag(QuestionLoc,
2955 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2956 << LTy << RTy << Composite
2957 << LHS->getSourceRange() << RHS->getSourceRange();
2958
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002959 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002960 }
Fariborz Jahanian55016362009-12-10 20:46:08 +00002961
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002962 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00002963 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2964 if (!Composite.isNull())
2965 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002966
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002967 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2968 << LHS->getType() << RHS->getType()
2969 << LHS->getSourceRange() << RHS->getSourceRange();
2970 return QualType();
2971}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002972
2973/// \brief Find a merged pointer type and convert the two expressions to it.
2974///
Douglas Gregor20b3e992009-08-24 17:42:35 +00002975/// This finds the composite pointer type (or member pointer type) for @p E1
2976/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2977/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002978/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002979///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002980/// \param Loc The location of the operator requiring these two expressions to
2981/// be converted to the composite pointer type.
2982///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002983/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2984/// a non-standard (but still sane) composite type to which both expressions
2985/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2986/// will be set true.
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002987QualType Sema::FindCompositePointerType(SourceLocation Loc,
2988 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002989 bool *NonStandardCompositeType) {
2990 if (NonStandardCompositeType)
2991 *NonStandardCompositeType = false;
2992
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002993 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2994 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002995
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00002996 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2997 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00002998 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002999
3000 // C++0x 5.9p2
3001 // Pointer conversions and qualification conversions are performed on
3002 // pointer operands to bring them to their composite pointer type. If
3003 // one operand is a null pointer constant, the composite pointer type is
3004 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00003005 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003006 if (T2->isMemberPointerType())
John McCall2de56d12010-08-25 11:45:40 +00003007 ImpCastExprToType(E1, T2, CK_NullToMemberPointer);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003008 else
John McCall404cd162010-11-13 01:35:44 +00003009 ImpCastExprToType(E1, T2, CK_NullToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003010 return T2;
3011 }
Douglas Gregorce940492009-09-25 04:25:58 +00003012 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003013 if (T1->isMemberPointerType())
John McCall2de56d12010-08-25 11:45:40 +00003014 ImpCastExprToType(E2, T1, CK_NullToMemberPointer);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003015 else
John McCall404cd162010-11-13 01:35:44 +00003016 ImpCastExprToType(E2, T1, CK_NullToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003017 return T1;
3018 }
Mike Stump1eb44332009-09-09 15:08:12 +00003019
Douglas Gregor20b3e992009-08-24 17:42:35 +00003020 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003021 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
3022 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003023 return QualType();
3024
3025 // Otherwise, of one of the operands has type "pointer to cv1 void," then
3026 // the other has type "pointer to cv2 T" and the composite pointer type is
3027 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
3028 // Otherwise, the composite pointer type is a pointer type similar to the
3029 // type of one of the operands, with a cv-qualification signature that is
3030 // the union of the cv-qualification signatures of the operand types.
3031 // In practice, the first part here is redundant; it's subsumed by the second.
3032 // What we do here is, we build the two possible composite types, and try the
3033 // conversions in both directions. If only one works, or if the two composite
3034 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00003035 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00003036 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
3037 QualifierVector QualifierUnion;
3038 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
3039 ContainingClassVector;
3040 ContainingClassVector MemberOfClass;
3041 QualType Composite1 = Context.getCanonicalType(T1),
3042 Composite2 = Context.getCanonicalType(T2);
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003043 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00003044 do {
3045 const PointerType *Ptr1, *Ptr2;
3046 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3047 (Ptr2 = Composite2->getAs<PointerType>())) {
3048 Composite1 = Ptr1->getPointeeType();
3049 Composite2 = Ptr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003050
3051 // If we're allowed to create a non-standard composite type, keep track
3052 // of where we need to fill in additional 'const' qualifiers.
3053 if (NonStandardCompositeType &&
3054 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3055 NeedConstBefore = QualifierUnion.size();
3056
Douglas Gregor20b3e992009-08-24 17:42:35 +00003057 QualifierUnion.push_back(
3058 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3059 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3060 continue;
3061 }
Mike Stump1eb44332009-09-09 15:08:12 +00003062
Douglas Gregor20b3e992009-08-24 17:42:35 +00003063 const MemberPointerType *MemPtr1, *MemPtr2;
3064 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3065 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3066 Composite1 = MemPtr1->getPointeeType();
3067 Composite2 = MemPtr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003068
3069 // If we're allowed to create a non-standard composite type, keep track
3070 // of where we need to fill in additional 'const' qualifiers.
3071 if (NonStandardCompositeType &&
3072 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3073 NeedConstBefore = QualifierUnion.size();
3074
Douglas Gregor20b3e992009-08-24 17:42:35 +00003075 QualifierUnion.push_back(
3076 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3077 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
3078 MemPtr2->getClass()));
3079 continue;
3080 }
Mike Stump1eb44332009-09-09 15:08:12 +00003081
Douglas Gregor20b3e992009-08-24 17:42:35 +00003082 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00003083
Douglas Gregor20b3e992009-08-24 17:42:35 +00003084 // Cannot unwrap any more types.
3085 break;
3086 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00003087
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003088 if (NeedConstBefore && NonStandardCompositeType) {
3089 // Extension: Add 'const' to qualifiers that come before the first qualifier
3090 // mismatch, so that our (non-standard!) composite type meets the
3091 // requirements of C++ [conv.qual]p4 bullet 3.
3092 for (unsigned I = 0; I != NeedConstBefore; ++I) {
3093 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
3094 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
3095 *NonStandardCompositeType = true;
3096 }
3097 }
3098 }
3099
Douglas Gregor20b3e992009-08-24 17:42:35 +00003100 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003101 ContainingClassVector::reverse_iterator MOC
3102 = MemberOfClass.rbegin();
3103 for (QualifierVector::reverse_iterator
3104 I = QualifierUnion.rbegin(),
3105 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00003106 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00003107 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00003108 if (MOC->first && MOC->second) {
3109 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00003110 Composite1 = Context.getMemberPointerType(
3111 Context.getQualifiedType(Composite1, Quals),
3112 MOC->first);
3113 Composite2 = Context.getMemberPointerType(
3114 Context.getQualifiedType(Composite2, Quals),
3115 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00003116 } else {
3117 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00003118 Composite1
3119 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
3120 Composite2
3121 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00003122 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003123 }
3124
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003125 // Try to convert to the first composite pointer type.
3126 InitializedEntity Entity1
3127 = InitializedEntity::InitializeTemporary(Composite1);
3128 InitializationKind Kind
3129 = InitializationKind::CreateCopy(Loc, SourceLocation());
3130 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
3131 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00003132
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003133 if (E1ToC1 && E2ToC1) {
3134 // Conversion to Composite1 is viable.
3135 if (!Context.hasSameType(Composite1, Composite2)) {
3136 // Composite2 is a different type from Composite1. Check whether
3137 // Composite2 is also viable.
3138 InitializedEntity Entity2
3139 = InitializedEntity::InitializeTemporary(Composite2);
3140 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3141 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3142 if (E1ToC2 && E2ToC2) {
3143 // Both Composite1 and Composite2 are viable and are different;
3144 // this is an ambiguity.
3145 return QualType();
3146 }
3147 }
3148
3149 // Convert E1 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00003150 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00003151 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003152 if (E1Result.isInvalid())
3153 return QualType();
3154 E1 = E1Result.takeAs<Expr>();
3155
3156 // Convert E2 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00003157 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00003158 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003159 if (E2Result.isInvalid())
3160 return QualType();
3161 E2 = E2Result.takeAs<Expr>();
3162
3163 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003164 }
3165
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003166 // Check whether Composite2 is viable.
3167 InitializedEntity Entity2
3168 = InitializedEntity::InitializeTemporary(Composite2);
3169 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3170 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3171 if (!E1ToC2 || !E2ToC2)
3172 return QualType();
3173
3174 // Convert E1 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00003175 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00003176 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003177 if (E1Result.isInvalid())
3178 return QualType();
3179 E1 = E1Result.takeAs<Expr>();
3180
3181 // Convert E2 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00003182 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00003183 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003184 if (E2Result.isInvalid())
3185 return QualType();
3186 E2 = E2Result.takeAs<Expr>();
3187
3188 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003189}
Anders Carlsson165a0a02009-05-17 18:41:29 +00003190
John McCall60d7b3a2010-08-24 06:29:42 +00003191ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor19cc1c72010-11-01 21:10:29 +00003192 if (!E)
3193 return ExprError();
3194
Anders Carlsson089c2602009-08-15 23:41:35 +00003195 if (!Context.getLangOptions().CPlusPlus)
3196 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003197
Douglas Gregor51326552009-12-24 18:51:59 +00003198 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
3199
Ted Kremenek6217b802009-07-29 21:53:49 +00003200 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00003201 if (!RT)
3202 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003203
Anders Carlsson0ea4dfd2010-07-16 21:18:37 +00003204 // If this is the result of a call or an Objective-C message send expression,
3205 // our source might actually be a reference, in which case we shouldn't bind.
Anders Carlsson283e4d52009-09-14 01:30:44 +00003206 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
Anders Carlsson0ea4dfd2010-07-16 21:18:37 +00003207 if (CE->getCallReturnType()->isReferenceType())
Anders Carlsson283e4d52009-09-14 01:30:44 +00003208 return Owned(E);
Anders Carlsson0ea4dfd2010-07-16 21:18:37 +00003209 } else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
3210 if (const ObjCMethodDecl *MD = ME->getMethodDecl()) {
3211 if (MD->getResultType()->isReferenceType())
3212 return Owned(E);
3213 }
Anders Carlsson283e4d52009-09-14 01:30:44 +00003214 }
John McCall86ff3082010-02-04 22:26:26 +00003215
Jeffrey Yasskinc60e13a2011-01-25 20:08:12 +00003216 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3217 if (RD->getAttr<ForbidTemporariesAttr>())
3218 Diag(E->getExprLoc(), diag::warn_temporaries_forbidden) << E->getType();
3219
John McCall86ff3082010-02-04 22:26:26 +00003220 // That should be enough to guarantee that this type is complete.
3221 // If it has a trivial destructor, we can avoid the extra copy.
John McCall507384f2010-08-12 02:40:37 +00003222 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall86ff3082010-02-04 22:26:26 +00003223 return Owned(E);
3224
Douglas Gregordb89f282010-07-01 22:47:18 +00003225 CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD));
Anders Carlsson860306e2009-05-30 21:21:49 +00003226 ExprTemporaries.push_back(Temp);
Douglas Gregordb89f282010-07-01 22:47:18 +00003227 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003228 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00003229 CheckDestructorAccess(E->getExprLoc(), Destructor,
3230 PDiag(diag::err_access_dtor_temp)
3231 << E->getType());
3232 }
Anders Carlssondef11992009-05-30 20:36:53 +00003233 // FIXME: Add the temporary to the temporaries vector.
3234 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
3235}
3236
John McCall4765fa02010-12-06 08:20:24 +00003237Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003238 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00003239
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00003240 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3241 assert(ExprTemporaries.size() >= FirstTemporary);
3242 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003243 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003244
John McCall4765fa02010-12-06 08:20:24 +00003245 Expr *E = ExprWithCleanups::Create(Context, SubExpr,
3246 &ExprTemporaries[FirstTemporary],
3247 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00003248 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
3249 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00003250
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003251 return E;
3252}
3253
John McCall60d7b3a2010-08-24 06:29:42 +00003254ExprResult
John McCall4765fa02010-12-06 08:20:24 +00003255Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregor90f93822009-12-22 22:17:25 +00003256 if (SubExpr.isInvalid())
3257 return ExprError();
3258
John McCall4765fa02010-12-06 08:20:24 +00003259 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregor90f93822009-12-22 22:17:25 +00003260}
3261
John McCall4765fa02010-12-06 08:20:24 +00003262Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003263 assert(SubStmt && "sub statement can't be null!");
3264
3265 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3266 assert(ExprTemporaries.size() >= FirstTemporary);
3267 if (ExprTemporaries.size() == FirstTemporary)
3268 return SubStmt;
3269
3270 // FIXME: In order to attach the temporaries, wrap the statement into
3271 // a StmtExpr; currently this is only used for asm statements.
3272 // This is hacky, either create a new CXXStmtWithTemporaries statement or
3273 // a new AsmStmtWithTemporaries.
3274 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
3275 SourceLocation(),
3276 SourceLocation());
3277 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
3278 SourceLocation());
John McCall4765fa02010-12-06 08:20:24 +00003279 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003280}
3281
John McCall60d7b3a2010-08-24 06:29:42 +00003282ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003283Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallb3d87482010-08-24 05:47:05 +00003284 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00003285 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003286 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003287 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003288 if (Result.isInvalid()) return ExprError();
3289 Base = Result.get();
Mike Stump1eb44332009-09-09 15:08:12 +00003290
John McCall9ae2f072010-08-23 23:25:46 +00003291 QualType BaseType = Base->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00003292 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003293 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00003294 // If we have a pointer to a dependent type and are using the -> operator,
3295 // the object type is the type that the pointer points to. We might still
3296 // have enough information about that type to do something useful.
3297 if (OpKind == tok::arrow)
3298 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3299 BaseType = Ptr->getPointeeType();
3300
John McCallb3d87482010-08-24 05:47:05 +00003301 ObjectType = ParsedType::make(BaseType);
Douglas Gregord4dca082010-02-24 18:44:31 +00003302 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00003303 return Owned(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003304 }
Mike Stump1eb44332009-09-09 15:08:12 +00003305
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003306 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00003307 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003308 // returned, with the original second operand.
3309 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00003310 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00003311 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00003312 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00003313 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00003314
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003315 while (BaseType->isRecordType()) {
John McCall9ae2f072010-08-23 23:25:46 +00003316 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
3317 if (Result.isInvalid())
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003318 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00003319 Base = Result.get();
3320 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonde699e52009-10-13 22:55:59 +00003321 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCall9ae2f072010-08-23 23:25:46 +00003322 BaseType = Base->getType();
John McCallc4e83212009-09-30 01:01:30 +00003323 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00003324 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00003325 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00003326 for (unsigned i = 0; i < Locations.size(); i++)
3327 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00003328 return ExprError();
3329 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003330 }
Mike Stump1eb44332009-09-09 15:08:12 +00003331
Douglas Gregor31658df2009-11-20 19:58:21 +00003332 if (BaseType->isPointerType())
3333 BaseType = BaseType->getPointeeType();
3334 }
Mike Stump1eb44332009-09-09 15:08:12 +00003335
3336 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003337 // vector types or Objective-C interfaces. Just return early and let
3338 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00003339 if (!BaseType->isRecordType()) {
3340 // C++ [basic.lookup.classref]p2:
3341 // [...] If the type of the object expression is of pointer to scalar
3342 // type, the unqualified-id is looked up in the context of the complete
3343 // postfix-expression.
Douglas Gregord4dca082010-02-24 18:44:31 +00003344 //
3345 // This also indicates that we should be parsing a
3346 // pseudo-destructor-name.
John McCallb3d87482010-08-24 05:47:05 +00003347 ObjectType = ParsedType();
Douglas Gregord4dca082010-02-24 18:44:31 +00003348 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00003349 return Owned(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00003350 }
Mike Stump1eb44332009-09-09 15:08:12 +00003351
Douglas Gregor03c57052009-11-17 05:17:33 +00003352 // The object type must be complete (or dependent).
3353 if (!BaseType->isDependentType() &&
3354 RequireCompleteType(OpLoc, BaseType,
3355 PDiag(diag::err_incomplete_member_access)))
3356 return ExprError();
3357
Douglas Gregorc68afe22009-09-03 21:38:09 +00003358 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00003359 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00003360 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00003361 // type C (or of pointer to a class type C), the unqualified-id is looked
3362 // up in the scope of class C. [...]
John McCallb3d87482010-08-24 05:47:05 +00003363 ObjectType = ParsedType::make(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00003364 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003365}
3366
John McCall60d7b3a2010-08-24 06:29:42 +00003367ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003368 Expr *MemExpr) {
Douglas Gregor77549082010-02-24 21:29:12 +00003369 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCall9ae2f072010-08-23 23:25:46 +00003370 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
3371 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregor849b2432010-03-31 17:46:05 +00003372 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
Douglas Gregor77549082010-02-24 21:29:12 +00003373
3374 return ActOnCallExpr(/*Scope*/ 0,
John McCall9ae2f072010-08-23 23:25:46 +00003375 MemExpr,
Douglas Gregor77549082010-02-24 21:29:12 +00003376 /*LPLoc*/ ExpectedLParenLoc,
John McCallf312b1e2010-08-26 23:41:50 +00003377 MultiExprArg(),
Douglas Gregor77549082010-02-24 21:29:12 +00003378 /*RPLoc*/ ExpectedLParenLoc);
3379}
Douglas Gregord4dca082010-02-24 18:44:31 +00003380
John McCall60d7b3a2010-08-24 06:29:42 +00003381ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003382 SourceLocation OpLoc,
3383 tok::TokenKind OpKind,
3384 const CXXScopeSpec &SS,
Douglas Gregor26d4ac92010-02-24 23:40:28 +00003385 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003386 SourceLocation CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00003387 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003388 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003389 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003390 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
Douglas Gregorb57fb492010-02-24 22:38:50 +00003391
3392 // C++ [expr.pseudo]p2:
3393 // The left-hand side of the dot operator shall be of scalar type. The
3394 // left-hand side of the arrow operator shall be of pointer to scalar type.
3395 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00003396 QualType ObjectType = Base->getType();
Douglas Gregorb57fb492010-02-24 22:38:50 +00003397 if (OpKind == tok::arrow) {
3398 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3399 ObjectType = Ptr->getPointeeType();
John McCall9ae2f072010-08-23 23:25:46 +00003400 } else if (!Base->isTypeDependent()) {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003401 // The user wrote "p->" when she probably meant "p."; fix it.
3402 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3403 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00003404 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb57fb492010-02-24 22:38:50 +00003405 if (isSFINAEContext())
3406 return ExprError();
3407
3408 OpKind = tok::period;
3409 }
3410 }
3411
3412 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
3413 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
John McCall9ae2f072010-08-23 23:25:46 +00003414 << ObjectType << Base->getSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00003415 return ExprError();
3416 }
3417
3418 // C++ [expr.pseudo]p2:
3419 // [...] The cv-unqualified versions of the object type and of the type
3420 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003421 if (DestructedTypeInfo) {
3422 QualType DestructedType = DestructedTypeInfo->getType();
3423 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003424 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003425 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
3426 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
3427 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00003428 << ObjectType << DestructedType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003429 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003430
3431 // Recover by setting the destructed type to the object type.
3432 DestructedType = ObjectType;
3433 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
3434 DestructedTypeStart);
3435 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3436 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00003437 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003438
Douglas Gregorb57fb492010-02-24 22:38:50 +00003439 // C++ [expr.pseudo]p2:
3440 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
3441 // form
3442 //
3443 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
3444 //
3445 // shall designate the same scalar type.
3446 if (ScopeTypeInfo) {
3447 QualType ScopeType = ScopeTypeInfo->getType();
3448 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00003449 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003450
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003451 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00003452 diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00003453 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003454 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00003455
3456 ScopeType = QualType();
3457 ScopeTypeInfo = 0;
3458 }
3459 }
3460
John McCall9ae2f072010-08-23 23:25:46 +00003461 Expr *Result
3462 = new (Context) CXXPseudoDestructorExpr(Context, Base,
3463 OpKind == tok::arrow, OpLoc,
3464 SS.getScopeRep(), SS.getRange(),
3465 ScopeTypeInfo,
3466 CCLoc,
3467 TildeLoc,
3468 Destructed);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003469
Douglas Gregorb57fb492010-02-24 22:38:50 +00003470 if (HasTrailingLParen)
John McCall9ae2f072010-08-23 23:25:46 +00003471 return Owned(Result);
Douglas Gregorb57fb492010-02-24 22:38:50 +00003472
John McCall9ae2f072010-08-23 23:25:46 +00003473 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor77549082010-02-24 21:29:12 +00003474}
3475
John McCall60d7b3a2010-08-24 06:29:42 +00003476ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
Douglas Gregor77549082010-02-24 21:29:12 +00003477 SourceLocation OpLoc,
3478 tok::TokenKind OpKind,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003479 CXXScopeSpec &SS,
Douglas Gregor77549082010-02-24 21:29:12 +00003480 UnqualifiedId &FirstTypeName,
3481 SourceLocation CCLoc,
3482 SourceLocation TildeLoc,
3483 UnqualifiedId &SecondTypeName,
3484 bool HasTrailingLParen) {
3485 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3486 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3487 "Invalid first type name in pseudo-destructor");
3488 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3489 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3490 "Invalid second type name in pseudo-destructor");
3491
Douglas Gregor77549082010-02-24 21:29:12 +00003492 // C++ [expr.pseudo]p2:
3493 // The left-hand side of the dot operator shall be of scalar type. The
3494 // left-hand side of the arrow operator shall be of pointer to scalar type.
3495 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00003496 QualType ObjectType = Base->getType();
Douglas Gregor77549082010-02-24 21:29:12 +00003497 if (OpKind == tok::arrow) {
3498 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3499 ObjectType = Ptr->getPointeeType();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003500 } else if (!ObjectType->isDependentType()) {
Douglas Gregor77549082010-02-24 21:29:12 +00003501 // The user wrote "p->" when she probably meant "p."; fix it.
3502 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003503 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00003504 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor77549082010-02-24 21:29:12 +00003505 if (isSFINAEContext())
3506 return ExprError();
3507
3508 OpKind = tok::period;
3509 }
3510 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003511
3512 // Compute the object type that we should use for name lookup purposes. Only
3513 // record types and dependent types matter.
John McCallb3d87482010-08-24 05:47:05 +00003514 ParsedType ObjectTypePtrForLookup;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003515 if (!SS.isSet()) {
John McCallb3d87482010-08-24 05:47:05 +00003516 if (const Type *T = ObjectType->getAs<RecordType>())
3517 ObjectTypePtrForLookup = ParsedType::make(QualType(T, 0));
3518 else if (ObjectType->isDependentType())
3519 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003520 }
Douglas Gregor77549082010-02-24 21:29:12 +00003521
Douglas Gregorb57fb492010-02-24 22:38:50 +00003522 // Convert the name of the type being destructed (following the ~) into a
3523 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00003524 QualType DestructedType;
3525 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003526 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00003527 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
John McCallb3d87482010-08-24 05:47:05 +00003528 ParsedType T = getTypeName(*SecondTypeName.Identifier,
3529 SecondTypeName.StartLocation,
3530 S, &SS, true, ObjectTypePtrForLookup);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003531 if (!T &&
3532 ((SS.isSet() && !computeDeclContext(SS, false)) ||
3533 (!SS.isSet() && ObjectType->isDependentType()))) {
3534 // The name of the type being destroyed is a dependent name, and we
3535 // couldn't find anything useful in scope. Just store the identifier and
3536 // it's location, and we'll perform (qualified) name lookup again at
3537 // template instantiation time.
3538 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
3539 SecondTypeName.StartLocation);
3540 } else if (!T) {
Douglas Gregor77549082010-02-24 21:29:12 +00003541 Diag(SecondTypeName.StartLocation,
3542 diag::err_pseudo_dtor_destructor_non_type)
3543 << SecondTypeName.Identifier << ObjectType;
3544 if (isSFINAEContext())
3545 return ExprError();
3546
3547 // Recover by assuming we had the right type all along.
3548 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003549 } else
Douglas Gregor77549082010-02-24 21:29:12 +00003550 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003551 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003552 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00003553 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003554 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3555 TemplateId->getTemplateArgs(),
3556 TemplateId->NumArgs);
John McCall2b5289b2010-08-23 07:28:44 +00003557 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003558 TemplateId->TemplateNameLoc,
3559 TemplateId->LAngleLoc,
3560 TemplateArgsPtr,
3561 TemplateId->RAngleLoc);
3562 if (T.isInvalid() || !T.get()) {
3563 // Recover by assuming we had the right type all along.
3564 DestructedType = ObjectType;
3565 } else
3566 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003567 }
3568
Douglas Gregorb57fb492010-02-24 22:38:50 +00003569 // If we've performed some kind of recovery, (re-)build the type source
3570 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003571 if (!DestructedType.isNull()) {
3572 if (!DestructedTypeInfo)
3573 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003574 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003575 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3576 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00003577
3578 // Convert the name of the scope type (the type prior to '::') into a type.
3579 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00003580 QualType ScopeType;
3581 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3582 FirstTypeName.Identifier) {
3583 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
John McCallb3d87482010-08-24 05:47:05 +00003584 ParsedType T = getTypeName(*FirstTypeName.Identifier,
3585 FirstTypeName.StartLocation,
3586 S, &SS, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00003587 if (!T) {
3588 Diag(FirstTypeName.StartLocation,
3589 diag::err_pseudo_dtor_destructor_non_type)
3590 << FirstTypeName.Identifier << ObjectType;
Douglas Gregor77549082010-02-24 21:29:12 +00003591
Douglas Gregorb57fb492010-02-24 22:38:50 +00003592 if (isSFINAEContext())
3593 return ExprError();
3594
3595 // Just drop this type. It's unnecessary anyway.
3596 ScopeType = QualType();
3597 } else
3598 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003599 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003600 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00003601 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003602 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3603 TemplateId->getTemplateArgs(),
3604 TemplateId->NumArgs);
John McCall2b5289b2010-08-23 07:28:44 +00003605 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003606 TemplateId->TemplateNameLoc,
3607 TemplateId->LAngleLoc,
3608 TemplateArgsPtr,
3609 TemplateId->RAngleLoc);
3610 if (T.isInvalid() || !T.get()) {
3611 // Recover by dropping this type.
3612 ScopeType = QualType();
3613 } else
3614 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003615 }
3616 }
Douglas Gregorb4a418f2010-02-24 23:02:30 +00003617
3618 if (!ScopeType.isNull() && !ScopeTypeInfo)
3619 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
3620 FirstTypeName.StartLocation);
3621
3622
John McCall9ae2f072010-08-23 23:25:46 +00003623 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00003624 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003625 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00003626}
3627
Douglas Gregorf2ae5262011-01-20 00:18:04 +00003628ExprResult Sema::BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
3629 CXXMethodDecl *Method) {
John McCall6bb80172010-03-30 21:47:33 +00003630 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
3631 FoundDecl, Method))
Douglas Gregorf2ae5262011-01-20 00:18:04 +00003632 return true;
Eli Friedman772fffa2009-12-09 04:53:56 +00003633
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003634 MemberExpr *ME =
Abramo Bagnara25777432010-08-11 22:01:17 +00003635 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
John McCallf89e55a2010-11-18 06:31:45 +00003636 SourceLocation(), Method->getType(),
3637 VK_RValue, OK_Ordinary);
3638 QualType ResultType = Method->getResultType();
3639 ExprValueKind VK = Expr::getValueKindForType(ResultType);
3640 ResultType = ResultType.getNonLValueExprType(Context);
3641
Douglas Gregor7edfb692009-11-23 12:27:39 +00003642 MarkDeclarationReferenced(Exp->getLocStart(), Method);
3643 CXXMemberCallExpr *CE =
John McCallf89e55a2010-11-18 06:31:45 +00003644 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
Douglas Gregor7edfb692009-11-23 12:27:39 +00003645 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003646 return CE;
3647}
3648
Sebastian Redl2e156222010-09-10 20:55:43 +00003649ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
3650 SourceLocation RParen) {
Sebastian Redl2e156222010-09-10 20:55:43 +00003651 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
3652 Operand->CanThrow(Context),
3653 KeyLoc, RParen));
3654}
3655
3656ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
3657 Expr *Operand, SourceLocation RParen) {
3658 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl02bc21a2010-09-10 20:55:37 +00003659}
3660
John McCallf6a16482010-12-04 03:47:34 +00003661/// Perform the conversions required for an expression used in a
3662/// context that ignores the result.
3663void Sema::IgnoredValueConversions(Expr *&E) {
John McCalla878cda2010-12-02 02:07:15 +00003664 // C99 6.3.2.1:
3665 // [Except in specific positions,] an lvalue that does not have
3666 // array type is converted to the value stored in the
3667 // designated object (and is no longer an lvalue).
John McCallf6a16482010-12-04 03:47:34 +00003668 if (E->isRValue()) return;
John McCalla878cda2010-12-02 02:07:15 +00003669
John McCallf6a16482010-12-04 03:47:34 +00003670 // We always want to do this on ObjC property references.
3671 if (E->getObjectKind() == OK_ObjCProperty) {
3672 ConvertPropertyForRValue(E);
3673 if (E->isRValue()) return;
3674 }
3675
3676 // Otherwise, this rule does not apply in C++, at least not for the moment.
3677 if (getLangOptions().CPlusPlus) return;
3678
3679 // GCC seems to also exclude expressions of incomplete enum type.
3680 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
3681 if (!T->getDecl()->isComplete()) {
3682 // FIXME: stupid workaround for a codegen bug!
3683 ImpCastExprToType(E, Context.VoidTy, CK_ToVoid);
3684 return;
3685 }
3686 }
3687
3688 DefaultFunctionArrayLvalueConversion(E);
John McCall85515d62010-12-04 12:29:11 +00003689 if (!E->getType()->isVoidType())
3690 RequireCompleteType(E->getExprLoc(), E->getType(),
3691 diag::err_incomplete_type);
John McCallf6a16482010-12-04 03:47:34 +00003692}
3693
3694ExprResult Sema::ActOnFinishFullExpr(Expr *FullExpr) {
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003695 if (!FullExpr)
3696 return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00003697
Douglas Gregord0937222010-12-13 22:49:22 +00003698 if (DiagnoseUnexpandedParameterPack(FullExpr))
3699 return ExprError();
3700
John McCallf6a16482010-12-04 03:47:34 +00003701 IgnoredValueConversions(FullExpr);
John McCallb4eb64d2010-10-08 02:01:28 +00003702 CheckImplicitConversions(FullExpr);
John McCall4765fa02010-12-06 08:20:24 +00003703 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson165a0a02009-05-17 18:41:29 +00003704}
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003705
3706StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
3707 if (!FullStmt) return StmtError();
3708
John McCall4765fa02010-12-06 08:20:24 +00003709 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003710}