blob: b380a4b7a79c567bb7e5aed48b5fa5ed12e4399f [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 Pichet01b7c302010-09-08 12:20:18 +0000375/// \brief Build a Microsoft __uuidof expression with a type operand.
376ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
377 SourceLocation TypeidLoc,
378 TypeSourceInfo *Operand,
379 SourceLocation RParenLoc) {
380 // FIXME: add __uuidof semantic analysis for type operand.
381 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
382 Operand,
383 SourceRange(TypeidLoc, RParenLoc)));
384}
385
386/// \brief Build a Microsoft __uuidof expression with an expression operand.
387ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
388 SourceLocation TypeidLoc,
389 Expr *E,
390 SourceLocation RParenLoc) {
391 // FIXME: add __uuidof semantic analysis for expr operand.
392 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
393 E,
394 SourceRange(TypeidLoc, RParenLoc)));
395}
396
397/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
398ExprResult
399Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
400 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
401 // If MSVCGuidDecl has not been cached, do the lookup.
402 if (!MSVCGuidDecl) {
403 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
404 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
405 LookupQualifiedName(R, Context.getTranslationUnitDecl());
406 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
407 if (!MSVCGuidDecl)
408 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
409 }
410
411 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
412
413 if (isType) {
414 // The operand is a type; handle it as such.
415 TypeSourceInfo *TInfo = 0;
416 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
417 &TInfo);
418 if (T.isNull())
419 return ExprError();
420
421 if (!TInfo)
422 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
423
424 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
425 }
426
427 // The operand is an expression.
428 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
429}
430
Steve Naroff1b273c42007-09-16 14:56:35 +0000431/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCall60d7b3a2010-08-24 06:29:42 +0000432ExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000433Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000434 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000435 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000436 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
437 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000438}
Chris Lattner50dd2892008-02-26 00:51:44 +0000439
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000440/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCall60d7b3a2010-08-24 06:29:42 +0000441ExprResult
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000442Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
443 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
444}
445
Chris Lattner50dd2892008-02-26 00:51:44 +0000446/// ActOnCXXThrow - Parse throw expressions.
John McCall60d7b3a2010-08-24 06:29:42 +0000447ExprResult
John McCall9ae2f072010-08-23 23:25:46 +0000448Sema::ActOnCXXThrow(SourceLocation OpLoc, Expr *Ex) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000449 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
450 return ExprError();
451 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
452}
453
454/// CheckCXXThrowOperand - Validate the operand of a throw.
455bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
456 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000457 // A throw-expression initializes a temporary object, called the exception
458 // object, the type of which is determined by removing any top-level
459 // cv-qualifiers from the static type of the operand of throw and adjusting
460 // the type from "array of T" or "function returning T" to "pointer to T"
461 // or "pointer to function returning T", [...]
462 if (E->getType().hasQualifiers())
John McCall2de56d12010-08-25 11:45:40 +0000463 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
Sebastian Redl906082e2010-07-20 04:20:21 +0000464 CastCategory(E));
Douglas Gregor154fe982009-12-23 22:04:40 +0000465
Sebastian Redl972041f2009-04-27 20:27:31 +0000466 DefaultFunctionArrayConversion(E);
467
468 // If the type of the exception would be an incomplete type or a pointer
469 // to an incomplete type other than (cv) void the program is ill-formed.
470 QualType Ty = E->getType();
John McCallac418162010-04-22 01:10:34 +0000471 bool isPointer = false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000472 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000473 Ty = Ptr->getPointeeType();
John McCallac418162010-04-22 01:10:34 +0000474 isPointer = true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000475 }
476 if (!isPointer || !Ty->isVoidType()) {
477 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000478 PDiag(isPointer ? diag::err_throw_incomplete_ptr
479 : diag::err_throw_incomplete)
480 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000481 return true;
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000482
Douglas Gregorbf422f92010-04-15 18:05:39 +0000483 if (RequireNonAbstractType(ThrowLoc, E->getType(),
484 PDiag(diag::err_throw_abstract_type)
485 << E->getSourceRange()))
486 return true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000487 }
488
John McCallac418162010-04-22 01:10:34 +0000489 // Initialize the exception result. This implicitly weeds out
490 // abstract types or types with inaccessible copy constructors.
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000491 // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p34.
John McCallac418162010-04-22 01:10:34 +0000492 InitializedEntity Entity =
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000493 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
494 /*NRVO=*/false);
John McCall60d7b3a2010-08-24 06:29:42 +0000495 ExprResult Res = PerformCopyInitialization(Entity,
John McCallac418162010-04-22 01:10:34 +0000496 SourceLocation(),
497 Owned(E));
498 if (Res.isInvalid())
499 return true;
500 E = Res.takeAs<Expr>();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000501
Eli Friedman5ed9b932010-06-03 20:39:03 +0000502 // If the exception has class type, we need additional handling.
503 const RecordType *RecordTy = Ty->getAs<RecordType>();
504 if (!RecordTy)
505 return false;
506 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
507
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000508 // If we are throwing a polymorphic class type or pointer thereof,
509 // exception handling will make use of the vtable.
Eli Friedman5ed9b932010-06-03 20:39:03 +0000510 MarkVTableUsed(ThrowLoc, RD);
511
512 // If the class has a non-trivial destructor, we must be able to call it.
513 if (RD->hasTrivialDestructor())
514 return false;
515
Douglas Gregor1d110e02010-07-01 14:13:13 +0000516 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +0000517 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman5ed9b932010-06-03 20:39:03 +0000518 if (!Destructor)
519 return false;
520
521 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
522 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregored8abf12010-07-08 06:14:04 +0000523 PDiag(diag::err_access_dtor_exception) << Ty);
Sebastian Redl972041f2009-04-27 20:27:31 +0000524 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000525}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000526
John McCall60d7b3a2010-08-24 06:29:42 +0000527ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000528 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
529 /// is a non-lvalue expression whose value is the address of the object for
530 /// which the function is called.
531
John McCallea1471e2010-05-20 01:18:31 +0000532 DeclContext *DC = getFunctionLevelDeclContext();
533 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000534 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000535 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000536 MD->getThisType(Context),
537 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000538
Sebastian Redlf53597f2009-03-15 17:47:39 +0000539 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000540}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000541
John McCall60d7b3a2010-08-24 06:29:42 +0000542ExprResult
Douglas Gregorab6677e2010-09-08 00:15:04 +0000543Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000544 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000545 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000546 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000547 if (!TypeRep)
548 return ExprError();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000549
John McCall9d125032010-01-15 18:39:57 +0000550 TypeSourceInfo *TInfo;
551 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
552 if (!TInfo)
553 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregorab6677e2010-09-08 00:15:04 +0000554
555 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
556}
557
558/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
559/// Can be interpreted either as function-style casting ("int(x)")
560/// or class type construction ("ClassType(x,y,z)")
561/// or creation of a value-initialized type ("int()").
562ExprResult
563Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
564 SourceLocation LParenLoc,
565 MultiExprArg exprs,
566 SourceLocation RParenLoc) {
567 QualType Ty = TInfo->getType();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000568 unsigned NumExprs = exprs.size();
569 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000570 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000571 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
572
Sebastian Redlf53597f2009-03-15 17:47:39 +0000573 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000574 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000575 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000576
Douglas Gregorab6677e2010-09-08 00:15:04 +0000577 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000578 LParenLoc,
579 Exprs, NumExprs,
580 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000581 }
582
Anders Carlssonbb60a502009-08-27 03:53:50 +0000583 if (Ty->isArrayType())
584 return ExprError(Diag(TyBeginLoc,
585 diag::err_value_init_for_array_type) << FullRange);
586 if (!Ty->isVoidType() &&
587 RequireCompleteType(TyBeginLoc, Ty,
588 PDiag(diag::err_invalid_incomplete_type_use)
589 << FullRange))
590 return ExprError();
Fariborz Jahanianf071e9b2009-10-23 21:01:39 +0000591
Anders Carlssonbb60a502009-08-27 03:53:50 +0000592 if (RequireNonAbstractType(TyBeginLoc, Ty,
593 diag::err_allocation_of_abstract_type))
594 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000595
596
Douglas Gregor506ae412009-01-16 18:33:17 +0000597 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000598 // If the expression list is a single expression, the type conversion
599 // expression is equivalent (in definedness, and if defined in meaning) to the
600 // corresponding cast expression.
601 //
602 if (NumExprs == 1) {
John McCall2de56d12010-08-25 11:45:40 +0000603 CastKind Kind = CK_Unknown;
John McCallf871d0c2010-08-07 06:22:56 +0000604 CXXCastPath BasePath;
Douglas Gregorab6677e2010-09-08 00:15:04 +0000605 if (CheckCastTypes(TInfo->getTypeLoc().getSourceRange(), Ty, Exprs[0],
606 Kind, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000607 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000608 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000609
610 exprs.release();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000611
John McCallf871d0c2010-08-07 06:22:56 +0000612 return Owned(CXXFunctionalCastExpr::Create(Context,
Douglas Gregorab6677e2010-09-08 00:15:04 +0000613 Ty.getNonLValueExprType(Context),
John McCallf871d0c2010-08-07 06:22:56 +0000614 TInfo, TyBeginLoc, Kind,
615 Exprs[0], &BasePath,
616 RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000617 }
618
Douglas Gregor19311e72010-09-08 21:40:08 +0000619 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
620 InitializationKind Kind
621 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
622 LParenLoc, RParenLoc)
623 : InitializationKind::CreateValue(TyBeginLoc,
624 LParenLoc, RParenLoc);
625 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
626 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redlf53597f2009-03-15 17:47:39 +0000627
Douglas Gregor19311e72010-09-08 21:40:08 +0000628 // FIXME: Improve AST representation?
629 return move(Result);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000630}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000631
632
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000633/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
634/// @code new (memory) int[size][4] @endcode
635/// or
636/// @code ::new Foo(23, "hello") @endcode
637/// For the interpretation of this heap of arguments, consult the base version.
John McCall60d7b3a2010-08-24 06:29:42 +0000638ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000639Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000640 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000641 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000642 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000643 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000644 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000645 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000646 // If the specified type is an array, unwrap it and save the expression.
647 if (D.getNumTypeObjects() > 0 &&
648 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
649 DeclaratorChunk &Chunk = D.getTypeObject(0);
650 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000651 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
652 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000653 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000654 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
655 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000656
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000657 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000658 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000659 }
660
Douglas Gregor043cad22009-09-11 00:18:58 +0000661 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000662 if (ArraySize) {
663 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000664 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
665 break;
666
667 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
668 if (Expr *NumElts = (Expr *)Array.NumElts) {
669 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
670 !NumElts->isIntegerConstantExpr(Context)) {
671 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
672 << NumElts->getSourceRange();
673 return ExprError();
674 }
675 }
676 }
677 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000678
John McCallbf1a0282010-06-04 23:28:52 +0000679 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
680 QualType AllocType = TInfo->getType();
Chris Lattnereaaebc72009-04-25 08:06:05 +0000681 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000682 return ExprError();
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000683
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000684 if (!TInfo)
685 TInfo = Context.getTrivialTypeSourceInfo(AllocType);
686
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000687 SourceRange R = TInfo->getTypeLoc().getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000688 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000689 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000690 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000691 PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000692 TypeIdParens,
Mike Stump1eb44332009-09-09 15:08:12 +0000693 AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000694 TInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000695 ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000696 ConstructorLParen,
697 move(ConstructorArgs),
698 ConstructorRParen);
699}
700
John McCall60d7b3a2010-08-24 06:29:42 +0000701ExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000702Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
703 SourceLocation PlacementLParen,
704 MultiExprArg PlacementArgs,
705 SourceLocation PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000706 SourceRange TypeIdParens,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000707 QualType AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000708 TypeSourceInfo *AllocTypeInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000709 Expr *ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000710 SourceLocation ConstructorLParen,
711 MultiExprArg ConstructorArgs,
712 SourceLocation ConstructorRParen) {
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000713 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
714 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000715 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000716
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000717 // Per C++0x [expr.new]p5, the type being constructed may be a
718 // typedef of an array type.
John McCall9ae2f072010-08-23 23:25:46 +0000719 if (!ArraySize) {
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000720 if (const ConstantArrayType *Array
721 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000722 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
723 Context.getSizeType(),
724 TypeRange.getEnd());
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000725 AllocType = Array->getElementType();
726 }
727 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000728
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000729 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000730
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000731 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
732 // or enumeration type with a non-negative value."
Sebastian Redl28507842009-02-26 14:39:58 +0000733 if (ArraySize && !ArraySize->isTypeDependent()) {
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000734
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000735 QualType SizeType = ArraySize->getType();
Douglas Gregorc30614b2010-06-29 23:17:37 +0000736
John McCall60d7b3a2010-08-24 06:29:42 +0000737 ExprResult ConvertedSize
John McCall9ae2f072010-08-23 23:25:46 +0000738 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000739 PDiag(diag::err_array_size_not_integral),
740 PDiag(diag::err_array_size_incomplete_type)
741 << ArraySize->getSourceRange(),
742 PDiag(diag::err_array_size_explicit_conversion),
743 PDiag(diag::note_array_size_conversion),
744 PDiag(diag::err_array_size_ambiguous_conversion),
745 PDiag(diag::note_array_size_conversion),
746 PDiag(getLangOptions().CPlusPlus0x? 0
747 : diag::ext_array_size_conversion));
748 if (ConvertedSize.isInvalid())
749 return ExprError();
750
John McCall9ae2f072010-08-23 23:25:46 +0000751 ArraySize = ConvertedSize.take();
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000752 SizeType = ArraySize->getType();
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000753 if (!SizeType->isIntegralOrEnumerationType())
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000754 return ExprError();
755
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000756 // Let's see if this is a constant < 0. If so, we reject it out of hand.
757 // We don't care about special rules, so we tell the machinery it's not
758 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000759 if (!ArraySize->isValueDependent()) {
760 llvm::APSInt Value;
761 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
762 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000763 llvm::APInt::getNullValue(Value.getBitWidth()),
764 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000765 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +0000766 diag::err_typecheck_negative_array_size)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000767 << ArraySize->getSourceRange());
Douglas Gregor2767ce22010-08-18 00:39:00 +0000768
769 if (!AllocType->isDependentType()) {
770 unsigned ActiveSizeBits
771 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
772 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
773 Diag(ArraySize->getSourceRange().getBegin(),
774 diag::err_array_too_large)
775 << Value.toString(10)
776 << ArraySize->getSourceRange();
777 return ExprError();
778 }
779 }
Douglas Gregor4bd40312010-07-13 15:54:32 +0000780 } else if (TypeIdParens.isValid()) {
781 // Can't have dynamic array size when the type-id is in parentheses.
782 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
783 << ArraySize->getSourceRange()
784 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
785 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
786
787 TypeIdParens = SourceRange();
Sebastian Redl28507842009-02-26 14:39:58 +0000788 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000789 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000790
Eli Friedman73c39ab2009-10-20 08:27:19 +0000791 ImpCastExprToType(ArraySize, Context.getSizeType(),
John McCall2de56d12010-08-25 11:45:40 +0000792 CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000793 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000794
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000795 FunctionDecl *OperatorNew = 0;
796 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000797 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
798 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000799
Sebastian Redl28507842009-02-26 14:39:58 +0000800 if (!AllocType->isDependentType() &&
801 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
802 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000803 SourceRange(PlacementLParen, PlacementRParen),
804 UseGlobal, AllocType, ArraySize, PlaceArgs,
805 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000806 return ExprError();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000807 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000808 if (OperatorNew) {
809 // Add default arguments, if any.
810 const FunctionProtoType *Proto =
811 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000812 VariadicCallType CallType =
813 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Anders Carlsson28e94832010-05-03 02:07:56 +0000814
815 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
816 Proto, 1, PlaceArgs, NumPlaceArgs,
817 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000818 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000819
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000820 NumPlaceArgs = AllPlaceArgs.size();
821 if (NumPlaceArgs > 0)
822 PlaceArgs = &AllPlaceArgs[0];
823 }
824
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000825 bool Init = ConstructorLParen.isValid();
826 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000827 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000828 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
829 unsigned NumConsArgs = ConstructorArgs.size();
John McCallca0408f2010-08-23 06:44:23 +0000830 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000831
Anders Carlsson48c95012010-05-03 15:45:23 +0000832 // Array 'new' can't have any initializers.
Anders Carlsson55cbd6e2010-05-16 16:24:20 +0000833 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlsson48c95012010-05-03 15:45:23 +0000834 SourceRange InitRange(ConsArgs[0]->getLocStart(),
835 ConsArgs[NumConsArgs - 1]->getLocEnd());
836
837 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
838 return ExprError();
839 }
840
Douglas Gregor99a2e602009-12-16 01:38:02 +0000841 if (!AllocType->isDependentType() &&
842 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
843 // C++0x [expr.new]p15:
844 // A new-expression that creates an object of type T initializes that
845 // object as follows:
846 InitializationKind Kind
847 // - If the new-initializer is omitted, the object is default-
848 // initialized (8.5); if no initialization is performed,
849 // the object has indeterminate value
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000850 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
Douglas Gregor99a2e602009-12-16 01:38:02 +0000851 // - Otherwise, the new-initializer is interpreted according to the
852 // initialization rules of 8.5 for direct-initialization.
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000853 : InitializationKind::CreateDirect(TypeRange.getBegin(),
Douglas Gregor99a2e602009-12-16 01:38:02 +0000854 ConstructorLParen,
855 ConstructorRParen);
856
Douglas Gregor99a2e602009-12-16 01:38:02 +0000857 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +0000858 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000859 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
John McCall60d7b3a2010-08-24 06:29:42 +0000860 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor99a2e602009-12-16 01:38:02 +0000861 move(ConstructorArgs));
862 if (FullInit.isInvalid())
863 return ExprError();
864
865 // FullInit is our initializer; walk through it to determine if it's a
866 // constructor call, which CXXNewExpr handles directly.
867 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
868 if (CXXBindTemporaryExpr *Binder
869 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
870 FullInitExpr = Binder->getSubExpr();
871 if (CXXConstructExpr *Construct
872 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
873 Constructor = Construct->getConstructor();
874 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
875 AEnd = Construct->arg_end();
876 A != AEnd; ++A)
877 ConvertedConstructorArgs.push_back(A->Retain());
878 } else {
879 // Take the converted initializer.
880 ConvertedConstructorArgs.push_back(FullInit.release());
881 }
882 } else {
883 // No initialization required.
884 }
885
886 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +0000887 NumConsArgs = ConvertedConstructorArgs.size();
888 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000889 }
Douglas Gregor99a2e602009-12-16 01:38:02 +0000890
Douglas Gregor6d908702010-02-26 05:06:18 +0000891 // Mark the new and delete operators as referenced.
892 if (OperatorNew)
893 MarkDeclarationReferenced(StartLoc, OperatorNew);
894 if (OperatorDelete)
895 MarkDeclarationReferenced(StartLoc, OperatorDelete);
896
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000897 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000898
Sebastian Redlf53597f2009-03-15 17:47:39 +0000899 PlacementArgs.release();
900 ConstructorArgs.release();
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000901
Ted Kremenekad7fe862010-02-11 22:51:03 +0000902 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000903 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenekad7fe862010-02-11 22:51:03 +0000904 ArraySize, Constructor, Init,
905 ConsArgs, NumConsArgs, OperatorDelete,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000906 ResultType, AllocTypeInfo,
907 StartLoc,
Ted Kremenekad7fe862010-02-11 22:51:03 +0000908 Init ? ConstructorRParen :
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000909 TypeRange.getEnd()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000910}
911
912/// CheckAllocatedType - Checks that a type is suitable as the allocated type
913/// in a new-expression.
914/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000915bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000916 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000917 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
918 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000919 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000920 return Diag(Loc, diag::err_bad_new_type)
921 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000922 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000923 return Diag(Loc, diag::err_bad_new_type)
924 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000925 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000926 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000927 PDiag(diag::err_new_incomplete_type)
928 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000929 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000930 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000931 diag::err_allocation_of_abstract_type))
932 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000933
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000934 return false;
935}
936
Douglas Gregor6d908702010-02-26 05:06:18 +0000937/// \brief Determine whether the given function is a non-placement
938/// deallocation function.
939static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
940 if (FD->isInvalidDecl())
941 return false;
942
943 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
944 return Method->isUsualDeallocationFunction();
945
946 return ((FD->getOverloadedOperator() == OO_Delete ||
947 FD->getOverloadedOperator() == OO_Array_Delete) &&
948 FD->getNumParams() == 1);
949}
950
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000951/// FindAllocationFunctions - Finds the overloads of operator new and delete
952/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000953bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
954 bool UseGlobal, QualType AllocType,
955 bool IsArray, Expr **PlaceArgs,
956 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000957 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000958 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000959 // --- Choosing an allocation function ---
960 // C++ 5.3.4p8 - 14 & 18
961 // 1) If UseGlobal is true, only look in the global scope. Else, also look
962 // in the scope of the allocated class.
963 // 2) If an array size is given, look for operator new[], else look for
964 // operator new.
965 // 3) The first argument is always size_t. Append the arguments from the
966 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000967
968 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
969 // We don't care about the actual value of this argument.
970 // FIXME: Should the Sema create the expression and embed it in the syntax
971 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000972 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Anders Carlssond67c4c32009-08-16 20:29:29 +0000973 Context.Target.getPointerWidth(0)),
974 Context.getSizeType(),
975 SourceLocation());
976 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000977 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
978
Douglas Gregor6d908702010-02-26 05:06:18 +0000979 // C++ [expr.new]p8:
980 // If the allocated type is a non-array type, the allocation
981 // function’s name is operator new and the deallocation function’s
982 // name is operator delete. If the allocated type is an array
983 // type, the allocation function’s name is operator new[] and the
984 // deallocation function’s name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000985 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
986 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +0000987 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
988 IsArray ? OO_Array_Delete : OO_Delete);
989
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +0000990 QualType AllocElemType = Context.getBaseElementType(AllocType);
991
992 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000993 CXXRecordDecl *Record
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +0000994 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +0000995 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000996 AllocArgs.size(), Record, /*AllowMissing=*/true,
997 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000998 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000999 }
1000 if (!OperatorNew) {
1001 // Didn't find a member overload. Look for a global one.
1002 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +00001003 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +00001004 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001005 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1006 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001007 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001008 }
1009
John McCall9c82afc2010-04-20 02:18:25 +00001010 // We don't need an operator delete if we're running under
1011 // -fno-exceptions.
1012 if (!getLangOptions().Exceptions) {
1013 OperatorDelete = 0;
1014 return false;
1015 }
1016
Anders Carlssond9583892009-05-31 20:26:12 +00001017 // FindAllocationOverload can change the passed in arguments, so we need to
1018 // copy them back.
1019 if (NumPlaceArgs > 0)
1020 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001021
Douglas Gregor6d908702010-02-26 05:06:18 +00001022 // C++ [expr.new]p19:
1023 //
1024 // If the new-expression begins with a unary :: operator, the
1025 // deallocation function’s name is looked up in the global
1026 // scope. Otherwise, if the allocated type is a class type T or an
1027 // array thereof, the deallocation function’s name is looked up in
1028 // the scope of T. If this lookup fails to find the name, or if
1029 // the allocated type is not a class type or array thereof, the
1030 // deallocation function’s name is looked up in the global scope.
1031 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001032 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001033 CXXRecordDecl *RD
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001034 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6d908702010-02-26 05:06:18 +00001035 LookupQualifiedName(FoundDelete, RD);
1036 }
John McCall90c8c572010-03-18 08:19:33 +00001037 if (FoundDelete.isAmbiguous())
1038 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +00001039
1040 if (FoundDelete.empty()) {
1041 DeclareGlobalNewDelete();
1042 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1043 }
1044
1045 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +00001046
1047 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1048
John McCall90c8c572010-03-18 08:19:33 +00001049 if (NumPlaceArgs > 0) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001050 // C++ [expr.new]p20:
1051 // A declaration of a placement deallocation function matches the
1052 // declaration of a placement allocation function if it has the
1053 // same number of parameters and, after parameter transformations
1054 // (8.3.5), all parameter types except the first are
1055 // identical. [...]
1056 //
1057 // To perform this comparison, we compute the function type that
1058 // the deallocation function should have, and use that type both
1059 // for template argument deduction and for comparison purposes.
1060 QualType ExpectedFunctionType;
1061 {
1062 const FunctionProtoType *Proto
1063 = OperatorNew->getType()->getAs<FunctionProtoType>();
1064 llvm::SmallVector<QualType, 4> ArgTypes;
1065 ArgTypes.push_back(Context.VoidPtrTy);
1066 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1067 ArgTypes.push_back(Proto->getArgType(I));
1068
1069 ExpectedFunctionType
1070 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
1071 ArgTypes.size(),
1072 Proto->isVariadic(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001073 0, false, false, 0, 0,
1074 FunctionType::ExtInfo());
Douglas Gregor6d908702010-02-26 05:06:18 +00001075 }
1076
1077 for (LookupResult::iterator D = FoundDelete.begin(),
1078 DEnd = FoundDelete.end();
1079 D != DEnd; ++D) {
1080 FunctionDecl *Fn = 0;
1081 if (FunctionTemplateDecl *FnTmpl
1082 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1083 // Perform template argument deduction to try to match the
1084 // expected function type.
1085 TemplateDeductionInfo Info(Context, StartLoc);
1086 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1087 continue;
1088 } else
1089 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1090
1091 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001092 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001093 }
1094 } else {
1095 // C++ [expr.new]p20:
1096 // [...] Any non-placement deallocation function matches a
1097 // non-placement allocation function. [...]
1098 for (LookupResult::iterator D = FoundDelete.begin(),
1099 DEnd = FoundDelete.end();
1100 D != DEnd; ++D) {
1101 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1102 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001103 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001104 }
1105 }
1106
1107 // C++ [expr.new]p20:
1108 // [...] If the lookup finds a single matching deallocation
1109 // function, that function will be called; otherwise, no
1110 // deallocation function will be called.
1111 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001112 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001113
1114 // C++0x [expr.new]p20:
1115 // If the lookup finds the two-parameter form of a usual
1116 // deallocation function (3.7.4.2) and that function, considered
1117 // as a placement deallocation function, would have been
1118 // selected as a match for the allocation function, the program
1119 // is ill-formed.
1120 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1121 isNonPlacementDeallocationFunction(OperatorDelete)) {
1122 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1123 << SourceRange(PlaceArgs[0]->getLocStart(),
1124 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1125 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1126 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001127 } else {
1128 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001129 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001130 }
1131 }
1132
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001133 return false;
1134}
1135
Sebastian Redl7f662392008-12-04 22:20:51 +00001136/// FindAllocationOverload - Find an fitting overload for the allocation
1137/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001138bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1139 DeclarationName Name, Expr** Args,
1140 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +00001141 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001142 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1143 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001144 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001145 if (AllowMissing)
1146 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001147 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001148 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001149 }
1150
John McCall90c8c572010-03-18 08:19:33 +00001151 if (R.isAmbiguous())
1152 return true;
1153
1154 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001155
John McCall5769d612010-02-08 23:07:23 +00001156 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001157 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1158 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001159 // Even member operator new/delete are implicitly treated as
1160 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001161 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001162
John McCall9aa472c2010-03-19 07:35:19 +00001163 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1164 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001165 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1166 Candidates,
1167 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001168 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001169 }
1170
John McCall9aa472c2010-03-19 07:35:19 +00001171 FunctionDecl *Fn = cast<FunctionDecl>(D);
1172 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001173 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001174 }
1175
1176 // Do the resolution.
1177 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00001178 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001179 case OR_Success: {
1180 // Got one!
1181 FunctionDecl *FnDecl = Best->Function;
1182 // The first argument is size_t, and the first parameter must be size_t,
1183 // too. This is checked on declaration and can be assumed. (It can't be
1184 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001185 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001186 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1187 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
John McCall60d7b3a2010-08-24 06:29:42 +00001188 ExprResult Result
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001189 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
1190 FnDecl->getParamDecl(i)),
1191 SourceLocation(),
1192 Owned(Args[i]->Retain()));
1193 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001194 return true;
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001195
1196 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001197 }
1198 Operator = FnDecl;
John McCall9aa472c2010-03-19 07:35:19 +00001199 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001200 return false;
1201 }
1202
1203 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +00001204 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001205 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001206 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001207 return true;
1208
1209 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +00001210 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +00001211 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001212 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001213 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001214
1215 case OR_Deleted:
1216 Diag(StartLoc, diag::err_ovl_deleted_call)
1217 << Best->Function->isDeleted()
1218 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001219 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001220 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001221 }
1222 assert(false && "Unreachable, bad result from BestViableFunction");
1223 return true;
1224}
1225
1226
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001227/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1228/// delete. These are:
1229/// @code
1230/// void* operator new(std::size_t) throw(std::bad_alloc);
1231/// void* operator new[](std::size_t) throw(std::bad_alloc);
1232/// void operator delete(void *) throw();
1233/// void operator delete[](void *) throw();
1234/// @endcode
1235/// Note that the placement and nothrow forms of new are *not* implicitly
1236/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001237void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001238 if (GlobalNewDeleteDeclared)
1239 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001240
1241 // C++ [basic.std.dynamic]p2:
1242 // [...] The following allocation and deallocation functions (18.4) are
1243 // implicitly declared in global scope in each translation unit of a
1244 // program
1245 //
1246 // void* operator new(std::size_t) throw(std::bad_alloc);
1247 // void* operator new[](std::size_t) throw(std::bad_alloc);
1248 // void operator delete(void*) throw();
1249 // void operator delete[](void*) throw();
1250 //
1251 // These implicit declarations introduce only the function names operator
1252 // new, operator new[], operator delete, operator delete[].
1253 //
1254 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1255 // "std" or "bad_alloc" as necessary to form the exception specification.
1256 // However, we do not make these implicit declarations visible to name
1257 // lookup.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001258 if (!StdBadAlloc) {
1259 // The "std::bad_alloc" class has not yet been declared, so build it
1260 // implicitly.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001261 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00001262 getOrCreateStdNamespace(),
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001263 SourceLocation(),
1264 &PP.getIdentifierTable().get("bad_alloc"),
1265 SourceLocation(), 0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001266 getStdBadAlloc()->setImplicit(true);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001267 }
1268
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001269 GlobalNewDeleteDeclared = true;
1270
1271 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1272 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001273 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001274
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001275 DeclareGlobalAllocationFunction(
1276 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001277 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001278 DeclareGlobalAllocationFunction(
1279 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001280 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001281 DeclareGlobalAllocationFunction(
1282 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1283 Context.VoidTy, VoidPtr);
1284 DeclareGlobalAllocationFunction(
1285 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1286 Context.VoidTy, VoidPtr);
1287}
1288
1289/// DeclareGlobalAllocationFunction - Declares a single implicit global
1290/// allocation function if it doesn't already exist.
1291void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001292 QualType Return, QualType Argument,
1293 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001294 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1295
1296 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001297 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001298 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001299 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001300 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001301 // Only look at non-template functions, as it is the predefined,
1302 // non-templated allocation function we are trying to declare here.
1303 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1304 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001305 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001306 Func->getParamDecl(0)->getType().getUnqualifiedType());
1307 // FIXME: Do we need to check for default arguments here?
Douglas Gregor7b868622010-08-18 15:06:25 +00001308 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1309 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00001310 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001311 return;
Douglas Gregor7b868622010-08-18 15:06:25 +00001312 }
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001313 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001314 }
1315 }
1316
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001317 QualType BadAllocType;
1318 bool HasBadAllocExceptionSpec
1319 = (Name.getCXXOverloadedOperator() == OO_New ||
1320 Name.getCXXOverloadedOperator() == OO_Array_New);
1321 if (HasBadAllocExceptionSpec) {
1322 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001323 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001324 }
1325
1326 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1327 true, false,
1328 HasBadAllocExceptionSpec? 1 : 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00001329 &BadAllocType,
1330 FunctionType::ExtInfo());
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001331 FunctionDecl *Alloc =
1332 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCalld931b082010-08-26 03:08:43 +00001333 FnType, /*TInfo=*/0, SC_None,
1334 SC_None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001335 Alloc->setImplicit();
Nuno Lopesfc284482009-12-16 16:59:22 +00001336
1337 if (AddMallocAttr)
Sean Huntcf807c42010-08-18 23:23:40 +00001338 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Nuno Lopesfc284482009-12-16 16:59:22 +00001339
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001340 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00001341 0, Argument, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00001342 SC_None,
1343 SC_None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00001344 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001345
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001346 // FIXME: Also add this declaration to the IdentifierResolver, but
1347 // make sure it is at the end of the chain to coincide with the
1348 // global scope.
John McCall5f1e0942010-08-24 08:50:51 +00001349 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001350}
1351
Anders Carlsson78f74552009-11-15 18:45:20 +00001352bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1353 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00001354 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001355 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001356 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001357 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +00001358
John McCalla24dc2e2009-11-17 02:14:36 +00001359 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001360 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001361
Chandler Carruth23893242010-06-28 00:30:51 +00001362 Found.suppressDiagnostics();
1363
John McCall046a7462010-08-04 00:31:26 +00001364 llvm::SmallVector<DeclAccessPair,4> Matches;
Anders Carlsson78f74552009-11-15 18:45:20 +00001365 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1366 F != FEnd; ++F) {
Chandler Carruth09556fd2010-08-08 07:04:00 +00001367 NamedDecl *ND = (*F)->getUnderlyingDecl();
1368
1369 // Ignore template operator delete members from the check for a usual
1370 // deallocation function.
1371 if (isa<FunctionTemplateDecl>(ND))
1372 continue;
1373
1374 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall046a7462010-08-04 00:31:26 +00001375 Matches.push_back(F.getPair());
1376 }
1377
1378 // There's exactly one suitable operator; pick it.
1379 if (Matches.size() == 1) {
1380 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
1381 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1382 Matches[0]);
1383 return false;
1384
1385 // We found multiple suitable operators; complain about the ambiguity.
1386 } else if (!Matches.empty()) {
1387 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1388 << Name << RD;
1389
1390 for (llvm::SmallVectorImpl<DeclAccessPair>::iterator
1391 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1392 Diag((*F)->getUnderlyingDecl()->getLocation(),
1393 diag::note_member_declared_here) << Name;
1394 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001395 }
1396
1397 // We did find operator delete/operator delete[] declarations, but
1398 // none of them were suitable.
1399 if (!Found.empty()) {
1400 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1401 << Name << RD;
1402
1403 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
John McCall046a7462010-08-04 00:31:26 +00001404 F != FEnd; ++F)
1405 Diag((*F)->getUnderlyingDecl()->getLocation(),
1406 diag::note_member_declared_here) << Name;
Anders Carlsson78f74552009-11-15 18:45:20 +00001407
1408 return true;
1409 }
1410
1411 // Look for a global declaration.
1412 DeclareGlobalNewDelete();
1413 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1414
1415 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1416 Expr* DeallocArgs[1];
1417 DeallocArgs[0] = &Null;
1418 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1419 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1420 Operator))
1421 return true;
1422
1423 assert(Operator && "Did not find a deallocation function!");
1424 return false;
1425}
1426
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001427/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1428/// @code ::delete ptr; @endcode
1429/// or
1430/// @code delete [] ptr; @endcode
John McCall60d7b3a2010-08-24 06:29:42 +00001431ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001432Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John McCall9ae2f072010-08-23 23:25:46 +00001433 bool ArrayForm, Expr *Ex) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001434 // C++ [expr.delete]p1:
1435 // The operand shall have a pointer type, or a class type having a single
1436 // conversion function to a pointer type. The result has type void.
1437 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001438 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1439
Anders Carlssond67c4c32009-08-16 20:29:29 +00001440 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001441 bool ArrayFormAsWritten = ArrayForm;
Mike Stump1eb44332009-09-09 15:08:12 +00001442
Sebastian Redl28507842009-02-26 14:39:58 +00001443 if (!Ex->isTypeDependent()) {
1444 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001445
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001446 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor254a9422010-07-29 14:44:35 +00001447 if (RequireCompleteType(StartLoc, Type,
1448 PDiag(diag::err_delete_incomplete_class_type)))
1449 return ExprError();
1450
John McCall32daa422010-03-31 01:36:47 +00001451 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1452
Fariborz Jahanian53462782009-09-11 21:44:33 +00001453 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCall32daa422010-03-31 01:36:47 +00001454 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001455 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001456 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001457 NamedDecl *D = I.getDecl();
1458 if (isa<UsingShadowDecl>(D))
1459 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1460
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001461 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001462 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001463 continue;
1464
John McCall32daa422010-03-31 01:36:47 +00001465 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001466
1467 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1468 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedman13578692010-08-05 02:49:48 +00001469 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001470 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001471 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001472 if (ObjectPtrConversions.size() == 1) {
1473 // We have a single conversion to a pointer-to-object type. Perform
1474 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001475 // TODO: don't redo the conversion calculation.
John McCall32daa422010-03-31 01:36:47 +00001476 if (!PerformImplicitConversion(Ex,
1477 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +00001478 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001479 Type = Ex->getType();
1480 }
1481 }
1482 else if (ObjectPtrConversions.size() > 1) {
1483 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1484 << Type << Ex->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001485 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1486 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001487 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001488 }
Sebastian Redl28507842009-02-26 14:39:58 +00001489 }
1490
Sebastian Redlf53597f2009-03-15 17:47:39 +00001491 if (!Type->isPointerType())
1492 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1493 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001494
Ted Kremenek6217b802009-07-29 21:53:49 +00001495 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor94a61572010-05-24 17:01:56 +00001496 if (Pointee->isVoidType() && !isSFINAEContext()) {
1497 // The C++ standard bans deleting a pointer to a non-object type, which
1498 // effectively bans deletion of "void*". However, most compilers support
1499 // this, so we treat it as a warning unless we're in a SFINAE context.
1500 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1501 << Type << Ex->getSourceRange();
1502 } else if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001503 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1504 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001505 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001506 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +00001507 PDiag(diag::warn_delete_incomplete)
1508 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001509 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +00001510
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001511 // C++ [expr.delete]p2:
1512 // [Note: a pointer to a const type can be the operand of a
1513 // delete-expression; it is not necessary to cast away the constness
1514 // (5.2.11) of the pointer expression before it is used as the operand
1515 // of the delete-expression. ]
1516 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
John McCall2de56d12010-08-25 11:45:40 +00001517 CK_NoOp);
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001518
1519 if (Pointee->isArrayType() && !ArrayForm) {
1520 Diag(StartLoc, diag::warn_delete_array_type)
1521 << Type << Ex->getSourceRange()
1522 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1523 ArrayForm = true;
1524 }
1525
Anders Carlssond67c4c32009-08-16 20:29:29 +00001526 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1527 ArrayForm ? OO_Array_Delete : OO_Delete);
1528
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001529 QualType PointeeElem = Context.getBaseElementType(Pointee);
1530 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001531 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1532
1533 if (!UseGlobal &&
1534 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001535 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001536
Anders Carlsson78f74552009-11-15 18:45:20 +00001537 if (!RD->hasTrivialDestructor())
Douglas Gregordb89f282010-07-01 22:47:18 +00001538 if (const CXXDestructorDecl *Dtor = LookupDestructor(RD))
Mike Stump1eb44332009-09-09 15:08:12 +00001539 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001540 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +00001541 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001542
Anders Carlssond67c4c32009-08-16 20:29:29 +00001543 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001544 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001545 DeclareGlobalNewDelete();
1546 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001547 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +00001548 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001549 OperatorDelete))
1550 return ExprError();
1551 }
Mike Stump1eb44332009-09-09 15:08:12 +00001552
John McCall9c82afc2010-04-20 02:18:25 +00001553 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1554
Sebastian Redl28507842009-02-26 14:39:58 +00001555 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001556 }
1557
Sebastian Redlf53597f2009-03-15 17:47:39 +00001558 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001559 ArrayFormAsWritten, OperatorDelete,
1560 Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001561}
1562
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001563/// \brief Check the use of the given variable as a C++ condition in an if,
1564/// while, do-while, or switch statement.
John McCall60d7b3a2010-08-24 06:29:42 +00001565ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
Douglas Gregor586596f2010-05-06 17:25:47 +00001566 SourceLocation StmtLoc,
1567 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001568 QualType T = ConditionVar->getType();
1569
1570 // C++ [stmt.select]p2:
1571 // The declarator shall not specify a function or an array.
1572 if (T->isFunctionType())
1573 return ExprError(Diag(ConditionVar->getLocation(),
1574 diag::err_invalid_use_of_function_type)
1575 << ConditionVar->getSourceRange());
1576 else if (T->isArrayType())
1577 return ExprError(Diag(ConditionVar->getLocation(),
1578 diag::err_invalid_use_of_array_type)
1579 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001580
Douglas Gregor586596f2010-05-06 17:25:47 +00001581 Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1582 ConditionVar->getLocation(),
1583 ConditionVar->getType().getNonReferenceType());
Douglas Gregorff331c12010-07-25 18:17:45 +00001584 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc))
Douglas Gregor586596f2010-05-06 17:25:47 +00001585 return ExprError();
Douglas Gregor586596f2010-05-06 17:25:47 +00001586
1587 return Owned(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001588}
1589
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001590/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1591bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1592 // C++ 6.4p4:
1593 // The value of a condition that is an initialized declaration in a statement
1594 // other than a switch statement is the value of the declared variable
1595 // implicitly converted to type bool. If that conversion is ill-formed, the
1596 // program is ill-formed.
1597 // The value of a condition that is an expression is the value of the
1598 // expression, implicitly converted to bool.
1599 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001600 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001601}
Douglas Gregor77a52232008-09-12 00:47:35 +00001602
1603/// Helper function to determine whether this is the (deprecated) C++
1604/// conversion from a string literal to a pointer to non-const char or
1605/// non-const wchar_t (for narrow and wide string literals,
1606/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001607bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001608Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1609 // Look inside the implicit cast, if it exists.
1610 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1611 From = Cast->getSubExpr();
1612
1613 // A string literal (2.13.4) that is not a wide string literal can
1614 // be converted to an rvalue of type "pointer to char"; a wide
1615 // string literal can be converted to an rvalue of type "pointer
1616 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00001617 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00001618 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001619 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001620 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001621 // This conversion is considered only when there is an
1622 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001623 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001624 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1625 (!StrLit->isWide() &&
1626 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1627 ToPointeeType->getKind() == BuiltinType::Char_S))))
1628 return true;
1629 }
1630
1631 return false;
1632}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001633
John McCall60d7b3a2010-08-24 06:29:42 +00001634static ExprResult BuildCXXCastArgument(Sema &S,
John McCall2de56d12010-08-25 11:45:40 +00001635 SourceLocation CastLoc,
1636 QualType Ty,
1637 CastKind Kind,
1638 CXXMethodDecl *Method,
1639 Expr *From) {
Douglas Gregorba70ab62010-04-16 22:17:36 +00001640 switch (Kind) {
1641 default: assert(0 && "Unhandled cast kind!");
John McCall2de56d12010-08-25 11:45:40 +00001642 case CK_ConstructorConversion: {
John McCallca0408f2010-08-23 06:44:23 +00001643 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregorba70ab62010-04-16 22:17:36 +00001644
1645 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
John McCallf312b1e2010-08-26 23:41:50 +00001646 MultiExprArg(&From, 1),
Douglas Gregorba70ab62010-04-16 22:17:36 +00001647 CastLoc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00001648 return ExprError();
Douglas Gregorba70ab62010-04-16 22:17:36 +00001649
John McCall60d7b3a2010-08-24 06:29:42 +00001650 ExprResult Result =
Douglas Gregorba70ab62010-04-16 22:17:36 +00001651 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
John McCall7a1fad32010-08-24 07:32:53 +00001652 move_arg(ConstructorArgs),
1653 /*ZeroInit*/ false, CXXConstructExpr::CK_Complete);
Douglas Gregorba70ab62010-04-16 22:17:36 +00001654 if (Result.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00001655 return ExprError();
Douglas Gregorba70ab62010-04-16 22:17:36 +00001656
1657 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1658 }
1659
John McCall2de56d12010-08-25 11:45:40 +00001660 case CK_UserDefinedConversion: {
Douglas Gregorba70ab62010-04-16 22:17:36 +00001661 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1662
1663 // Create an implicit call expr that calls it.
1664 // FIXME: pass the FoundDecl for the user-defined conversion here
1665 CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method);
1666 return S.MaybeBindToTemporary(CE);
1667 }
1668 }
1669}
1670
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001671/// PerformImplicitConversion - Perform an implicit conversion of the
1672/// expression From to the type ToType using the pre-computed implicit
1673/// conversion sequence ICS. Returns true if there was an error, false
1674/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001675/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001676/// used in the error message.
1677bool
1678Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1679 const ImplicitConversionSequence &ICS,
Douglas Gregor68647482009-12-16 03:45:30 +00001680 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall1d318332010-01-12 00:44:57 +00001681 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001682 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001683 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001684 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001685 return true;
1686 break;
1687
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001688 case ImplicitConversionSequence::UserDefinedConversion: {
1689
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001690 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall2de56d12010-08-25 11:45:40 +00001691 CastKind CastKind = CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001692 QualType BeforeToType;
1693 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCall2de56d12010-08-25 11:45:40 +00001694 CastKind = CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001695
1696 // If the user-defined conversion is specified by a conversion function,
1697 // the initial standard conversion sequence converts the source type to
1698 // the implicit object parameter of the conversion function.
1699 BeforeToType = Context.getTagDeclType(Conv->getParent());
1700 } else if (const CXXConstructorDecl *Ctor =
1701 dyn_cast<CXXConstructorDecl>(FD)) {
John McCall2de56d12010-08-25 11:45:40 +00001702 CastKind = CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001703 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001704 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001705 // If the user-defined conversion is specified by a constructor, the
1706 // initial standard conversion sequence converts the source type to the
1707 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001708 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1709 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001710 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001711 else
1712 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001713 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001714 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001715 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001716 ICS.UserDefined.Before, AA_Converting,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001717 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001718 return true;
1719 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001720
John McCall60d7b3a2010-08-24 06:29:42 +00001721 ExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00001722 = BuildCXXCastArgument(*this,
1723 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00001724 ToType.getNonReferenceType(),
1725 CastKind, cast<CXXMethodDecl>(FD),
John McCall9ae2f072010-08-23 23:25:46 +00001726 From);
Anders Carlsson0aebc812009-09-09 21:33:21 +00001727
1728 if (CastArg.isInvalid())
1729 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001730
1731 From = CastArg.takeAs<Expr>();
1732
Eli Friedmand8889622009-11-27 04:41:50 +00001733 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor68647482009-12-16 03:45:30 +00001734 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001735 }
John McCall1d318332010-01-12 00:44:57 +00001736
1737 case ImplicitConversionSequence::AmbiguousConversion:
John McCall120d63c2010-08-24 20:38:10 +00001738 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall1d318332010-01-12 00:44:57 +00001739 PDiag(diag::err_typecheck_ambiguous_condition)
1740 << From->getSourceRange());
1741 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001742
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001743 case ImplicitConversionSequence::EllipsisConversion:
1744 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001745 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001746
1747 case ImplicitConversionSequence::BadConversion:
1748 return true;
1749 }
1750
1751 // Everything went well.
1752 return false;
1753}
1754
1755/// PerformImplicitConversion - Perform an implicit conversion of the
1756/// expression From to the type ToType by following the standard
1757/// conversion sequence SCS. Returns true if there was an error, false
1758/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001759/// expression. Flavor is the context in which we're performing this
1760/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001761bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001762Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001763 const StandardConversionSequence& SCS,
Douglas Gregor68647482009-12-16 03:45:30 +00001764 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001765 // Overall FIXME: we are recomputing too many types here and doing far too
1766 // much extra work. What this means is that we need to keep track of more
1767 // information that is computed when we try the implicit conversion initially,
1768 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001769 QualType FromType = From->getType();
1770
Douglas Gregor225c41e2008-11-03 19:09:14 +00001771 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001772 // FIXME: When can ToType be a reference type?
1773 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001774 if (SCS.Second == ICK_Derived_To_Base) {
John McCallca0408f2010-08-23 06:44:23 +00001775 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001776 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCallca0408f2010-08-23 06:44:23 +00001777 MultiExprArg(*this, &From, 1),
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001778 /*FIXME:ConstructLoc*/SourceLocation(),
1779 ConstructorArgs))
1780 return true;
John McCall60d7b3a2010-08-24 06:29:42 +00001781 ExprResult FromResult =
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001782 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1783 ToType, SCS.CopyConstructor,
John McCall7a1fad32010-08-24 07:32:53 +00001784 move_arg(ConstructorArgs),
1785 /*ZeroInit*/ false,
1786 CXXConstructExpr::CK_Complete);
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001787 if (FromResult.isInvalid())
1788 return true;
1789 From = FromResult.takeAs<Expr>();
1790 return false;
1791 }
John McCall60d7b3a2010-08-24 06:29:42 +00001792 ExprResult FromResult =
Mike Stump1eb44332009-09-09 15:08:12 +00001793 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1794 ToType, SCS.CopyConstructor,
John McCall7a1fad32010-08-24 07:32:53 +00001795 MultiExprArg(*this, &From, 1),
1796 /*ZeroInit*/ false,
1797 CXXConstructExpr::CK_Complete);
Mike Stump1eb44332009-09-09 15:08:12 +00001798
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001799 if (FromResult.isInvalid())
1800 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001801
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001802 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001803 return false;
1804 }
1805
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001806 // Resolve overloaded function references.
1807 if (Context.hasSameType(FromType, Context.OverloadTy)) {
1808 DeclAccessPair Found;
1809 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1810 true, Found);
1811 if (!Fn)
1812 return true;
1813
1814 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1815 return true;
1816
1817 From = FixOverloadedFunctionReference(From, Found, Fn);
1818 FromType = From->getType();
1819 }
1820
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001821 // Perform the first implicit conversion.
1822 switch (SCS.First) {
1823 case ICK_Identity:
1824 case ICK_Lvalue_To_Rvalue:
1825 // Nothing to do.
1826 break;
1827
1828 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001829 FromType = Context.getArrayDecayedType(FromType);
John McCall2de56d12010-08-25 11:45:40 +00001830 ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001831 break;
1832
1833 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001834 FromType = Context.getPointerType(FromType);
John McCall2de56d12010-08-25 11:45:40 +00001835 ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001836 break;
1837
1838 default:
1839 assert(false && "Improper first standard conversion");
1840 break;
1841 }
1842
1843 // Perform the second implicit conversion
1844 switch (SCS.Second) {
1845 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001846 // If both sides are functions (or pointers/references to them), there could
1847 // be incompatible exception declarations.
1848 if (CheckExceptionSpecCompatibility(From, ToType))
1849 return true;
1850 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001851 break;
1852
Douglas Gregor43c79c22009-12-09 00:47:37 +00001853 case ICK_NoReturn_Adjustment:
1854 // If both sides are functions (or pointers/references to them), there could
1855 // be incompatible exception declarations.
1856 if (CheckExceptionSpecCompatibility(From, ToType))
1857 return true;
1858
1859 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
John McCall2de56d12010-08-25 11:45:40 +00001860 CK_NoOp);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001861 break;
1862
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001863 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001864 case ICK_Integral_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00001865 ImpCastExprToType(From, ToType, CK_IntegralCast);
Eli Friedman73c39ab2009-10-20 08:27:19 +00001866 break;
1867
1868 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001869 case ICK_Floating_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00001870 ImpCastExprToType(From, ToType, CK_FloatingCast);
Eli Friedman73c39ab2009-10-20 08:27:19 +00001871 break;
1872
1873 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001874 case ICK_Complex_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00001875 ImpCastExprToType(From, ToType, CK_Unknown);
Eli Friedman73c39ab2009-10-20 08:27:19 +00001876 break;
1877
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001878 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001879 if (ToType->isRealFloatingType())
John McCall2de56d12010-08-25 11:45:40 +00001880 ImpCastExprToType(From, ToType, CK_IntegralToFloating);
Eli Friedman73c39ab2009-10-20 08:27:19 +00001881 else
John McCall2de56d12010-08-25 11:45:40 +00001882 ImpCastExprToType(From, ToType, CK_FloatingToIntegral);
Eli Friedman73c39ab2009-10-20 08:27:19 +00001883 break;
1884
Douglas Gregorf9201e02009-02-11 23:02:49 +00001885 case ICK_Compatible_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00001886 ImpCastExprToType(From, ToType, CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001887 break;
1888
Anders Carlsson61faec12009-09-12 04:46:44 +00001889 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001890 if (SCS.IncompatibleObjC) {
1891 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001892 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001893 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00001894 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00001895 << From->getSourceRange();
1896 }
1897
Anders Carlsson61faec12009-09-12 04:46:44 +00001898
John McCall2de56d12010-08-25 11:45:40 +00001899 CastKind Kind = CK_Unknown;
John McCallf871d0c2010-08-07 06:22:56 +00001900 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001901 if (CheckPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001902 return true;
John McCall5baba9d2010-08-25 10:28:54 +00001903 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001904 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001905 }
1906
1907 case ICK_Pointer_Member: {
John McCall2de56d12010-08-25 11:45:40 +00001908 CastKind Kind = CK_Unknown;
John McCallf871d0c2010-08-07 06:22:56 +00001909 CXXCastPath BasePath;
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001910 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath,
1911 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001912 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001913 if (CheckExceptionSpecCompatibility(From, ToType))
1914 return true;
John McCall5baba9d2010-08-25 10:28:54 +00001915 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
Anders Carlsson61faec12009-09-12 04:46:44 +00001916 break;
1917 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001918 case ICK_Boolean_Conversion: {
John McCall2de56d12010-08-25 11:45:40 +00001919 CastKind Kind = CK_Unknown;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001920 if (FromType->isMemberPointerType())
John McCall2de56d12010-08-25 11:45:40 +00001921 Kind = CK_MemberPointerToBoolean;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001922
1923 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001924 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001925 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001926
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001927 case ICK_Derived_To_Base: {
John McCallf871d0c2010-08-07 06:22:56 +00001928 CXXCastPath BasePath;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001929 if (CheckDerivedToBaseConversion(From->getType(),
1930 ToType.getNonReferenceType(),
1931 From->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001932 From->getSourceRange(),
1933 &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001934 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001935 return true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001936
Sebastian Redl906082e2010-07-20 04:20:21 +00001937 ImpCastExprToType(From, ToType.getNonReferenceType(),
John McCall2de56d12010-08-25 11:45:40 +00001938 CK_DerivedToBase, CastCategory(From),
John McCallf871d0c2010-08-07 06:22:56 +00001939 &BasePath);
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001940 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001941 }
1942
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001943 case ICK_Vector_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00001944 ImpCastExprToType(From, ToType, CK_BitCast);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001945 break;
1946
1947 case ICK_Vector_Splat:
John McCall2de56d12010-08-25 11:45:40 +00001948 ImpCastExprToType(From, ToType, CK_VectorSplat);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001949 break;
1950
1951 case ICK_Complex_Real:
John McCall2de56d12010-08-25 11:45:40 +00001952 ImpCastExprToType(From, ToType, CK_Unknown);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001953 break;
1954
1955 case ICK_Lvalue_To_Rvalue:
1956 case ICK_Array_To_Pointer:
1957 case ICK_Function_To_Pointer:
1958 case ICK_Qualification:
1959 case ICK_Num_Conversion_Kinds:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001960 assert(false && "Improper second standard conversion");
1961 break;
1962 }
1963
1964 switch (SCS.Third) {
1965 case ICK_Identity:
1966 // Nothing to do.
1967 break;
1968
Sebastian Redl906082e2010-07-20 04:20:21 +00001969 case ICK_Qualification: {
1970 // The qualification keeps the category of the inner expression, unless the
1971 // target type isn't a reference.
John McCall5baba9d2010-08-25 10:28:54 +00001972 ExprValueKind VK = ToType->isReferenceType() ?
1973 CastCategory(From) : VK_RValue;
Douglas Gregor63982352010-07-13 18:40:04 +00001974 ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
John McCall2de56d12010-08-25 11:45:40 +00001975 CK_NoOp, VK);
Douglas Gregora9bff302010-02-28 18:30:25 +00001976
1977 if (SCS.DeprecatedStringLiteralToCharPtr)
1978 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
1979 << ToType.getNonReferenceType();
1980
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001981 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00001982 }
1983
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001984 default:
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001985 assert(false && "Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001986 break;
1987 }
1988
1989 return false;
1990}
1991
Sebastian Redl0dfd8482010-09-13 20:56:31 +00001992ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001993 SourceLocation KWLoc,
1994 ParsedType Ty,
1995 SourceLocation RParen) {
1996 TypeSourceInfo *TSInfo;
1997 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00001998
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001999 if (!TSInfo)
2000 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002001 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002002}
2003
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002004static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT, QualType T) {
2005 assert(!T->isDependentType() &&
2006 "Cannot evaluate traits for dependent types.");
2007 ASTContext &C = Self.Context;
2008 switch(UTT) {
2009 default: assert(false && "Unknown type trait or not implemented");
2010 case UTT_IsPOD: return T->isPODType();
2011 case UTT_IsLiteral: return T->isLiteralType();
2012 case UTT_IsClass: // Fallthrough
2013 case UTT_IsUnion:
2014 if (const RecordType *Record = T->getAs<RecordType>()) {
2015 bool Union = Record->getDecl()->isUnion();
2016 return UTT == UTT_IsUnion ? Union : !Union;
2017 }
2018 return false;
2019 case UTT_IsEnum: return T->isEnumeralType();
2020 case UTT_IsPolymorphic:
2021 if (const RecordType *Record = T->getAs<RecordType>()) {
2022 // Type traits are only parsed in C++, so we've got CXXRecords.
2023 return cast<CXXRecordDecl>(Record->getDecl())->isPolymorphic();
2024 }
2025 return false;
2026 case UTT_IsAbstract:
2027 if (const RecordType *RT = T->getAs<RecordType>())
2028 return cast<CXXRecordDecl>(RT->getDecl())->isAbstract();
2029 return false;
2030 case UTT_IsEmpty:
2031 if (const RecordType *Record = T->getAs<RecordType>()) {
2032 return !Record->getDecl()->isUnion()
2033 && cast<CXXRecordDecl>(Record->getDecl())->isEmpty();
2034 }
2035 return false;
2036 case UTT_HasTrivialConstructor:
2037 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2038 // If __is_pod (type) is true then the trait is true, else if type is
2039 // a cv class or union type (or array thereof) with a trivial default
2040 // constructor ([class.ctor]) then the trait is true, else it is false.
2041 if (T->isPODType())
2042 return true;
2043 if (const RecordType *RT =
2044 C.getBaseElementType(T)->getAs<RecordType>())
2045 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialConstructor();
2046 return false;
2047 case UTT_HasTrivialCopy:
2048 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2049 // If __is_pod (type) is true or type is a reference type then
2050 // the trait is true, else if type is a cv class or union type
2051 // with a trivial copy constructor ([class.copy]) then the trait
2052 // is true, else it is false.
2053 if (T->isPODType() || T->isReferenceType())
2054 return true;
2055 if (const RecordType *RT = T->getAs<RecordType>())
2056 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2057 return false;
2058 case UTT_HasTrivialAssign:
2059 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2060 // If type is const qualified or is a reference type then the
2061 // trait is false. Otherwise if __is_pod (type) is true then the
2062 // trait is true, else if type is a cv class or union type with
2063 // a trivial copy assignment ([class.copy]) then the trait is
2064 // true, else it is false.
2065 // Note: the const and reference restrictions are interesting,
2066 // given that const and reference members don't prevent a class
2067 // from having a trivial copy assignment operator (but do cause
2068 // errors if the copy assignment operator is actually used, q.v.
2069 // [class.copy]p12).
2070
2071 if (C.getBaseElementType(T).isConstQualified())
2072 return false;
2073 if (T->isPODType())
2074 return true;
2075 if (const RecordType *RT = T->getAs<RecordType>())
2076 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2077 return false;
2078 case UTT_HasTrivialDestructor:
2079 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2080 // If __is_pod (type) is true or type is a reference type
2081 // then the trait is true, else if type is a cv class or union
2082 // type (or array thereof) with a trivial destructor
2083 // ([class.dtor]) then the trait is true, else it is
2084 // false.
2085 if (T->isPODType() || T->isReferenceType())
2086 return true;
2087 if (const RecordType *RT =
2088 C.getBaseElementType(T)->getAs<RecordType>())
2089 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2090 return false;
2091 // TODO: Propagate nothrowness for implicitly declared special members.
2092 case UTT_HasNothrowAssign:
2093 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2094 // If type is const qualified or is a reference type then the
2095 // trait is false. Otherwise if __has_trivial_assign (type)
2096 // is true then the trait is true, else if type is a cv class
2097 // or union type with copy assignment operators that are known
2098 // not to throw an exception then the trait is true, else it is
2099 // false.
2100 if (C.getBaseElementType(T).isConstQualified())
2101 return false;
2102 if (T->isReferenceType())
2103 return false;
2104 if (T->isPODType())
2105 return true;
2106 if (const RecordType *RT = T->getAs<RecordType>()) {
2107 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2108 if (RD->hasTrivialCopyAssignment())
2109 return true;
2110
2111 bool FoundAssign = false;
2112 bool AllNoThrow = true;
2113 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
2114 DeclContext::lookup_const_iterator Op, OpEnd;
2115 for (llvm::tie(Op, OpEnd) = RD->lookup(Name);
2116 Op != OpEnd; ++Op) {
2117 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2118 if (Operator->isCopyAssignmentOperator()) {
2119 FoundAssign = true;
2120 const FunctionProtoType *CPT
2121 = Operator->getType()->getAs<FunctionProtoType>();
2122 if (!CPT->hasEmptyExceptionSpec()) {
2123 AllNoThrow = false;
2124 break;
2125 }
2126 }
2127 }
2128
2129 return FoundAssign && AllNoThrow;
2130 }
2131 return false;
2132 case UTT_HasNothrowCopy:
2133 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2134 // If __has_trivial_copy (type) is true then the trait is true, else
2135 // if type is a cv class or union type with copy constructors that are
2136 // known not to throw an exception then the trait is true, else it is
2137 // false.
2138 if (T->isPODType() || T->isReferenceType())
2139 return true;
2140 if (const RecordType *RT = T->getAs<RecordType>()) {
2141 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2142 if (RD->hasTrivialCopyConstructor())
2143 return true;
2144
2145 bool FoundConstructor = false;
2146 bool AllNoThrow = true;
2147 unsigned FoundTQs;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002148 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl5f4e8992010-09-13 21:10:20 +00002149 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002150 Con != ConEnd; ++Con) {
2151 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2152 if (Constructor->isCopyConstructor(FoundTQs)) {
2153 FoundConstructor = true;
2154 const FunctionProtoType *CPT
2155 = Constructor->getType()->getAs<FunctionProtoType>();
Sebastian Redl751025d2010-09-13 22:02:47 +00002156 // TODO: check whether evaluating default arguments can throw.
2157 // For now, we'll be conservative and assume that they can throw.
2158 if (!CPT->hasEmptyExceptionSpec() || CPT->getNumArgs() > 1) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002159 AllNoThrow = false;
2160 break;
2161 }
2162 }
2163 }
2164
2165 return FoundConstructor && AllNoThrow;
2166 }
2167 return false;
2168 case UTT_HasNothrowConstructor:
2169 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2170 // If __has_trivial_constructor (type) is true then the trait is
2171 // true, else if type is a cv class or union type (or array
2172 // thereof) with a default constructor that is known not to
2173 // throw an exception then the trait is true, else it is false.
2174 if (T->isPODType())
2175 return true;
2176 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
2177 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2178 if (RD->hasTrivialConstructor())
2179 return true;
2180
Sebastian Redl751025d2010-09-13 22:02:47 +00002181 DeclContext::lookup_const_iterator Con, ConEnd;
2182 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2183 Con != ConEnd; ++Con) {
2184 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2185 if (Constructor->isDefaultConstructor()) {
2186 const FunctionProtoType *CPT
2187 = Constructor->getType()->getAs<FunctionProtoType>();
2188 // TODO: check whether evaluating default arguments can throw.
2189 // For now, we'll be conservative and assume that they can throw.
2190 return CPT->hasEmptyExceptionSpec() && CPT->getNumArgs() == 0;
2191 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002192 }
2193 }
2194 return false;
2195 case UTT_HasVirtualDestructor:
2196 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2197 // If type is a class type with a virtual destructor ([class.dtor])
2198 // then the trait is true, else it is false.
2199 if (const RecordType *Record = T->getAs<RecordType>()) {
2200 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2201 if (CXXDestructorDecl *Destructor = RD->getDestructor())
2202 return Destructor->isVirtual();
2203 }
2204 return false;
2205 }
2206}
2207
2208ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002209 SourceLocation KWLoc,
2210 TypeSourceInfo *TSInfo,
2211 SourceLocation RParen) {
2212 QualType T = TSInfo->getType();
2213
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002214 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
2215 // all traits except __is_class, __is_enum and __is_union require a the type
Sebastian Redl607a1782010-09-08 00:48:43 +00002216 // to be complete, an array of unknown bound, or void.
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002217 if (UTT != UTT_IsClass && UTT != UTT_IsEnum && UTT != UTT_IsUnion) {
Sebastian Redl607a1782010-09-08 00:48:43 +00002218 QualType E = T;
2219 if (T->isIncompleteArrayType())
2220 E = Context.getAsArrayType(T)->getElementType();
2221 if (!T->isVoidType() &&
2222 RequireCompleteType(KWLoc, E,
Anders Carlssond497ba72009-08-26 22:59:12 +00002223 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002224 return ExprError();
2225 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00002226
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002227 bool Value = false;
2228 if (!T->isDependentType())
2229 Value = EvaluateUnaryTypeTrait(*this, UTT, T);
2230
2231 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002232 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00002233}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002234
2235QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00002236 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002237 const char *OpSpelling = isIndirect ? "->*" : ".*";
2238 // C++ 5.5p2
2239 // The binary operator .* [p3: ->*] binds its second operand, which shall
2240 // be of type "pointer to member of T" (where T is a completely-defined
2241 // class type) [...]
2242 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002243 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00002244 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002245 Diag(Loc, diag::err_bad_memptr_rhs)
2246 << OpSpelling << RType << rex->getSourceRange();
2247 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00002248 }
Douglas Gregore7450f52009-03-24 19:52:54 +00002249
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002250 QualType Class(MemPtr->getClass(), 0);
2251
Sebastian Redl59fc2692010-04-10 10:14:54 +00002252 if (RequireCompleteType(Loc, Class, diag::err_memptr_rhs_to_incomplete))
2253 return QualType();
2254
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002255 // C++ 5.5p2
2256 // [...] to its first operand, which shall be of class T or of a class of
2257 // which T is an unambiguous and accessible base class. [p3: a pointer to
2258 // such a class]
2259 QualType LType = lex->getType();
2260 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002261 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002262 LType = Ptr->getPointeeType().getNonReferenceType();
2263 else {
2264 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00002265 << OpSpelling << 1 << LType
Douglas Gregor849b2432010-03-31 17:46:05 +00002266 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002267 return QualType();
2268 }
2269 }
2270
Douglas Gregora4923eb2009-11-16 21:35:15 +00002271 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00002272 // If we want to check the hierarchy, we need a complete type.
2273 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
2274 << OpSpelling << (int)isIndirect)) {
2275 return QualType();
2276 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002277 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002278 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00002279 // FIXME: Would it be useful to print full ambiguity paths, or is that
2280 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002281 if (!IsDerivedFrom(LType, Class, Paths) ||
2282 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
2283 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00002284 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002285 return QualType();
2286 }
Eli Friedman3005efe2010-01-16 00:00:48 +00002287 // Cast LHS to type of use.
2288 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
John McCall5baba9d2010-08-25 10:28:54 +00002289 ExprValueKind VK =
2290 isIndirect ? VK_RValue : CastCategory(lex);
Sebastian Redl906082e2010-07-20 04:20:21 +00002291
John McCallf871d0c2010-08-07 06:22:56 +00002292 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002293 BuildBasePathArray(Paths, BasePath);
John McCall5baba9d2010-08-25 10:28:54 +00002294 ImpCastExprToType(lex, UseType, CK_DerivedToBase, VK, &BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002295 }
2296
Douglas Gregored8abf12010-07-08 06:14:04 +00002297 if (isa<CXXScalarValueInitExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00002298 // Diagnose use of pointer-to-member type which when used as
2299 // the functional cast in a pointer-to-member expression.
2300 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
2301 return QualType();
2302 }
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002303 // C++ 5.5p2
2304 // The result is an object or a function of the type specified by the
2305 // second operand.
2306 // The cv qualifiers are the union of those in the pointer and the left side,
2307 // in accordance with 5.5p5 and 5.2.5.
2308 // FIXME: This returns a dereferenced member function pointer as a normal
2309 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00002310 // calling them. There's also a GCC extension to get a function pointer to the
2311 // thing, which is another complication, because this type - unlike the type
2312 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002313 // argument.
2314 // We probably need a "MemberFunctionClosureType" or something like that.
2315 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00002316 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002317 return Result;
2318}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002319
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002320/// \brief Try to convert a type to another according to C++0x 5.16p3.
2321///
2322/// This is part of the parameter validation for the ? operator. If either
2323/// value operand is a class type, the two operands are attempted to be
2324/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002325/// It returns true if the program is ill-formed and has already been diagnosed
2326/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002327static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
2328 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00002329 bool &HaveConversion,
2330 QualType &ToType) {
2331 HaveConversion = false;
2332 ToType = To->getType();
2333
2334 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
2335 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002336 // C++0x 5.16p3
2337 // The process for determining whether an operand expression E1 of type T1
2338 // can be converted to match an operand expression E2 of type T2 is defined
2339 // as follows:
2340 // -- If E2 is an lvalue:
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002341 bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid);
2342 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002343 // E1 can be converted to match E2 if E1 can be implicitly converted to
2344 // type "lvalue reference to T2", subject to the constraint that in the
2345 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002346 QualType T = Self.Context.getLValueReferenceType(ToType);
2347 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2348
2349 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2350 if (InitSeq.isDirectReferenceBinding()) {
2351 ToType = T;
2352 HaveConversion = true;
2353 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002354 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002355
2356 if (InitSeq.isAmbiguous())
2357 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002358 }
John McCallb1bdc622010-02-25 01:37:24 +00002359
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002360 // -- If E2 is an rvalue, or if the conversion above cannot be done:
2361 // -- if E1 and E2 have class type, and the underlying class types are
2362 // the same or one is a base class of the other:
2363 QualType FTy = From->getType();
2364 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002365 const RecordType *FRec = FTy->getAs<RecordType>();
2366 const RecordType *TRec = TTy->getAs<RecordType>();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002367 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
2368 Self.IsDerivedFrom(FTy, TTy);
2369 if (FRec && TRec &&
2370 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002371 // E1 can be converted to match E2 if the class of T2 is the
2372 // same type as, or a base class of, the class of T1, and
2373 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00002374 if (FRec == TRec || FDerivedFromT) {
2375 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002376 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2377 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2378 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2379 HaveConversion = true;
2380 return false;
2381 }
2382
2383 if (InitSeq.isAmbiguous())
2384 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2385 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002386 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002387
2388 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002389 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002390
2391 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2392 // implicitly converted to the type that expression E2 would have
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002393 // if E2 were converted to an rvalue (or the type it has, if E2 is
2394 // an rvalue).
2395 //
2396 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2397 // to the array-to-pointer or function-to-pointer conversions.
2398 if (!TTy->getAs<TagType>())
2399 TTy = TTy.getUnqualifiedType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002400
2401 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2402 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2403 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
2404 ToType = TTy;
2405 if (InitSeq.isAmbiguous())
2406 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2407
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002408 return false;
2409}
2410
2411/// \brief Try to find a common type for two according to C++0x 5.16p5.
2412///
2413/// This is part of the parameter validation for the ? operator. If either
2414/// value operand is a class type, overload resolution is used to find a
2415/// conversion to a common type.
2416static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2417 SourceLocation Loc) {
2418 Expr *Args[2] = { LHS, RHS };
John McCall5769d612010-02-08 23:07:23 +00002419 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor573d9c32009-10-21 23:19:44 +00002420 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002421
2422 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00002423 switch (CandidateSet.BestViableFunction(Self, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002424 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002425 // We found a match. Perform the conversions on the arguments and move on.
2426 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00002427 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002428 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00002429 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002430 break;
2431 return false;
2432
Douglas Gregor20093b42009-12-09 23:02:17 +00002433 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002434 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2435 << LHS->getType() << RHS->getType()
2436 << LHS->getSourceRange() << RHS->getSourceRange();
2437 return true;
2438
Douglas Gregor20093b42009-12-09 23:02:17 +00002439 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002440 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2441 << LHS->getType() << RHS->getType()
2442 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00002443 // FIXME: Print the possible common types by printing the return types of
2444 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002445 break;
2446
Douglas Gregor20093b42009-12-09 23:02:17 +00002447 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002448 assert(false && "Conditional operator has only built-in overloads");
2449 break;
2450 }
2451 return true;
2452}
2453
Sebastian Redl76458502009-04-17 16:30:52 +00002454/// \brief Perform an "extended" implicit conversion as returned by
2455/// TryClassUnification.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002456static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2457 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2458 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2459 SourceLocation());
2460 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
John McCallf312b1e2010-08-26 23:41:50 +00002461 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&E, 1));
Douglas Gregorb70cf442010-03-26 20:14:36 +00002462 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00002463 return true;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002464
2465 E = Result.takeAs<Expr>();
Sebastian Redl76458502009-04-17 16:30:52 +00002466 return false;
2467}
2468
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002469/// \brief Check the operands of ?: under C++ semantics.
2470///
2471/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2472/// extension. In this case, LHS == Cond. (But they're not aliases.)
2473QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2474 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002475 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2476 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002477
2478 // C++0x 5.16p1
2479 // The first expression is contextually converted to bool.
2480 if (!Cond->isTypeDependent()) {
2481 if (CheckCXXBooleanCondition(Cond))
2482 return QualType();
2483 }
2484
2485 // Either of the arguments dependent?
2486 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2487 return Context.DependentTy;
2488
2489 // C++0x 5.16p2
2490 // If either the second or the third operand has type (cv) void, ...
2491 QualType LTy = LHS->getType();
2492 QualType RTy = RHS->getType();
2493 bool LVoid = LTy->isVoidType();
2494 bool RVoid = RTy->isVoidType();
2495 if (LVoid || RVoid) {
2496 // ... then the [l2r] conversions are performed on the second and third
2497 // operands ...
Douglas Gregora873dfc2010-02-03 00:27:59 +00002498 DefaultFunctionArrayLvalueConversion(LHS);
2499 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002500 LTy = LHS->getType();
2501 RTy = RHS->getType();
2502
2503 // ... and one of the following shall hold:
2504 // -- The second or the third operand (but not both) is a throw-
2505 // expression; the result is of the type of the other and is an rvalue.
2506 bool LThrow = isa<CXXThrowExpr>(LHS);
2507 bool RThrow = isa<CXXThrowExpr>(RHS);
2508 if (LThrow && !RThrow)
2509 return RTy;
2510 if (RThrow && !LThrow)
2511 return LTy;
2512
2513 // -- Both the second and third operands have type void; the result is of
2514 // type void and is an rvalue.
2515 if (LVoid && RVoid)
2516 return Context.VoidTy;
2517
2518 // Neither holds, error.
2519 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2520 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2521 << LHS->getSourceRange() << RHS->getSourceRange();
2522 return QualType();
2523 }
2524
2525 // Neither is void.
2526
2527 // C++0x 5.16p3
2528 // Otherwise, if the second and third operand have different types, and
2529 // either has (cv) class type, and attempt is made to convert each of those
2530 // operands to the other.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002531 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002532 (LTy->isRecordType() || RTy->isRecordType())) {
2533 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2534 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002535 QualType L2RType, R2LType;
2536 bool HaveL2R, HaveR2L;
2537 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002538 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002539 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002540 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002541
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002542 // If both can be converted, [...] the program is ill-formed.
2543 if (HaveL2R && HaveR2L) {
2544 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2545 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2546 return QualType();
2547 }
2548
2549 // If exactly one conversion is possible, that conversion is applied to
2550 // the chosen operand and the converted operands are used in place of the
2551 // original operands for the remainder of this section.
2552 if (HaveL2R) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002553 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002554 return QualType();
2555 LTy = LHS->getType();
2556 } else if (HaveR2L) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002557 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002558 return QualType();
2559 RTy = RHS->getType();
2560 }
2561 }
2562
2563 // C++0x 5.16p4
2564 // If the second and third operands are lvalues and have the same type,
2565 // the result is of that type [...]
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002566 bool Same = Context.hasSameType(LTy, RTy);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002567 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
2568 RHS->isLvalue(Context) == Expr::LV_Valid)
2569 return LTy;
2570
2571 // C++0x 5.16p5
2572 // Otherwise, the result is an rvalue. If the second and third operands
2573 // do not have the same type, and either has (cv) class type, ...
2574 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2575 // ... overload resolution is used to determine the conversions (if any)
2576 // to be applied to the operands. If the overload resolution fails, the
2577 // program is ill-formed.
2578 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2579 return QualType();
2580 }
2581
2582 // C++0x 5.16p6
2583 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2584 // conversions are performed on the second and third operands.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002585 DefaultFunctionArrayLvalueConversion(LHS);
2586 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002587 LTy = LHS->getType();
2588 RTy = RHS->getType();
2589
2590 // After those conversions, one of the following shall hold:
2591 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00002592 // is of that type. If the operands have class type, the result
2593 // is a prvalue temporary of the result type, which is
2594 // copy-initialized from either the second operand or the third
2595 // operand depending on the value of the first operand.
2596 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
2597 if (LTy->isRecordType()) {
2598 // The operands have class type. Make a temporary copy.
2599 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
John McCall60d7b3a2010-08-24 06:29:42 +00002600 ExprResult LHSCopy = PerformCopyInitialization(Entity,
Douglas Gregorb65a4582010-05-19 23:40:50 +00002601 SourceLocation(),
2602 Owned(LHS));
2603 if (LHSCopy.isInvalid())
2604 return QualType();
2605
John McCall60d7b3a2010-08-24 06:29:42 +00002606 ExprResult RHSCopy = PerformCopyInitialization(Entity,
Douglas Gregorb65a4582010-05-19 23:40:50 +00002607 SourceLocation(),
2608 Owned(RHS));
2609 if (RHSCopy.isInvalid())
2610 return QualType();
2611
2612 LHS = LHSCopy.takeAs<Expr>();
2613 RHS = RHSCopy.takeAs<Expr>();
2614 }
2615
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002616 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00002617 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002618
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002619 // Extension: conditional operator involving vector types.
2620 if (LTy->isVectorType() || RTy->isVectorType())
2621 return CheckVectorOperands(QuestionLoc, LHS, RHS);
2622
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002623 // -- The second and third operands have arithmetic or enumeration type;
2624 // the usual arithmetic conversions are performed to bring them to a
2625 // common type, and the result is of that type.
2626 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2627 UsualArithmeticConversions(LHS, RHS);
2628 return LHS->getType();
2629 }
2630
2631 // -- The second and third operands have pointer type, or one has pointer
2632 // type and the other is a null pointer constant; pointer conversions
2633 // and qualification conversions are performed to bring them to their
2634 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00002635 // -- The second and third operands have pointer to member type, or one has
2636 // pointer to member type and the other is a null pointer constant;
2637 // pointer to member conversions and qualification conversions are
2638 // performed to bring them to a common type, whose cv-qualification
2639 // shall match the cv-qualification of either the second or the third
2640 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002641 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002642 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002643 isSFINAEContext()? 0 : &NonStandardCompositeType);
2644 if (!Composite.isNull()) {
2645 if (NonStandardCompositeType)
2646 Diag(QuestionLoc,
2647 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2648 << LTy << RTy << Composite
2649 << LHS->getSourceRange() << RHS->getSourceRange();
2650
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002651 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002652 }
Fariborz Jahanian55016362009-12-10 20:46:08 +00002653
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002654 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00002655 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2656 if (!Composite.isNull())
2657 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002658
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002659 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2660 << LHS->getType() << RHS->getType()
2661 << LHS->getSourceRange() << RHS->getSourceRange();
2662 return QualType();
2663}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002664
2665/// \brief Find a merged pointer type and convert the two expressions to it.
2666///
Douglas Gregor20b3e992009-08-24 17:42:35 +00002667/// This finds the composite pointer type (or member pointer type) for @p E1
2668/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2669/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002670/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002671///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002672/// \param Loc The location of the operator requiring these two expressions to
2673/// be converted to the composite pointer type.
2674///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002675/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2676/// a non-standard (but still sane) composite type to which both expressions
2677/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2678/// will be set true.
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002679QualType Sema::FindCompositePointerType(SourceLocation Loc,
2680 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002681 bool *NonStandardCompositeType) {
2682 if (NonStandardCompositeType)
2683 *NonStandardCompositeType = false;
2684
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002685 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2686 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002687
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00002688 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2689 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00002690 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002691
2692 // C++0x 5.9p2
2693 // Pointer conversions and qualification conversions are performed on
2694 // pointer operands to bring them to their composite pointer type. If
2695 // one operand is a null pointer constant, the composite pointer type is
2696 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00002697 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002698 if (T2->isMemberPointerType())
John McCall2de56d12010-08-25 11:45:40 +00002699 ImpCastExprToType(E1, T2, CK_NullToMemberPointer);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002700 else
John McCall2de56d12010-08-25 11:45:40 +00002701 ImpCastExprToType(E1, T2, CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002702 return T2;
2703 }
Douglas Gregorce940492009-09-25 04:25:58 +00002704 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002705 if (T1->isMemberPointerType())
John McCall2de56d12010-08-25 11:45:40 +00002706 ImpCastExprToType(E2, T1, CK_NullToMemberPointer);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002707 else
John McCall2de56d12010-08-25 11:45:40 +00002708 ImpCastExprToType(E2, T1, CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002709 return T1;
2710 }
Mike Stump1eb44332009-09-09 15:08:12 +00002711
Douglas Gregor20b3e992009-08-24 17:42:35 +00002712 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002713 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2714 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002715 return QualType();
2716
2717 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2718 // the other has type "pointer to cv2 T" and the composite pointer type is
2719 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2720 // Otherwise, the composite pointer type is a pointer type similar to the
2721 // type of one of the operands, with a cv-qualification signature that is
2722 // the union of the cv-qualification signatures of the operand types.
2723 // In practice, the first part here is redundant; it's subsumed by the second.
2724 // What we do here is, we build the two possible composite types, and try the
2725 // conversions in both directions. If only one works, or if the two composite
2726 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00002727 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00002728 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2729 QualifierVector QualifierUnion;
2730 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2731 ContainingClassVector;
2732 ContainingClassVector MemberOfClass;
2733 QualType Composite1 = Context.getCanonicalType(T1),
2734 Composite2 = Context.getCanonicalType(T2);
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002735 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00002736 do {
2737 const PointerType *Ptr1, *Ptr2;
2738 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2739 (Ptr2 = Composite2->getAs<PointerType>())) {
2740 Composite1 = Ptr1->getPointeeType();
2741 Composite2 = Ptr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002742
2743 // If we're allowed to create a non-standard composite type, keep track
2744 // of where we need to fill in additional 'const' qualifiers.
2745 if (NonStandardCompositeType &&
2746 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2747 NeedConstBefore = QualifierUnion.size();
2748
Douglas Gregor20b3e992009-08-24 17:42:35 +00002749 QualifierUnion.push_back(
2750 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2751 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2752 continue;
2753 }
Mike Stump1eb44332009-09-09 15:08:12 +00002754
Douglas Gregor20b3e992009-08-24 17:42:35 +00002755 const MemberPointerType *MemPtr1, *MemPtr2;
2756 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2757 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2758 Composite1 = MemPtr1->getPointeeType();
2759 Composite2 = MemPtr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002760
2761 // If we're allowed to create a non-standard composite type, keep track
2762 // of where we need to fill in additional 'const' qualifiers.
2763 if (NonStandardCompositeType &&
2764 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2765 NeedConstBefore = QualifierUnion.size();
2766
Douglas Gregor20b3e992009-08-24 17:42:35 +00002767 QualifierUnion.push_back(
2768 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2769 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2770 MemPtr2->getClass()));
2771 continue;
2772 }
Mike Stump1eb44332009-09-09 15:08:12 +00002773
Douglas Gregor20b3e992009-08-24 17:42:35 +00002774 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00002775
Douglas Gregor20b3e992009-08-24 17:42:35 +00002776 // Cannot unwrap any more types.
2777 break;
2778 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00002779
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002780 if (NeedConstBefore && NonStandardCompositeType) {
2781 // Extension: Add 'const' to qualifiers that come before the first qualifier
2782 // mismatch, so that our (non-standard!) composite type meets the
2783 // requirements of C++ [conv.qual]p4 bullet 3.
2784 for (unsigned I = 0; I != NeedConstBefore; ++I) {
2785 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
2786 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
2787 *NonStandardCompositeType = true;
2788 }
2789 }
2790 }
2791
Douglas Gregor20b3e992009-08-24 17:42:35 +00002792 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002793 ContainingClassVector::reverse_iterator MOC
2794 = MemberOfClass.rbegin();
2795 for (QualifierVector::reverse_iterator
2796 I = QualifierUnion.rbegin(),
2797 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00002798 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00002799 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002800 if (MOC->first && MOC->second) {
2801 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00002802 Composite1 = Context.getMemberPointerType(
2803 Context.getQualifiedType(Composite1, Quals),
2804 MOC->first);
2805 Composite2 = Context.getMemberPointerType(
2806 Context.getQualifiedType(Composite2, Quals),
2807 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002808 } else {
2809 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00002810 Composite1
2811 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2812 Composite2
2813 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00002814 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002815 }
2816
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002817 // Try to convert to the first composite pointer type.
2818 InitializedEntity Entity1
2819 = InitializedEntity::InitializeTemporary(Composite1);
2820 InitializationKind Kind
2821 = InitializationKind::CreateCopy(Loc, SourceLocation());
2822 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
2823 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00002824
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002825 if (E1ToC1 && E2ToC1) {
2826 // Conversion to Composite1 is viable.
2827 if (!Context.hasSameType(Composite1, Composite2)) {
2828 // Composite2 is a different type from Composite1. Check whether
2829 // Composite2 is also viable.
2830 InitializedEntity Entity2
2831 = InitializedEntity::InitializeTemporary(Composite2);
2832 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2833 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2834 if (E1ToC2 && E2ToC2) {
2835 // Both Composite1 and Composite2 are viable and are different;
2836 // this is an ambiguity.
2837 return QualType();
2838 }
2839 }
2840
2841 // Convert E1 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00002842 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00002843 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002844 if (E1Result.isInvalid())
2845 return QualType();
2846 E1 = E1Result.takeAs<Expr>();
2847
2848 // Convert E2 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00002849 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00002850 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002851 if (E2Result.isInvalid())
2852 return QualType();
2853 E2 = E2Result.takeAs<Expr>();
2854
2855 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002856 }
2857
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002858 // Check whether Composite2 is viable.
2859 InitializedEntity Entity2
2860 = InitializedEntity::InitializeTemporary(Composite2);
2861 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2862 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2863 if (!E1ToC2 || !E2ToC2)
2864 return QualType();
2865
2866 // Convert E1 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00002867 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00002868 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002869 if (E1Result.isInvalid())
2870 return QualType();
2871 E1 = E1Result.takeAs<Expr>();
2872
2873 // Convert E2 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00002874 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00002875 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002876 if (E2Result.isInvalid())
2877 return QualType();
2878 E2 = E2Result.takeAs<Expr>();
2879
2880 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002881}
Anders Carlsson165a0a02009-05-17 18:41:29 +00002882
John McCall60d7b3a2010-08-24 06:29:42 +00002883ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00002884 if (!Context.getLangOptions().CPlusPlus)
2885 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002886
Douglas Gregor51326552009-12-24 18:51:59 +00002887 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2888
Ted Kremenek6217b802009-07-29 21:53:49 +00002889 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00002890 if (!RT)
2891 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002892
Anders Carlsson0ea4dfd2010-07-16 21:18:37 +00002893 // If this is the result of a call or an Objective-C message send expression,
2894 // our source might actually be a reference, in which case we shouldn't bind.
Anders Carlsson283e4d52009-09-14 01:30:44 +00002895 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
Anders Carlsson0ea4dfd2010-07-16 21:18:37 +00002896 if (CE->getCallReturnType()->isReferenceType())
Anders Carlsson283e4d52009-09-14 01:30:44 +00002897 return Owned(E);
Anders Carlsson0ea4dfd2010-07-16 21:18:37 +00002898 } else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
2899 if (const ObjCMethodDecl *MD = ME->getMethodDecl()) {
2900 if (MD->getResultType()->isReferenceType())
2901 return Owned(E);
2902 }
Anders Carlsson283e4d52009-09-14 01:30:44 +00002903 }
John McCall86ff3082010-02-04 22:26:26 +00002904
2905 // That should be enough to guarantee that this type is complete.
2906 // If it has a trivial destructor, we can avoid the extra copy.
2907 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall507384f2010-08-12 02:40:37 +00002908 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall86ff3082010-02-04 22:26:26 +00002909 return Owned(E);
2910
Douglas Gregordb89f282010-07-01 22:47:18 +00002911 CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD));
Anders Carlsson860306e2009-05-30 21:21:49 +00002912 ExprTemporaries.push_back(Temp);
Douglas Gregordb89f282010-07-01 22:47:18 +00002913 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002914 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00002915 CheckDestructorAccess(E->getExprLoc(), Destructor,
2916 PDiag(diag::err_access_dtor_temp)
2917 << E->getType());
2918 }
Anders Carlssondef11992009-05-30 20:36:53 +00002919 // FIXME: Add the temporary to the temporaries vector.
2920 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2921}
2922
Anders Carlsson0ece4912009-12-15 20:51:39 +00002923Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002924 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002925
John McCall323ed742010-05-06 08:58:33 +00002926 // Check any implicit conversions within the expression.
2927 CheckImplicitConversions(SubExpr);
2928
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002929 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2930 assert(ExprTemporaries.size() >= FirstTemporary);
2931 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002932 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002933
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002934 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002935 &ExprTemporaries[FirstTemporary],
Anders Carlsson0ece4912009-12-15 20:51:39 +00002936 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002937 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2938 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002939
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002940 return E;
2941}
2942
John McCall60d7b3a2010-08-24 06:29:42 +00002943ExprResult
2944Sema::MaybeCreateCXXExprWithTemporaries(ExprResult SubExpr) {
Douglas Gregor90f93822009-12-22 22:17:25 +00002945 if (SubExpr.isInvalid())
2946 return ExprError();
2947
2948 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2949}
2950
Anders Carlsson5ee56e92009-12-16 02:09:40 +00002951FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2952 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2953 assert(ExprTemporaries.size() >= FirstTemporary);
2954
2955 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2956 CXXTemporary **Temporaries =
2957 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2958
2959 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2960
2961 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2962 ExprTemporaries.end());
2963
2964 return E;
2965}
2966
John McCall60d7b3a2010-08-24 06:29:42 +00002967ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00002968Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallb3d87482010-08-24 05:47:05 +00002969 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00002970 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002971 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00002972 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00002973 if (Result.isInvalid()) return ExprError();
2974 Base = Result.get();
Mike Stump1eb44332009-09-09 15:08:12 +00002975
John McCall9ae2f072010-08-23 23:25:46 +00002976 QualType BaseType = Base->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00002977 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002978 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002979 // If we have a pointer to a dependent type and are using the -> operator,
2980 // the object type is the type that the pointer points to. We might still
2981 // have enough information about that type to do something useful.
2982 if (OpKind == tok::arrow)
2983 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2984 BaseType = Ptr->getPointeeType();
2985
John McCallb3d87482010-08-24 05:47:05 +00002986 ObjectType = ParsedType::make(BaseType);
Douglas Gregord4dca082010-02-24 18:44:31 +00002987 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00002988 return Owned(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002989 }
Mike Stump1eb44332009-09-09 15:08:12 +00002990
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002991 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002992 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002993 // returned, with the original second operand.
2994 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002995 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002996 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002997 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002998 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002999
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003000 while (BaseType->isRecordType()) {
John McCall9ae2f072010-08-23 23:25:46 +00003001 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
3002 if (Result.isInvalid())
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003003 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00003004 Base = Result.get();
3005 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonde699e52009-10-13 22:55:59 +00003006 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCall9ae2f072010-08-23 23:25:46 +00003007 BaseType = Base->getType();
John McCallc4e83212009-09-30 01:01:30 +00003008 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00003009 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00003010 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00003011 for (unsigned i = 0; i < Locations.size(); i++)
3012 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00003013 return ExprError();
3014 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003015 }
Mike Stump1eb44332009-09-09 15:08:12 +00003016
Douglas Gregor31658df2009-11-20 19:58:21 +00003017 if (BaseType->isPointerType())
3018 BaseType = BaseType->getPointeeType();
3019 }
Mike Stump1eb44332009-09-09 15:08:12 +00003020
3021 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003022 // vector types or Objective-C interfaces. Just return early and let
3023 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00003024 if (!BaseType->isRecordType()) {
3025 // C++ [basic.lookup.classref]p2:
3026 // [...] If the type of the object expression is of pointer to scalar
3027 // type, the unqualified-id is looked up in the context of the complete
3028 // postfix-expression.
Douglas Gregord4dca082010-02-24 18:44:31 +00003029 //
3030 // This also indicates that we should be parsing a
3031 // pseudo-destructor-name.
John McCallb3d87482010-08-24 05:47:05 +00003032 ObjectType = ParsedType();
Douglas Gregord4dca082010-02-24 18:44:31 +00003033 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00003034 return Owned(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00003035 }
Mike Stump1eb44332009-09-09 15:08:12 +00003036
Douglas Gregor03c57052009-11-17 05:17:33 +00003037 // The object type must be complete (or dependent).
3038 if (!BaseType->isDependentType() &&
3039 RequireCompleteType(OpLoc, BaseType,
3040 PDiag(diag::err_incomplete_member_access)))
3041 return ExprError();
3042
Douglas Gregorc68afe22009-09-03 21:38:09 +00003043 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00003044 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00003045 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00003046 // type C (or of pointer to a class type C), the unqualified-id is looked
3047 // up in the scope of class C. [...]
John McCallb3d87482010-08-24 05:47:05 +00003048 ObjectType = ParsedType::make(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00003049 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003050}
3051
John McCall60d7b3a2010-08-24 06:29:42 +00003052ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003053 Expr *MemExpr) {
Douglas Gregor77549082010-02-24 21:29:12 +00003054 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCall9ae2f072010-08-23 23:25:46 +00003055 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
3056 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregor849b2432010-03-31 17:46:05 +00003057 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
Douglas Gregor77549082010-02-24 21:29:12 +00003058
3059 return ActOnCallExpr(/*Scope*/ 0,
John McCall9ae2f072010-08-23 23:25:46 +00003060 MemExpr,
Douglas Gregor77549082010-02-24 21:29:12 +00003061 /*LPLoc*/ ExpectedLParenLoc,
John McCallf312b1e2010-08-26 23:41:50 +00003062 MultiExprArg(),
Douglas Gregor77549082010-02-24 21:29:12 +00003063 /*RPLoc*/ ExpectedLParenLoc);
3064}
Douglas Gregord4dca082010-02-24 18:44:31 +00003065
John McCall60d7b3a2010-08-24 06:29:42 +00003066ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003067 SourceLocation OpLoc,
3068 tok::TokenKind OpKind,
3069 const CXXScopeSpec &SS,
Douglas Gregor26d4ac92010-02-24 23:40:28 +00003070 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003071 SourceLocation CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00003072 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003073 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003074 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003075 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
Douglas Gregorb57fb492010-02-24 22:38:50 +00003076
3077 // C++ [expr.pseudo]p2:
3078 // The left-hand side of the dot operator shall be of scalar type. The
3079 // left-hand side of the arrow operator shall be of pointer to scalar type.
3080 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00003081 QualType ObjectType = Base->getType();
Douglas Gregorb57fb492010-02-24 22:38:50 +00003082 if (OpKind == tok::arrow) {
3083 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3084 ObjectType = Ptr->getPointeeType();
John McCall9ae2f072010-08-23 23:25:46 +00003085 } else if (!Base->isTypeDependent()) {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003086 // The user wrote "p->" when she probably meant "p."; fix it.
3087 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3088 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00003089 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb57fb492010-02-24 22:38:50 +00003090 if (isSFINAEContext())
3091 return ExprError();
3092
3093 OpKind = tok::period;
3094 }
3095 }
3096
3097 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
3098 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
John McCall9ae2f072010-08-23 23:25:46 +00003099 << ObjectType << Base->getSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00003100 return ExprError();
3101 }
3102
3103 // C++ [expr.pseudo]p2:
3104 // [...] The cv-unqualified versions of the object type and of the type
3105 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003106 if (DestructedTypeInfo) {
3107 QualType DestructedType = DestructedTypeInfo->getType();
3108 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003109 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003110 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
3111 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
3112 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00003113 << ObjectType << DestructedType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003114 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003115
3116 // Recover by setting the destructed type to the object type.
3117 DestructedType = ObjectType;
3118 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
3119 DestructedTypeStart);
3120 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3121 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00003122 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003123
Douglas Gregorb57fb492010-02-24 22:38:50 +00003124 // C++ [expr.pseudo]p2:
3125 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
3126 // form
3127 //
3128 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
3129 //
3130 // shall designate the same scalar type.
3131 if (ScopeTypeInfo) {
3132 QualType ScopeType = ScopeTypeInfo->getType();
3133 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00003134 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003135
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003136 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00003137 diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00003138 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003139 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00003140
3141 ScopeType = QualType();
3142 ScopeTypeInfo = 0;
3143 }
3144 }
3145
John McCall9ae2f072010-08-23 23:25:46 +00003146 Expr *Result
3147 = new (Context) CXXPseudoDestructorExpr(Context, Base,
3148 OpKind == tok::arrow, OpLoc,
3149 SS.getScopeRep(), SS.getRange(),
3150 ScopeTypeInfo,
3151 CCLoc,
3152 TildeLoc,
3153 Destructed);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003154
Douglas Gregorb57fb492010-02-24 22:38:50 +00003155 if (HasTrailingLParen)
John McCall9ae2f072010-08-23 23:25:46 +00003156 return Owned(Result);
Douglas Gregorb57fb492010-02-24 22:38:50 +00003157
John McCall9ae2f072010-08-23 23:25:46 +00003158 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor77549082010-02-24 21:29:12 +00003159}
3160
John McCall60d7b3a2010-08-24 06:29:42 +00003161ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
Douglas Gregor77549082010-02-24 21:29:12 +00003162 SourceLocation OpLoc,
3163 tok::TokenKind OpKind,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003164 CXXScopeSpec &SS,
Douglas Gregor77549082010-02-24 21:29:12 +00003165 UnqualifiedId &FirstTypeName,
3166 SourceLocation CCLoc,
3167 SourceLocation TildeLoc,
3168 UnqualifiedId &SecondTypeName,
3169 bool HasTrailingLParen) {
3170 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3171 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3172 "Invalid first type name in pseudo-destructor");
3173 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3174 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3175 "Invalid second type name in pseudo-destructor");
3176
Douglas Gregor77549082010-02-24 21:29:12 +00003177 // C++ [expr.pseudo]p2:
3178 // The left-hand side of the dot operator shall be of scalar type. The
3179 // left-hand side of the arrow operator shall be of pointer to scalar type.
3180 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00003181 QualType ObjectType = Base->getType();
Douglas Gregor77549082010-02-24 21:29:12 +00003182 if (OpKind == tok::arrow) {
3183 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3184 ObjectType = Ptr->getPointeeType();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003185 } else if (!ObjectType->isDependentType()) {
Douglas Gregor77549082010-02-24 21:29:12 +00003186 // The user wrote "p->" when she probably meant "p."; fix it.
3187 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003188 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00003189 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor77549082010-02-24 21:29:12 +00003190 if (isSFINAEContext())
3191 return ExprError();
3192
3193 OpKind = tok::period;
3194 }
3195 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003196
3197 // Compute the object type that we should use for name lookup purposes. Only
3198 // record types and dependent types matter.
John McCallb3d87482010-08-24 05:47:05 +00003199 ParsedType ObjectTypePtrForLookup;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003200 if (!SS.isSet()) {
John McCallb3d87482010-08-24 05:47:05 +00003201 if (const Type *T = ObjectType->getAs<RecordType>())
3202 ObjectTypePtrForLookup = ParsedType::make(QualType(T, 0));
3203 else if (ObjectType->isDependentType())
3204 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003205 }
Douglas Gregor77549082010-02-24 21:29:12 +00003206
Douglas Gregorb57fb492010-02-24 22:38:50 +00003207 // Convert the name of the type being destructed (following the ~) into a
3208 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00003209 QualType DestructedType;
3210 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003211 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00003212 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
John McCallb3d87482010-08-24 05:47:05 +00003213 ParsedType T = getTypeName(*SecondTypeName.Identifier,
3214 SecondTypeName.StartLocation,
3215 S, &SS, true, ObjectTypePtrForLookup);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003216 if (!T &&
3217 ((SS.isSet() && !computeDeclContext(SS, false)) ||
3218 (!SS.isSet() && ObjectType->isDependentType()))) {
3219 // The name of the type being destroyed is a dependent name, and we
3220 // couldn't find anything useful in scope. Just store the identifier and
3221 // it's location, and we'll perform (qualified) name lookup again at
3222 // template instantiation time.
3223 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
3224 SecondTypeName.StartLocation);
3225 } else if (!T) {
Douglas Gregor77549082010-02-24 21:29:12 +00003226 Diag(SecondTypeName.StartLocation,
3227 diag::err_pseudo_dtor_destructor_non_type)
3228 << SecondTypeName.Identifier << ObjectType;
3229 if (isSFINAEContext())
3230 return ExprError();
3231
3232 // Recover by assuming we had the right type all along.
3233 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003234 } else
Douglas Gregor77549082010-02-24 21:29:12 +00003235 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003236 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003237 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00003238 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003239 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3240 TemplateId->getTemplateArgs(),
3241 TemplateId->NumArgs);
John McCall2b5289b2010-08-23 07:28:44 +00003242 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003243 TemplateId->TemplateNameLoc,
3244 TemplateId->LAngleLoc,
3245 TemplateArgsPtr,
3246 TemplateId->RAngleLoc);
3247 if (T.isInvalid() || !T.get()) {
3248 // Recover by assuming we had the right type all along.
3249 DestructedType = ObjectType;
3250 } else
3251 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003252 }
3253
Douglas Gregorb57fb492010-02-24 22:38:50 +00003254 // If we've performed some kind of recovery, (re-)build the type source
3255 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003256 if (!DestructedType.isNull()) {
3257 if (!DestructedTypeInfo)
3258 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003259 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003260 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3261 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00003262
3263 // Convert the name of the scope type (the type prior to '::') into a type.
3264 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00003265 QualType ScopeType;
3266 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3267 FirstTypeName.Identifier) {
3268 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
John McCallb3d87482010-08-24 05:47:05 +00003269 ParsedType T = getTypeName(*FirstTypeName.Identifier,
3270 FirstTypeName.StartLocation,
3271 S, &SS, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00003272 if (!T) {
3273 Diag(FirstTypeName.StartLocation,
3274 diag::err_pseudo_dtor_destructor_non_type)
3275 << FirstTypeName.Identifier << ObjectType;
Douglas Gregor77549082010-02-24 21:29:12 +00003276
Douglas Gregorb57fb492010-02-24 22:38:50 +00003277 if (isSFINAEContext())
3278 return ExprError();
3279
3280 // Just drop this type. It's unnecessary anyway.
3281 ScopeType = QualType();
3282 } else
3283 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003284 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003285 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00003286 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003287 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3288 TemplateId->getTemplateArgs(),
3289 TemplateId->NumArgs);
John McCall2b5289b2010-08-23 07:28:44 +00003290 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003291 TemplateId->TemplateNameLoc,
3292 TemplateId->LAngleLoc,
3293 TemplateArgsPtr,
3294 TemplateId->RAngleLoc);
3295 if (T.isInvalid() || !T.get()) {
3296 // Recover by dropping this type.
3297 ScopeType = QualType();
3298 } else
3299 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003300 }
3301 }
Douglas Gregorb4a418f2010-02-24 23:02:30 +00003302
3303 if (!ScopeType.isNull() && !ScopeTypeInfo)
3304 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
3305 FirstTypeName.StartLocation);
3306
3307
John McCall9ae2f072010-08-23 23:25:46 +00003308 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00003309 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003310 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00003311}
3312
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003313CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
John McCall6bb80172010-03-30 21:47:33 +00003314 NamedDecl *FoundDecl,
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003315 CXXMethodDecl *Method) {
John McCall6bb80172010-03-30 21:47:33 +00003316 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
3317 FoundDecl, Method))
Eli Friedman772fffa2009-12-09 04:53:56 +00003318 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
3319
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003320 MemberExpr *ME =
Abramo Bagnara25777432010-08-11 22:01:17 +00003321 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003322 SourceLocation(), Method->getType());
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003323 QualType ResultType = Method->getCallResultType();
Douglas Gregor7edfb692009-11-23 12:27:39 +00003324 MarkDeclarationReferenced(Exp->getLocStart(), Method);
3325 CXXMemberCallExpr *CE =
3326 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
3327 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003328 return CE;
3329}
3330
Sebastian Redl2e156222010-09-10 20:55:43 +00003331ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
3332 SourceLocation RParen) {
Sebastian Redl2e156222010-09-10 20:55:43 +00003333 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
3334 Operand->CanThrow(Context),
3335 KeyLoc, RParen));
3336}
3337
3338ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
3339 Expr *Operand, SourceLocation RParen) {
3340 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl02bc21a2010-09-10 20:55:37 +00003341}
3342
John McCall60d7b3a2010-08-24 06:29:42 +00003343ExprResult Sema::ActOnFinishFullExpr(Expr *FullExpr) {
John McCall9ae2f072010-08-23 23:25:46 +00003344 if (!FullExpr) return ExprError();
3345 return MaybeCreateCXXExprWithTemporaries(FullExpr);
Anders Carlsson165a0a02009-05-17 18:41:29 +00003346}