blob: 70e9a97fc6736ee1e93676915c09b41812204097 [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
Eli Friedman98efb9f2010-10-12 20:32:36 +0000512 // If a pointer is thrown, the referenced object will not be destroyed.
513 if (isPointer)
514 return false;
515
Eli Friedman5ed9b932010-06-03 20:39:03 +0000516 // If the class has a non-trivial destructor, we must be able to call it.
517 if (RD->hasTrivialDestructor())
518 return false;
519
Douglas Gregor1d110e02010-07-01 14:13:13 +0000520 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +0000521 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman5ed9b932010-06-03 20:39:03 +0000522 if (!Destructor)
523 return false;
524
525 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
526 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregored8abf12010-07-08 06:14:04 +0000527 PDiag(diag::err_access_dtor_exception) << Ty);
Sebastian Redl972041f2009-04-27 20:27:31 +0000528 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000529}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000530
John McCall60d7b3a2010-08-24 06:29:42 +0000531ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000532 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
533 /// is a non-lvalue expression whose value is the address of the object for
534 /// which the function is called.
535
John McCallea1471e2010-05-20 01:18:31 +0000536 DeclContext *DC = getFunctionLevelDeclContext();
537 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000538 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000539 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000540 MD->getThisType(Context),
541 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000542
Sebastian Redlf53597f2009-03-15 17:47:39 +0000543 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000544}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000545
John McCall60d7b3a2010-08-24 06:29:42 +0000546ExprResult
Douglas Gregorab6677e2010-09-08 00:15:04 +0000547Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000548 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000549 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000550 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000551 if (!TypeRep)
552 return ExprError();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000553
John McCall9d125032010-01-15 18:39:57 +0000554 TypeSourceInfo *TInfo;
555 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
556 if (!TInfo)
557 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregorab6677e2010-09-08 00:15:04 +0000558
559 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
560}
561
562/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
563/// Can be interpreted either as function-style casting ("int(x)")
564/// or class type construction ("ClassType(x,y,z)")
565/// or creation of a value-initialized type ("int()").
566ExprResult
567Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
568 SourceLocation LParenLoc,
569 MultiExprArg exprs,
570 SourceLocation RParenLoc) {
571 QualType Ty = TInfo->getType();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000572 unsigned NumExprs = exprs.size();
573 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000574 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000575 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
576
Sebastian Redlf53597f2009-03-15 17:47:39 +0000577 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000578 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000579 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000580
Douglas Gregorab6677e2010-09-08 00:15:04 +0000581 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000582 LParenLoc,
583 Exprs, NumExprs,
584 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000585 }
586
Anders Carlssonbb60a502009-08-27 03:53:50 +0000587 if (Ty->isArrayType())
588 return ExprError(Diag(TyBeginLoc,
589 diag::err_value_init_for_array_type) << FullRange);
590 if (!Ty->isVoidType() &&
591 RequireCompleteType(TyBeginLoc, Ty,
592 PDiag(diag::err_invalid_incomplete_type_use)
593 << FullRange))
594 return ExprError();
Fariborz Jahanianf071e9b2009-10-23 21:01:39 +0000595
Anders Carlssonbb60a502009-08-27 03:53:50 +0000596 if (RequireNonAbstractType(TyBeginLoc, Ty,
597 diag::err_allocation_of_abstract_type))
598 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000599
600
Douglas Gregor506ae412009-01-16 18:33:17 +0000601 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000602 // If the expression list is a single expression, the type conversion
603 // expression is equivalent (in definedness, and if defined in meaning) to the
604 // corresponding cast expression.
605 //
606 if (NumExprs == 1) {
John McCalldaa8e4e2010-11-15 09:13:47 +0000607 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +0000608 CXXCastPath BasePath;
Douglas Gregorab6677e2010-09-08 00:15:04 +0000609 if (CheckCastTypes(TInfo->getTypeLoc().getSourceRange(), Ty, Exprs[0],
610 Kind, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000611 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000612 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000613
614 exprs.release();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000615
John McCallf871d0c2010-08-07 06:22:56 +0000616 return Owned(CXXFunctionalCastExpr::Create(Context,
Douglas Gregorab6677e2010-09-08 00:15:04 +0000617 Ty.getNonLValueExprType(Context),
John McCallf871d0c2010-08-07 06:22:56 +0000618 TInfo, TyBeginLoc, Kind,
619 Exprs[0], &BasePath,
620 RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000621 }
622
Douglas Gregor19311e72010-09-08 21:40:08 +0000623 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
624 InitializationKind Kind
625 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
626 LParenLoc, RParenLoc)
627 : InitializationKind::CreateValue(TyBeginLoc,
628 LParenLoc, RParenLoc);
629 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
630 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redlf53597f2009-03-15 17:47:39 +0000631
Douglas Gregor19311e72010-09-08 21:40:08 +0000632 // FIXME: Improve AST representation?
633 return move(Result);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000634}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000635
636
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000637/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
638/// @code new (memory) int[size][4] @endcode
639/// or
640/// @code ::new Foo(23, "hello") @endcode
641/// For the interpretation of this heap of arguments, consult the base version.
John McCall60d7b3a2010-08-24 06:29:42 +0000642ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000643Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000644 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000645 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000646 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000647 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000648 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000649 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000650 // If the specified type is an array, unwrap it and save the expression.
651 if (D.getNumTypeObjects() > 0 &&
652 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
653 DeclaratorChunk &Chunk = D.getTypeObject(0);
654 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000655 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
656 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000657 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000658 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
659 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000660
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000661 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000662 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000663 }
664
Douglas Gregor043cad22009-09-11 00:18:58 +0000665 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000666 if (ArraySize) {
667 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000668 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
669 break;
670
671 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
672 if (Expr *NumElts = (Expr *)Array.NumElts) {
673 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
674 !NumElts->isIntegerConstantExpr(Context)) {
675 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
676 << NumElts->getSourceRange();
677 return ExprError();
678 }
679 }
680 }
681 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000682
John McCallbf1a0282010-06-04 23:28:52 +0000683 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
684 QualType AllocType = TInfo->getType();
Chris Lattnereaaebc72009-04-25 08:06:05 +0000685 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000686 return ExprError();
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000687
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000688 if (!TInfo)
689 TInfo = Context.getTrivialTypeSourceInfo(AllocType);
690
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000691 SourceRange R = TInfo->getTypeLoc().getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000692 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000693 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000694 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000695 PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000696 TypeIdParens,
Mike Stump1eb44332009-09-09 15:08:12 +0000697 AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000698 TInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000699 ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000700 ConstructorLParen,
701 move(ConstructorArgs),
702 ConstructorRParen);
703}
704
John McCall60d7b3a2010-08-24 06:29:42 +0000705ExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000706Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
707 SourceLocation PlacementLParen,
708 MultiExprArg PlacementArgs,
709 SourceLocation PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000710 SourceRange TypeIdParens,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000711 QualType AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000712 TypeSourceInfo *AllocTypeInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000713 Expr *ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000714 SourceLocation ConstructorLParen,
715 MultiExprArg ConstructorArgs,
716 SourceLocation ConstructorRParen) {
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000717 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000718
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000719 // Per C++0x [expr.new]p5, the type being constructed may be a
720 // typedef of an array type.
John McCall9ae2f072010-08-23 23:25:46 +0000721 if (!ArraySize) {
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000722 if (const ConstantArrayType *Array
723 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000724 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
725 Context.getSizeType(),
726 TypeRange.getEnd());
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000727 AllocType = Array->getElementType();
728 }
729 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000730
Douglas Gregora0750762010-10-06 16:00:31 +0000731 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
732 return ExprError();
733
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000734 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000735
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000736 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
737 // or enumeration type with a non-negative value."
Sebastian Redl28507842009-02-26 14:39:58 +0000738 if (ArraySize && !ArraySize->isTypeDependent()) {
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000739
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000740 QualType SizeType = ArraySize->getType();
Douglas Gregorc30614b2010-06-29 23:17:37 +0000741
John McCall60d7b3a2010-08-24 06:29:42 +0000742 ExprResult ConvertedSize
John McCall9ae2f072010-08-23 23:25:46 +0000743 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000744 PDiag(diag::err_array_size_not_integral),
745 PDiag(diag::err_array_size_incomplete_type)
746 << ArraySize->getSourceRange(),
747 PDiag(diag::err_array_size_explicit_conversion),
748 PDiag(diag::note_array_size_conversion),
749 PDiag(diag::err_array_size_ambiguous_conversion),
750 PDiag(diag::note_array_size_conversion),
751 PDiag(getLangOptions().CPlusPlus0x? 0
752 : diag::ext_array_size_conversion));
753 if (ConvertedSize.isInvalid())
754 return ExprError();
755
John McCall9ae2f072010-08-23 23:25:46 +0000756 ArraySize = ConvertedSize.take();
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000757 SizeType = ArraySize->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000758 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000759 return ExprError();
760
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000761 // Let's see if this is a constant < 0. If so, we reject it out of hand.
762 // We don't care about special rules, so we tell the machinery it's not
763 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000764 if (!ArraySize->isValueDependent()) {
765 llvm::APSInt Value;
766 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
767 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000768 llvm::APInt::getNullValue(Value.getBitWidth()),
769 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000770 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +0000771 diag::err_typecheck_negative_array_size)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000772 << ArraySize->getSourceRange());
Douglas Gregor2767ce22010-08-18 00:39:00 +0000773
774 if (!AllocType->isDependentType()) {
775 unsigned ActiveSizeBits
776 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
777 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
778 Diag(ArraySize->getSourceRange().getBegin(),
779 diag::err_array_too_large)
780 << Value.toString(10)
781 << ArraySize->getSourceRange();
782 return ExprError();
783 }
784 }
Douglas Gregor4bd40312010-07-13 15:54:32 +0000785 } else if (TypeIdParens.isValid()) {
786 // Can't have dynamic array size when the type-id is in parentheses.
787 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
788 << ArraySize->getSourceRange()
789 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
790 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
791
792 TypeIdParens = SourceRange();
Sebastian Redl28507842009-02-26 14:39:58 +0000793 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000794 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000795
Eli Friedman73c39ab2009-10-20 08:27:19 +0000796 ImpCastExprToType(ArraySize, Context.getSizeType(),
John McCall2de56d12010-08-25 11:45:40 +0000797 CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000798 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000799
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000800 FunctionDecl *OperatorNew = 0;
801 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000802 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
803 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000804
Sebastian Redl28507842009-02-26 14:39:58 +0000805 if (!AllocType->isDependentType() &&
806 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
807 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000808 SourceRange(PlacementLParen, PlacementRParen),
809 UseGlobal, AllocType, ArraySize, PlaceArgs,
810 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000811 return ExprError();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000812 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000813 if (OperatorNew) {
814 // Add default arguments, if any.
815 const FunctionProtoType *Proto =
816 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000817 VariadicCallType CallType =
818 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Anders Carlsson28e94832010-05-03 02:07:56 +0000819
820 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
821 Proto, 1, PlaceArgs, NumPlaceArgs,
822 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000823 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000824
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000825 NumPlaceArgs = AllPlaceArgs.size();
826 if (NumPlaceArgs > 0)
827 PlaceArgs = &AllPlaceArgs[0];
828 }
829
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000830 bool Init = ConstructorLParen.isValid();
831 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000832 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000833 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
834 unsigned NumConsArgs = ConstructorArgs.size();
John McCallca0408f2010-08-23 06:44:23 +0000835 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000836
Anders Carlsson48c95012010-05-03 15:45:23 +0000837 // Array 'new' can't have any initializers.
Anders Carlsson55cbd6e2010-05-16 16:24:20 +0000838 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlsson48c95012010-05-03 15:45:23 +0000839 SourceRange InitRange(ConsArgs[0]->getLocStart(),
840 ConsArgs[NumConsArgs - 1]->getLocEnd());
841
842 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
843 return ExprError();
844 }
845
Douglas Gregor99a2e602009-12-16 01:38:02 +0000846 if (!AllocType->isDependentType() &&
847 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
848 // C++0x [expr.new]p15:
849 // A new-expression that creates an object of type T initializes that
850 // object as follows:
851 InitializationKind Kind
852 // - If the new-initializer is omitted, the object is default-
853 // initialized (8.5); if no initialization is performed,
854 // the object has indeterminate value
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000855 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
Douglas Gregor99a2e602009-12-16 01:38:02 +0000856 // - Otherwise, the new-initializer is interpreted according to the
857 // initialization rules of 8.5 for direct-initialization.
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000858 : InitializationKind::CreateDirect(TypeRange.getBegin(),
Douglas Gregor99a2e602009-12-16 01:38:02 +0000859 ConstructorLParen,
860 ConstructorRParen);
861
Douglas Gregor99a2e602009-12-16 01:38:02 +0000862 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +0000863 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000864 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
John McCall60d7b3a2010-08-24 06:29:42 +0000865 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor99a2e602009-12-16 01:38:02 +0000866 move(ConstructorArgs));
867 if (FullInit.isInvalid())
868 return ExprError();
869
870 // FullInit is our initializer; walk through it to determine if it's a
871 // constructor call, which CXXNewExpr handles directly.
872 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
873 if (CXXBindTemporaryExpr *Binder
874 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
875 FullInitExpr = Binder->getSubExpr();
876 if (CXXConstructExpr *Construct
877 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
878 Constructor = Construct->getConstructor();
879 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
880 AEnd = Construct->arg_end();
881 A != AEnd; ++A)
John McCall3fa5cae2010-10-26 07:05:15 +0000882 ConvertedConstructorArgs.push_back(*A);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000883 } else {
884 // Take the converted initializer.
885 ConvertedConstructorArgs.push_back(FullInit.release());
886 }
887 } else {
888 // No initialization required.
889 }
890
891 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +0000892 NumConsArgs = ConvertedConstructorArgs.size();
893 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000894 }
Douglas Gregor99a2e602009-12-16 01:38:02 +0000895
Douglas Gregor6d908702010-02-26 05:06:18 +0000896 // Mark the new and delete operators as referenced.
897 if (OperatorNew)
898 MarkDeclarationReferenced(StartLoc, OperatorNew);
899 if (OperatorDelete)
900 MarkDeclarationReferenced(StartLoc, OperatorDelete);
901
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000902 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000903
Sebastian Redlf53597f2009-03-15 17:47:39 +0000904 PlacementArgs.release();
905 ConstructorArgs.release();
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000906
Ted Kremenekad7fe862010-02-11 22:51:03 +0000907 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000908 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenekad7fe862010-02-11 22:51:03 +0000909 ArraySize, Constructor, Init,
910 ConsArgs, NumConsArgs, OperatorDelete,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000911 ResultType, AllocTypeInfo,
912 StartLoc,
Ted Kremenekad7fe862010-02-11 22:51:03 +0000913 Init ? ConstructorRParen :
Chandler Carruth428edaf2010-10-25 08:47:36 +0000914 TypeRange.getEnd(),
915 ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000916}
917
918/// CheckAllocatedType - Checks that a type is suitable as the allocated type
919/// in a new-expression.
920/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000921bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000922 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000923 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
924 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000925 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000926 return Diag(Loc, diag::err_bad_new_type)
927 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000928 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000929 return Diag(Loc, diag::err_bad_new_type)
930 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000931 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000932 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000933 PDiag(diag::err_new_incomplete_type)
934 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000935 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000936 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000937 diag::err_allocation_of_abstract_type))
938 return true;
Douglas Gregora0750762010-10-06 16:00:31 +0000939 else if (AllocType->isVariablyModifiedType())
940 return Diag(Loc, diag::err_variably_modified_new_type)
941 << AllocType;
942
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000943 return false;
944}
945
Douglas Gregor6d908702010-02-26 05:06:18 +0000946/// \brief Determine whether the given function is a non-placement
947/// deallocation function.
948static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
949 if (FD->isInvalidDecl())
950 return false;
951
952 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
953 return Method->isUsualDeallocationFunction();
954
955 return ((FD->getOverloadedOperator() == OO_Delete ||
956 FD->getOverloadedOperator() == OO_Array_Delete) &&
957 FD->getNumParams() == 1);
958}
959
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000960/// FindAllocationFunctions - Finds the overloads of operator new and delete
961/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000962bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
963 bool UseGlobal, QualType AllocType,
964 bool IsArray, Expr **PlaceArgs,
965 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000966 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000967 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000968 // --- Choosing an allocation function ---
969 // C++ 5.3.4p8 - 14 & 18
970 // 1) If UseGlobal is true, only look in the global scope. Else, also look
971 // in the scope of the allocated class.
972 // 2) If an array size is given, look for operator new[], else look for
973 // operator new.
974 // 3) The first argument is always size_t. Append the arguments from the
975 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000976
977 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
978 // We don't care about the actual value of this argument.
979 // FIXME: Should the Sema create the expression and embed it in the syntax
980 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000981 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Anders Carlssond67c4c32009-08-16 20:29:29 +0000982 Context.Target.getPointerWidth(0)),
983 Context.getSizeType(),
984 SourceLocation());
985 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000986 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
987
Douglas Gregor6d908702010-02-26 05:06:18 +0000988 // C++ [expr.new]p8:
989 // If the allocated type is a non-array type, the allocation
990 // function’s name is operator new and the deallocation function’s
991 // name is operator delete. If the allocated type is an array
992 // type, the allocation function’s name is operator new[] and the
993 // deallocation function’s name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000994 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
995 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +0000996 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
997 IsArray ? OO_Array_Delete : OO_Delete);
998
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +0000999 QualType AllocElemType = Context.getBaseElementType(AllocType);
1000
1001 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +00001002 CXXRecordDecl *Record
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001003 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
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(), Record, /*AllowMissing=*/true,
1006 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001007 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001008 }
1009 if (!OperatorNew) {
1010 // Didn't find a member overload. Look for a global one.
1011 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +00001012 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +00001013 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001014 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1015 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001016 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001017 }
1018
John McCall9c82afc2010-04-20 02:18:25 +00001019 // We don't need an operator delete if we're running under
1020 // -fno-exceptions.
1021 if (!getLangOptions().Exceptions) {
1022 OperatorDelete = 0;
1023 return false;
1024 }
1025
Anders Carlssond9583892009-05-31 20:26:12 +00001026 // FindAllocationOverload can change the passed in arguments, so we need to
1027 // copy them back.
1028 if (NumPlaceArgs > 0)
1029 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001030
Douglas Gregor6d908702010-02-26 05:06:18 +00001031 // C++ [expr.new]p19:
1032 //
1033 // If the new-expression begins with a unary :: operator, the
1034 // deallocation function’s name is looked up in the global
1035 // scope. Otherwise, if the allocated type is a class type T or an
1036 // array thereof, the deallocation function’s name is looked up in
1037 // the scope of T. If this lookup fails to find the name, or if
1038 // the allocated type is not a class type or array thereof, the
1039 // deallocation function’s name is looked up in the global scope.
1040 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001041 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001042 CXXRecordDecl *RD
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001043 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6d908702010-02-26 05:06:18 +00001044 LookupQualifiedName(FoundDelete, RD);
1045 }
John McCall90c8c572010-03-18 08:19:33 +00001046 if (FoundDelete.isAmbiguous())
1047 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +00001048
1049 if (FoundDelete.empty()) {
1050 DeclareGlobalNewDelete();
1051 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1052 }
1053
1054 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +00001055
1056 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1057
John McCalledeb6c92010-09-14 21:34:24 +00001058 // Whether we're looking for a placement operator delete is dictated
1059 // by whether we selected a placement operator new, not by whether
1060 // we had explicit placement arguments. This matters for things like
1061 // struct A { void *operator new(size_t, int = 0); ... };
1062 // A *a = new A()
1063 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1064
1065 if (isPlacementNew) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001066 // C++ [expr.new]p20:
1067 // A declaration of a placement deallocation function matches the
1068 // declaration of a placement allocation function if it has the
1069 // same number of parameters and, after parameter transformations
1070 // (8.3.5), all parameter types except the first are
1071 // identical. [...]
1072 //
1073 // To perform this comparison, we compute the function type that
1074 // the deallocation function should have, and use that type both
1075 // for template argument deduction and for comparison purposes.
1076 QualType ExpectedFunctionType;
1077 {
1078 const FunctionProtoType *Proto
1079 = OperatorNew->getType()->getAs<FunctionProtoType>();
1080 llvm::SmallVector<QualType, 4> ArgTypes;
1081 ArgTypes.push_back(Context.VoidPtrTy);
1082 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1083 ArgTypes.push_back(Proto->getArgType(I));
1084
1085 ExpectedFunctionType
1086 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
1087 ArgTypes.size(),
1088 Proto->isVariadic(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001089 0, false, false, 0, 0,
1090 FunctionType::ExtInfo());
Douglas Gregor6d908702010-02-26 05:06:18 +00001091 }
1092
1093 for (LookupResult::iterator D = FoundDelete.begin(),
1094 DEnd = FoundDelete.end();
1095 D != DEnd; ++D) {
1096 FunctionDecl *Fn = 0;
1097 if (FunctionTemplateDecl *FnTmpl
1098 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1099 // Perform template argument deduction to try to match the
1100 // expected function type.
1101 TemplateDeductionInfo Info(Context, StartLoc);
1102 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1103 continue;
1104 } else
1105 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1106
1107 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001108 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001109 }
1110 } else {
1111 // C++ [expr.new]p20:
1112 // [...] Any non-placement deallocation function matches a
1113 // non-placement allocation function. [...]
1114 for (LookupResult::iterator D = FoundDelete.begin(),
1115 DEnd = FoundDelete.end();
1116 D != DEnd; ++D) {
1117 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1118 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001119 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001120 }
1121 }
1122
1123 // C++ [expr.new]p20:
1124 // [...] If the lookup finds a single matching deallocation
1125 // function, that function will be called; otherwise, no
1126 // deallocation function will be called.
1127 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001128 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001129
1130 // C++0x [expr.new]p20:
1131 // If the lookup finds the two-parameter form of a usual
1132 // deallocation function (3.7.4.2) and that function, considered
1133 // as a placement deallocation function, would have been
1134 // selected as a match for the allocation function, the program
1135 // is ill-formed.
1136 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1137 isNonPlacementDeallocationFunction(OperatorDelete)) {
1138 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1139 << SourceRange(PlaceArgs[0]->getLocStart(),
1140 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1141 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1142 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001143 } else {
1144 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001145 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001146 }
1147 }
1148
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001149 return false;
1150}
1151
Sebastian Redl7f662392008-12-04 22:20:51 +00001152/// FindAllocationOverload - Find an fitting overload for the allocation
1153/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001154bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1155 DeclarationName Name, Expr** Args,
1156 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +00001157 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001158 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1159 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001160 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001161 if (AllowMissing)
1162 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001163 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001164 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001165 }
1166
John McCall90c8c572010-03-18 08:19:33 +00001167 if (R.isAmbiguous())
1168 return true;
1169
1170 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001171
John McCall5769d612010-02-08 23:07:23 +00001172 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001173 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1174 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001175 // Even member operator new/delete are implicitly treated as
1176 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001177 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001178
John McCall9aa472c2010-03-19 07:35:19 +00001179 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1180 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001181 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1182 Candidates,
1183 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001184 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001185 }
1186
John McCall9aa472c2010-03-19 07:35:19 +00001187 FunctionDecl *Fn = cast<FunctionDecl>(D);
1188 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001189 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001190 }
1191
1192 // Do the resolution.
1193 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00001194 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001195 case OR_Success: {
1196 // Got one!
1197 FunctionDecl *FnDecl = Best->Function;
1198 // The first argument is size_t, and the first parameter must be size_t,
1199 // too. This is checked on declaration and can be assumed. (It can't be
1200 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001201 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001202 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1203 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
John McCall60d7b3a2010-08-24 06:29:42 +00001204 ExprResult Result
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001205 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001206 Context,
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001207 FnDecl->getParamDecl(i)),
1208 SourceLocation(),
John McCall3fa5cae2010-10-26 07:05:15 +00001209 Owned(Args[i]));
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001210 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001211 return true;
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001212
1213 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001214 }
1215 Operator = FnDecl;
John McCall9aa472c2010-03-19 07:35:19 +00001216 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001217 return false;
1218 }
1219
1220 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +00001221 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001222 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001223 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001224 return true;
1225
1226 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +00001227 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +00001228 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001229 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001230 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001231
1232 case OR_Deleted:
1233 Diag(StartLoc, diag::err_ovl_deleted_call)
1234 << Best->Function->isDeleted()
1235 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001236 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001237 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001238 }
1239 assert(false && "Unreachable, bad result from BestViableFunction");
1240 return true;
1241}
1242
1243
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001244/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1245/// delete. These are:
1246/// @code
1247/// void* operator new(std::size_t) throw(std::bad_alloc);
1248/// void* operator new[](std::size_t) throw(std::bad_alloc);
1249/// void operator delete(void *) throw();
1250/// void operator delete[](void *) throw();
1251/// @endcode
1252/// Note that the placement and nothrow forms of new are *not* implicitly
1253/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001254void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001255 if (GlobalNewDeleteDeclared)
1256 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001257
1258 // C++ [basic.std.dynamic]p2:
1259 // [...] The following allocation and deallocation functions (18.4) are
1260 // implicitly declared in global scope in each translation unit of a
1261 // program
1262 //
1263 // void* operator new(std::size_t) throw(std::bad_alloc);
1264 // void* operator new[](std::size_t) throw(std::bad_alloc);
1265 // void operator delete(void*) throw();
1266 // void operator delete[](void*) throw();
1267 //
1268 // These implicit declarations introduce only the function names operator
1269 // new, operator new[], operator delete, operator delete[].
1270 //
1271 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1272 // "std" or "bad_alloc" as necessary to form the exception specification.
1273 // However, we do not make these implicit declarations visible to name
1274 // lookup.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001275 if (!StdBadAlloc) {
1276 // The "std::bad_alloc" class has not yet been declared, so build it
1277 // implicitly.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001278 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00001279 getOrCreateStdNamespace(),
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001280 SourceLocation(),
1281 &PP.getIdentifierTable().get("bad_alloc"),
1282 SourceLocation(), 0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001283 getStdBadAlloc()->setImplicit(true);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001284 }
1285
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001286 GlobalNewDeleteDeclared = true;
1287
1288 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1289 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001290 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001291
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001292 DeclareGlobalAllocationFunction(
1293 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001294 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001295 DeclareGlobalAllocationFunction(
1296 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001297 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001298 DeclareGlobalAllocationFunction(
1299 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1300 Context.VoidTy, VoidPtr);
1301 DeclareGlobalAllocationFunction(
1302 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1303 Context.VoidTy, VoidPtr);
1304}
1305
1306/// DeclareGlobalAllocationFunction - Declares a single implicit global
1307/// allocation function if it doesn't already exist.
1308void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001309 QualType Return, QualType Argument,
1310 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001311 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1312
1313 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001314 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001315 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001316 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001317 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001318 // Only look at non-template functions, as it is the predefined,
1319 // non-templated allocation function we are trying to declare here.
1320 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1321 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001322 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001323 Func->getParamDecl(0)->getType().getUnqualifiedType());
1324 // FIXME: Do we need to check for default arguments here?
Douglas Gregor7b868622010-08-18 15:06:25 +00001325 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1326 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00001327 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001328 return;
Douglas Gregor7b868622010-08-18 15:06:25 +00001329 }
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001330 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001331 }
1332 }
1333
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001334 QualType BadAllocType;
1335 bool HasBadAllocExceptionSpec
1336 = (Name.getCXXOverloadedOperator() == OO_New ||
1337 Name.getCXXOverloadedOperator() == OO_Array_New);
1338 if (HasBadAllocExceptionSpec) {
1339 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001340 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001341 }
1342
1343 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1344 true, false,
1345 HasBadAllocExceptionSpec? 1 : 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00001346 &BadAllocType,
1347 FunctionType::ExtInfo());
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001348 FunctionDecl *Alloc =
1349 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCalld931b082010-08-26 03:08:43 +00001350 FnType, /*TInfo=*/0, SC_None,
1351 SC_None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001352 Alloc->setImplicit();
Nuno Lopesfc284482009-12-16 16:59:22 +00001353
1354 if (AddMallocAttr)
Sean Huntcf807c42010-08-18 23:23:40 +00001355 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Nuno Lopesfc284482009-12-16 16:59:22 +00001356
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001357 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00001358 0, Argument, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00001359 SC_None,
1360 SC_None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00001361 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001362
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001363 // FIXME: Also add this declaration to the IdentifierResolver, but
1364 // make sure it is at the end of the chain to coincide with the
1365 // global scope.
John McCall5f1e0942010-08-24 08:50:51 +00001366 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001367}
1368
Anders Carlsson78f74552009-11-15 18:45:20 +00001369bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1370 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00001371 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001372 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001373 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001374 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +00001375
John McCalla24dc2e2009-11-17 02:14:36 +00001376 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001377 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001378
Chandler Carruth23893242010-06-28 00:30:51 +00001379 Found.suppressDiagnostics();
1380
John McCall046a7462010-08-04 00:31:26 +00001381 llvm::SmallVector<DeclAccessPair,4> Matches;
Anders Carlsson78f74552009-11-15 18:45:20 +00001382 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1383 F != FEnd; ++F) {
Chandler Carruth09556fd2010-08-08 07:04:00 +00001384 NamedDecl *ND = (*F)->getUnderlyingDecl();
1385
1386 // Ignore template operator delete members from the check for a usual
1387 // deallocation function.
1388 if (isa<FunctionTemplateDecl>(ND))
1389 continue;
1390
1391 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall046a7462010-08-04 00:31:26 +00001392 Matches.push_back(F.getPair());
1393 }
1394
1395 // There's exactly one suitable operator; pick it.
1396 if (Matches.size() == 1) {
1397 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
1398 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1399 Matches[0]);
1400 return false;
1401
1402 // We found multiple suitable operators; complain about the ambiguity.
1403 } else if (!Matches.empty()) {
1404 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1405 << Name << RD;
1406
1407 for (llvm::SmallVectorImpl<DeclAccessPair>::iterator
1408 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1409 Diag((*F)->getUnderlyingDecl()->getLocation(),
1410 diag::note_member_declared_here) << Name;
1411 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001412 }
1413
1414 // We did find operator delete/operator delete[] declarations, but
1415 // none of them were suitable.
1416 if (!Found.empty()) {
1417 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1418 << Name << RD;
1419
1420 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
John McCall046a7462010-08-04 00:31:26 +00001421 F != FEnd; ++F)
1422 Diag((*F)->getUnderlyingDecl()->getLocation(),
1423 diag::note_member_declared_here) << Name;
Anders Carlsson78f74552009-11-15 18:45:20 +00001424
1425 return true;
1426 }
1427
1428 // Look for a global declaration.
1429 DeclareGlobalNewDelete();
1430 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1431
1432 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1433 Expr* DeallocArgs[1];
1434 DeallocArgs[0] = &Null;
1435 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1436 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1437 Operator))
1438 return true;
1439
1440 assert(Operator && "Did not find a deallocation function!");
1441 return false;
1442}
1443
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001444/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1445/// @code ::delete ptr; @endcode
1446/// or
1447/// @code delete [] ptr; @endcode
John McCall60d7b3a2010-08-24 06:29:42 +00001448ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001449Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John McCall9ae2f072010-08-23 23:25:46 +00001450 bool ArrayForm, Expr *Ex) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001451 // C++ [expr.delete]p1:
1452 // The operand shall have a pointer type, or a class type having a single
1453 // conversion function to a pointer type. The result has type void.
1454 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001455 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1456
Anders Carlssond67c4c32009-08-16 20:29:29 +00001457 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001458 bool ArrayFormAsWritten = ArrayForm;
Mike Stump1eb44332009-09-09 15:08:12 +00001459
Sebastian Redl28507842009-02-26 14:39:58 +00001460 if (!Ex->isTypeDependent()) {
1461 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001462
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001463 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor254a9422010-07-29 14:44:35 +00001464 if (RequireCompleteType(StartLoc, Type,
1465 PDiag(diag::err_delete_incomplete_class_type)))
1466 return ExprError();
1467
John McCall32daa422010-03-31 01:36:47 +00001468 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1469
Fariborz Jahanian53462782009-09-11 21:44:33 +00001470 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCall32daa422010-03-31 01:36:47 +00001471 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001472 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001473 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001474 NamedDecl *D = I.getDecl();
1475 if (isa<UsingShadowDecl>(D))
1476 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1477
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001478 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001479 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001480 continue;
1481
John McCall32daa422010-03-31 01:36:47 +00001482 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001483
1484 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1485 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedman13578692010-08-05 02:49:48 +00001486 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001487 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001488 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001489 if (ObjectPtrConversions.size() == 1) {
1490 // We have a single conversion to a pointer-to-object type. Perform
1491 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001492 // TODO: don't redo the conversion calculation.
John McCall32daa422010-03-31 01:36:47 +00001493 if (!PerformImplicitConversion(Ex,
1494 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +00001495 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001496 Type = Ex->getType();
1497 }
1498 }
1499 else if (ObjectPtrConversions.size() > 1) {
1500 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1501 << Type << Ex->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001502 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1503 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001504 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001505 }
Sebastian Redl28507842009-02-26 14:39:58 +00001506 }
1507
Sebastian Redlf53597f2009-03-15 17:47:39 +00001508 if (!Type->isPointerType())
1509 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1510 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001511
Ted Kremenek6217b802009-07-29 21:53:49 +00001512 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor94a61572010-05-24 17:01:56 +00001513 if (Pointee->isVoidType() && !isSFINAEContext()) {
1514 // The C++ standard bans deleting a pointer to a non-object type, which
1515 // effectively bans deletion of "void*". However, most compilers support
1516 // this, so we treat it as a warning unless we're in a SFINAE context.
1517 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1518 << Type << Ex->getSourceRange();
1519 } else if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001520 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1521 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001522 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001523 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +00001524 PDiag(diag::warn_delete_incomplete)
1525 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001526 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +00001527
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001528 // C++ [expr.delete]p2:
1529 // [Note: a pointer to a const type can be the operand of a
1530 // delete-expression; it is not necessary to cast away the constness
1531 // (5.2.11) of the pointer expression before it is used as the operand
1532 // of the delete-expression. ]
1533 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
John McCall2de56d12010-08-25 11:45:40 +00001534 CK_NoOp);
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001535
1536 if (Pointee->isArrayType() && !ArrayForm) {
1537 Diag(StartLoc, diag::warn_delete_array_type)
1538 << Type << Ex->getSourceRange()
1539 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1540 ArrayForm = true;
1541 }
1542
Anders Carlssond67c4c32009-08-16 20:29:29 +00001543 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1544 ArrayForm ? OO_Array_Delete : OO_Delete);
1545
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001546 QualType PointeeElem = Context.getBaseElementType(Pointee);
1547 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001548 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1549
1550 if (!UseGlobal &&
1551 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001552 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001553
Anders Carlsson78f74552009-11-15 18:45:20 +00001554 if (!RD->hasTrivialDestructor())
Douglas Gregor9b623632010-10-12 23:32:35 +00001555 if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001556 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001557 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor9b623632010-10-12 23:32:35 +00001558 DiagnoseUseOfDecl(Dtor, StartLoc);
1559 }
Anders Carlssond67c4c32009-08-16 20:29:29 +00001560 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001561
Anders Carlssond67c4c32009-08-16 20:29:29 +00001562 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001563 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001564 DeclareGlobalNewDelete();
1565 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001566 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +00001567 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001568 OperatorDelete))
1569 return ExprError();
1570 }
Mike Stump1eb44332009-09-09 15:08:12 +00001571
John McCall9c82afc2010-04-20 02:18:25 +00001572 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1573
Sebastian Redl28507842009-02-26 14:39:58 +00001574 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001575 }
1576
Sebastian Redlf53597f2009-03-15 17:47:39 +00001577 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001578 ArrayFormAsWritten, OperatorDelete,
1579 Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001580}
1581
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001582/// \brief Check the use of the given variable as a C++ condition in an if,
1583/// while, do-while, or switch statement.
John McCall60d7b3a2010-08-24 06:29:42 +00001584ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
Douglas Gregor586596f2010-05-06 17:25:47 +00001585 SourceLocation StmtLoc,
1586 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001587 QualType T = ConditionVar->getType();
1588
1589 // C++ [stmt.select]p2:
1590 // The declarator shall not specify a function or an array.
1591 if (T->isFunctionType())
1592 return ExprError(Diag(ConditionVar->getLocation(),
1593 diag::err_invalid_use_of_function_type)
1594 << ConditionVar->getSourceRange());
1595 else if (T->isArrayType())
1596 return ExprError(Diag(ConditionVar->getLocation(),
1597 diag::err_invalid_use_of_array_type)
1598 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001599
Douglas Gregor586596f2010-05-06 17:25:47 +00001600 Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1601 ConditionVar->getLocation(),
1602 ConditionVar->getType().getNonReferenceType());
Douglas Gregorff331c12010-07-25 18:17:45 +00001603 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc))
Douglas Gregor586596f2010-05-06 17:25:47 +00001604 return ExprError();
Douglas Gregor586596f2010-05-06 17:25:47 +00001605
1606 return Owned(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001607}
1608
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001609/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1610bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1611 // C++ 6.4p4:
1612 // The value of a condition that is an initialized declaration in a statement
1613 // other than a switch statement is the value of the declared variable
1614 // implicitly converted to type bool. If that conversion is ill-formed, the
1615 // program is ill-formed.
1616 // The value of a condition that is an expression is the value of the
1617 // expression, implicitly converted to bool.
1618 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001619 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001620}
Douglas Gregor77a52232008-09-12 00:47:35 +00001621
1622/// Helper function to determine whether this is the (deprecated) C++
1623/// conversion from a string literal to a pointer to non-const char or
1624/// non-const wchar_t (for narrow and wide string literals,
1625/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001626bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001627Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1628 // Look inside the implicit cast, if it exists.
1629 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1630 From = Cast->getSubExpr();
1631
1632 // A string literal (2.13.4) that is not a wide string literal can
1633 // be converted to an rvalue of type "pointer to char"; a wide
1634 // string literal can be converted to an rvalue of type "pointer
1635 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00001636 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00001637 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001638 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001639 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001640 // This conversion is considered only when there is an
1641 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001642 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001643 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1644 (!StrLit->isWide() &&
1645 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1646 ToPointeeType->getKind() == BuiltinType::Char_S))))
1647 return true;
1648 }
1649
1650 return false;
1651}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001652
John McCall60d7b3a2010-08-24 06:29:42 +00001653static ExprResult BuildCXXCastArgument(Sema &S,
John McCall2de56d12010-08-25 11:45:40 +00001654 SourceLocation CastLoc,
1655 QualType Ty,
1656 CastKind Kind,
1657 CXXMethodDecl *Method,
1658 Expr *From) {
Douglas Gregorba70ab62010-04-16 22:17:36 +00001659 switch (Kind) {
1660 default: assert(0 && "Unhandled cast kind!");
John McCall2de56d12010-08-25 11:45:40 +00001661 case CK_ConstructorConversion: {
John McCallca0408f2010-08-23 06:44:23 +00001662 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregorba70ab62010-04-16 22:17:36 +00001663
1664 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
John McCallf312b1e2010-08-26 23:41:50 +00001665 MultiExprArg(&From, 1),
Douglas Gregorba70ab62010-04-16 22:17:36 +00001666 CastLoc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00001667 return ExprError();
Douglas Gregorba70ab62010-04-16 22:17:36 +00001668
John McCall60d7b3a2010-08-24 06:29:42 +00001669 ExprResult Result =
Douglas Gregorba70ab62010-04-16 22:17:36 +00001670 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
John McCall7a1fad32010-08-24 07:32:53 +00001671 move_arg(ConstructorArgs),
Chandler Carruth428edaf2010-10-25 08:47:36 +00001672 /*ZeroInit*/ false, CXXConstructExpr::CK_Complete,
1673 SourceRange());
Douglas Gregorba70ab62010-04-16 22:17:36 +00001674 if (Result.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00001675 return ExprError();
Douglas Gregorba70ab62010-04-16 22:17:36 +00001676
1677 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1678 }
1679
John McCall2de56d12010-08-25 11:45:40 +00001680 case CK_UserDefinedConversion: {
Douglas Gregorba70ab62010-04-16 22:17:36 +00001681 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1682
1683 // Create an implicit call expr that calls it.
1684 // FIXME: pass the FoundDecl for the user-defined conversion here
1685 CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method);
1686 return S.MaybeBindToTemporary(CE);
1687 }
1688 }
1689}
1690
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001691/// PerformImplicitConversion - Perform an implicit conversion of the
1692/// expression From to the type ToType using the pre-computed implicit
1693/// conversion sequence ICS. Returns true if there was an error, false
1694/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001695/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001696/// used in the error message.
1697bool
1698Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1699 const ImplicitConversionSequence &ICS,
Douglas Gregor68647482009-12-16 03:45:30 +00001700 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall1d318332010-01-12 00:44:57 +00001701 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001702 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001703 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001704 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001705 return true;
1706 break;
1707
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001708 case ImplicitConversionSequence::UserDefinedConversion: {
1709
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001710 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCalldaa8e4e2010-11-15 09:13:47 +00001711 CastKind CastKind;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001712 QualType BeforeToType;
1713 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCall2de56d12010-08-25 11:45:40 +00001714 CastKind = CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001715
1716 // If the user-defined conversion is specified by a conversion function,
1717 // the initial standard conversion sequence converts the source type to
1718 // the implicit object parameter of the conversion function.
1719 BeforeToType = Context.getTagDeclType(Conv->getParent());
1720 } else if (const CXXConstructorDecl *Ctor =
1721 dyn_cast<CXXConstructorDecl>(FD)) {
John McCall2de56d12010-08-25 11:45:40 +00001722 CastKind = CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001723 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001724 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001725 // If the user-defined conversion is specified by a constructor, the
1726 // initial standard conversion sequence converts the source type to the
1727 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001728 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1729 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001730 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001731 else
1732 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001733 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001734 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001735 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001736 ICS.UserDefined.Before, AA_Converting,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001737 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001738 return true;
1739 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001740
John McCall60d7b3a2010-08-24 06:29:42 +00001741 ExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00001742 = BuildCXXCastArgument(*this,
1743 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00001744 ToType.getNonReferenceType(),
1745 CastKind, cast<CXXMethodDecl>(FD),
John McCall9ae2f072010-08-23 23:25:46 +00001746 From);
Anders Carlsson0aebc812009-09-09 21:33:21 +00001747
1748 if (CastArg.isInvalid())
1749 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001750
1751 From = CastArg.takeAs<Expr>();
1752
Eli Friedmand8889622009-11-27 04:41:50 +00001753 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor68647482009-12-16 03:45:30 +00001754 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001755 }
John McCall1d318332010-01-12 00:44:57 +00001756
1757 case ImplicitConversionSequence::AmbiguousConversion:
John McCall120d63c2010-08-24 20:38:10 +00001758 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall1d318332010-01-12 00:44:57 +00001759 PDiag(diag::err_typecheck_ambiguous_condition)
1760 << From->getSourceRange());
1761 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001762
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001763 case ImplicitConversionSequence::EllipsisConversion:
1764 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001765 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001766
1767 case ImplicitConversionSequence::BadConversion:
1768 return true;
1769 }
1770
1771 // Everything went well.
1772 return false;
1773}
1774
1775/// PerformImplicitConversion - Perform an implicit conversion of the
1776/// expression From to the type ToType by following the standard
1777/// conversion sequence SCS. Returns true if there was an error, false
1778/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001779/// expression. Flavor is the context in which we're performing this
1780/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001781bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001782Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001783 const StandardConversionSequence& SCS,
Douglas Gregor68647482009-12-16 03:45:30 +00001784 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001785 // Overall FIXME: we are recomputing too many types here and doing far too
1786 // much extra work. What this means is that we need to keep track of more
1787 // information that is computed when we try the implicit conversion initially,
1788 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001789 QualType FromType = From->getType();
1790
Douglas Gregor225c41e2008-11-03 19:09:14 +00001791 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001792 // FIXME: When can ToType be a reference type?
1793 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001794 if (SCS.Second == ICK_Derived_To_Base) {
John McCallca0408f2010-08-23 06:44:23 +00001795 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001796 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCallca0408f2010-08-23 06:44:23 +00001797 MultiExprArg(*this, &From, 1),
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001798 /*FIXME:ConstructLoc*/SourceLocation(),
1799 ConstructorArgs))
1800 return true;
John McCall60d7b3a2010-08-24 06:29:42 +00001801 ExprResult FromResult =
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001802 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1803 ToType, SCS.CopyConstructor,
John McCall7a1fad32010-08-24 07:32:53 +00001804 move_arg(ConstructorArgs),
1805 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00001806 CXXConstructExpr::CK_Complete,
1807 SourceRange());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001808 if (FromResult.isInvalid())
1809 return true;
1810 From = FromResult.takeAs<Expr>();
1811 return false;
1812 }
John McCall60d7b3a2010-08-24 06:29:42 +00001813 ExprResult FromResult =
Mike Stump1eb44332009-09-09 15:08:12 +00001814 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1815 ToType, SCS.CopyConstructor,
John McCall7a1fad32010-08-24 07:32:53 +00001816 MultiExprArg(*this, &From, 1),
1817 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00001818 CXXConstructExpr::CK_Complete,
1819 SourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +00001820
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001821 if (FromResult.isInvalid())
1822 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001823
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001824 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001825 return false;
1826 }
1827
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001828 // Resolve overloaded function references.
1829 if (Context.hasSameType(FromType, Context.OverloadTy)) {
1830 DeclAccessPair Found;
1831 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1832 true, Found);
1833 if (!Fn)
1834 return true;
1835
1836 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1837 return true;
Douglas Gregor9b623632010-10-12 23:32:35 +00001838
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001839 From = FixOverloadedFunctionReference(From, Found, Fn);
1840 FromType = From->getType();
1841 }
1842
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001843 // Perform the first implicit conversion.
1844 switch (SCS.First) {
1845 case ICK_Identity:
1846 case ICK_Lvalue_To_Rvalue:
1847 // Nothing to do.
1848 break;
1849
1850 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001851 FromType = Context.getArrayDecayedType(FromType);
John McCall2de56d12010-08-25 11:45:40 +00001852 ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001853 break;
1854
1855 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001856 FromType = Context.getPointerType(FromType);
John McCall2de56d12010-08-25 11:45:40 +00001857 ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001858 break;
1859
1860 default:
1861 assert(false && "Improper first standard conversion");
1862 break;
1863 }
1864
1865 // Perform the second implicit conversion
1866 switch (SCS.Second) {
1867 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001868 // If both sides are functions (or pointers/references to them), there could
1869 // be incompatible exception declarations.
1870 if (CheckExceptionSpecCompatibility(From, ToType))
1871 return true;
1872 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001873 break;
1874
Douglas Gregor43c79c22009-12-09 00:47:37 +00001875 case ICK_NoReturn_Adjustment:
1876 // If both sides are functions (or pointers/references to them), there could
1877 // be incompatible exception declarations.
1878 if (CheckExceptionSpecCompatibility(From, ToType))
1879 return true;
1880
1881 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
John McCall2de56d12010-08-25 11:45:40 +00001882 CK_NoOp);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001883 break;
1884
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001885 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001886 case ICK_Integral_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00001887 ImpCastExprToType(From, ToType, CK_IntegralCast);
Eli Friedman73c39ab2009-10-20 08:27:19 +00001888 break;
1889
1890 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001891 case ICK_Floating_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00001892 ImpCastExprToType(From, ToType, CK_FloatingCast);
Eli Friedman73c39ab2009-10-20 08:27:19 +00001893 break;
1894
1895 case ICK_Complex_Promotion:
John McCalldaa8e4e2010-11-15 09:13:47 +00001896 case ICK_Complex_Conversion: {
1897 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
1898 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
1899 CastKind CK;
1900 if (FromEl->isRealFloatingType()) {
1901 if (ToEl->isRealFloatingType())
1902 CK = CK_FloatingComplexCast;
1903 else
1904 CK = CK_FloatingComplexToIntegralComplex;
1905 } else if (ToEl->isRealFloatingType()) {
1906 CK = CK_IntegralComplexToFloatingComplex;
1907 } else {
1908 CK = CK_IntegralComplexCast;
1909 }
1910 ImpCastExprToType(From, ToType, CK);
Eli Friedman73c39ab2009-10-20 08:27:19 +00001911 break;
John McCalldaa8e4e2010-11-15 09:13:47 +00001912 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00001913
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001914 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001915 if (ToType->isRealFloatingType())
John McCall2de56d12010-08-25 11:45:40 +00001916 ImpCastExprToType(From, ToType, CK_IntegralToFloating);
Eli Friedman73c39ab2009-10-20 08:27:19 +00001917 else
John McCall2de56d12010-08-25 11:45:40 +00001918 ImpCastExprToType(From, ToType, CK_FloatingToIntegral);
Eli Friedman73c39ab2009-10-20 08:27:19 +00001919 break;
1920
Douglas Gregorf9201e02009-02-11 23:02:49 +00001921 case ICK_Compatible_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00001922 ImpCastExprToType(From, ToType, CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001923 break;
1924
Anders Carlsson61faec12009-09-12 04:46:44 +00001925 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001926 if (SCS.IncompatibleObjC) {
1927 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001928 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001929 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00001930 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00001931 << From->getSourceRange();
1932 }
Anders Carlsson61faec12009-09-12 04:46:44 +00001933
John McCalldaa8e4e2010-11-15 09:13:47 +00001934 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00001935 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001936 if (CheckPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001937 return true;
John McCall5baba9d2010-08-25 10:28:54 +00001938 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001939 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001940 }
1941
1942 case ICK_Pointer_Member: {
John McCalldaa8e4e2010-11-15 09:13:47 +00001943 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00001944 CXXCastPath BasePath;
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001945 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath,
1946 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001947 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001948 if (CheckExceptionSpecCompatibility(From, ToType))
1949 return true;
John McCall5baba9d2010-08-25 10:28:54 +00001950 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
Anders Carlsson61faec12009-09-12 04:46:44 +00001951 break;
1952 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001953 case ICK_Boolean_Conversion: {
John McCalldaa8e4e2010-11-15 09:13:47 +00001954 CastKind Kind = CK_Invalid;
1955 switch (FromType->getScalarTypeKind()) {
1956 case Type::STK_Pointer: Kind = CK_PointerToBoolean; break;
1957 case Type::STK_MemberPointer: Kind = CK_MemberPointerToBoolean; break;
1958 case Type::STK_Bool: llvm_unreachable("bool -> bool conversion?");
1959 case Type::STK_Integral: Kind = CK_IntegralToBoolean; break;
1960 case Type::STK_Floating: Kind = CK_FloatingToBoolean; break;
1961 case Type::STK_IntegralComplex: Kind = CK_IntegralComplexToBoolean; break;
1962 case Type::STK_FloatingComplex: Kind = CK_FloatingComplexToBoolean; break;
1963 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001964
1965 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001966 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001967 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001968
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001969 case ICK_Derived_To_Base: {
John McCallf871d0c2010-08-07 06:22:56 +00001970 CXXCastPath BasePath;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001971 if (CheckDerivedToBaseConversion(From->getType(),
1972 ToType.getNonReferenceType(),
1973 From->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001974 From->getSourceRange(),
1975 &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001976 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001977 return true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001978
Sebastian Redl906082e2010-07-20 04:20:21 +00001979 ImpCastExprToType(From, ToType.getNonReferenceType(),
John McCall2de56d12010-08-25 11:45:40 +00001980 CK_DerivedToBase, CastCategory(From),
John McCallf871d0c2010-08-07 06:22:56 +00001981 &BasePath);
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001982 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001983 }
1984
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001985 case ICK_Vector_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00001986 ImpCastExprToType(From, ToType, CK_BitCast);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001987 break;
1988
1989 case ICK_Vector_Splat:
John McCall2de56d12010-08-25 11:45:40 +00001990 ImpCastExprToType(From, ToType, CK_VectorSplat);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001991 break;
1992
1993 case ICK_Complex_Real:
John McCalldaa8e4e2010-11-15 09:13:47 +00001994 // Case 1. x -> _Complex y
1995 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
1996 QualType ElType = ToComplex->getElementType();
1997 bool isFloatingComplex = ElType->isRealFloatingType();
1998
1999 // x -> y
2000 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2001 // do nothing
2002 } else if (From->getType()->isRealFloatingType()) {
2003 ImpCastExprToType(From, ElType,
2004 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral);
2005 } else {
2006 assert(From->getType()->isIntegerType());
2007 ImpCastExprToType(From, ElType,
2008 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast);
2009 }
2010 // y -> _Complex y
2011 ImpCastExprToType(From, ToType,
2012 isFloatingComplex ? CK_FloatingRealToComplex
2013 : CK_IntegralRealToComplex);
2014
2015 // Case 2. _Complex x -> y
2016 } else {
2017 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2018 assert(FromComplex);
2019
2020 QualType ElType = FromComplex->getElementType();
2021 bool isFloatingComplex = ElType->isRealFloatingType();
2022
2023 // _Complex x -> x
2024 ImpCastExprToType(From, ElType,
2025 isFloatingComplex ? CK_FloatingComplexToReal
2026 : CK_IntegralComplexToReal);
2027
2028 // x -> y
2029 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2030 // do nothing
2031 } else if (ToType->isRealFloatingType()) {
2032 ImpCastExprToType(From, ToType,
2033 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating);
2034 } else {
2035 assert(ToType->isIntegerType());
2036 ImpCastExprToType(From, ToType,
2037 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast);
2038 }
2039 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002040 break;
2041
2042 case ICK_Lvalue_To_Rvalue:
2043 case ICK_Array_To_Pointer:
2044 case ICK_Function_To_Pointer:
2045 case ICK_Qualification:
2046 case ICK_Num_Conversion_Kinds:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002047 assert(false && "Improper second standard conversion");
2048 break;
2049 }
2050
2051 switch (SCS.Third) {
2052 case ICK_Identity:
2053 // Nothing to do.
2054 break;
2055
Sebastian Redl906082e2010-07-20 04:20:21 +00002056 case ICK_Qualification: {
2057 // The qualification keeps the category of the inner expression, unless the
2058 // target type isn't a reference.
John McCall5baba9d2010-08-25 10:28:54 +00002059 ExprValueKind VK = ToType->isReferenceType() ?
2060 CastCategory(From) : VK_RValue;
Douglas Gregor63982352010-07-13 18:40:04 +00002061 ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
John McCall2de56d12010-08-25 11:45:40 +00002062 CK_NoOp, VK);
Douglas Gregora9bff302010-02-28 18:30:25 +00002063
2064 if (SCS.DeprecatedStringLiteralToCharPtr)
2065 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2066 << ToType.getNonReferenceType();
2067
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002068 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002069 }
2070
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002071 default:
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002072 assert(false && "Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002073 break;
2074 }
2075
2076 return false;
2077}
2078
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002079ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002080 SourceLocation KWLoc,
2081 ParsedType Ty,
2082 SourceLocation RParen) {
2083 TypeSourceInfo *TSInfo;
2084 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002085
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002086 if (!TSInfo)
2087 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002088 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002089}
2090
Sebastian Redlf8aca862010-09-14 23:40:14 +00002091static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT, QualType T,
2092 SourceLocation KeyLoc) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002093 assert(!T->isDependentType() &&
2094 "Cannot evaluate traits for dependent types.");
2095 ASTContext &C = Self.Context;
2096 switch(UTT) {
2097 default: assert(false && "Unknown type trait or not implemented");
2098 case UTT_IsPOD: return T->isPODType();
2099 case UTT_IsLiteral: return T->isLiteralType();
2100 case UTT_IsClass: // Fallthrough
2101 case UTT_IsUnion:
2102 if (const RecordType *Record = T->getAs<RecordType>()) {
2103 bool Union = Record->getDecl()->isUnion();
2104 return UTT == UTT_IsUnion ? Union : !Union;
2105 }
2106 return false;
2107 case UTT_IsEnum: return T->isEnumeralType();
2108 case UTT_IsPolymorphic:
2109 if (const RecordType *Record = T->getAs<RecordType>()) {
2110 // Type traits are only parsed in C++, so we've got CXXRecords.
2111 return cast<CXXRecordDecl>(Record->getDecl())->isPolymorphic();
2112 }
2113 return false;
2114 case UTT_IsAbstract:
2115 if (const RecordType *RT = T->getAs<RecordType>())
2116 return cast<CXXRecordDecl>(RT->getDecl())->isAbstract();
2117 return false;
2118 case UTT_IsEmpty:
2119 if (const RecordType *Record = T->getAs<RecordType>()) {
2120 return !Record->getDecl()->isUnion()
2121 && cast<CXXRecordDecl>(Record->getDecl())->isEmpty();
2122 }
2123 return false;
2124 case UTT_HasTrivialConstructor:
2125 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2126 // If __is_pod (type) is true then the trait is true, else if type is
2127 // a cv class or union type (or array thereof) with a trivial default
2128 // constructor ([class.ctor]) then the trait is true, else it is false.
2129 if (T->isPODType())
2130 return true;
2131 if (const RecordType *RT =
2132 C.getBaseElementType(T)->getAs<RecordType>())
2133 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialConstructor();
2134 return false;
2135 case UTT_HasTrivialCopy:
2136 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2137 // If __is_pod (type) is true or type is a reference type then
2138 // the trait is true, else if type is a cv class or union type
2139 // with a trivial copy constructor ([class.copy]) then the trait
2140 // is true, else it is false.
2141 if (T->isPODType() || T->isReferenceType())
2142 return true;
2143 if (const RecordType *RT = T->getAs<RecordType>())
2144 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2145 return false;
2146 case UTT_HasTrivialAssign:
2147 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2148 // If type is const qualified or is a reference type then the
2149 // trait is false. Otherwise if __is_pod (type) is true then the
2150 // trait is true, else if type is a cv class or union type with
2151 // a trivial copy assignment ([class.copy]) then the trait is
2152 // true, else it is false.
2153 // Note: the const and reference restrictions are interesting,
2154 // given that const and reference members don't prevent a class
2155 // from having a trivial copy assignment operator (but do cause
2156 // errors if the copy assignment operator is actually used, q.v.
2157 // [class.copy]p12).
2158
2159 if (C.getBaseElementType(T).isConstQualified())
2160 return false;
2161 if (T->isPODType())
2162 return true;
2163 if (const RecordType *RT = T->getAs<RecordType>())
2164 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2165 return false;
2166 case UTT_HasTrivialDestructor:
2167 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2168 // If __is_pod (type) is true or type is a reference type
2169 // then the trait is true, else if type is a cv class or union
2170 // type (or array thereof) with a trivial destructor
2171 // ([class.dtor]) then the trait is true, else it is
2172 // false.
2173 if (T->isPODType() || T->isReferenceType())
2174 return true;
2175 if (const RecordType *RT =
2176 C.getBaseElementType(T)->getAs<RecordType>())
2177 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2178 return false;
2179 // TODO: Propagate nothrowness for implicitly declared special members.
2180 case UTT_HasNothrowAssign:
2181 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2182 // If type is const qualified or is a reference type then the
2183 // trait is false. Otherwise if __has_trivial_assign (type)
2184 // is true then the trait is true, else if type is a cv class
2185 // or union type with copy assignment operators that are known
2186 // not to throw an exception then the trait is true, else it is
2187 // false.
2188 if (C.getBaseElementType(T).isConstQualified())
2189 return false;
2190 if (T->isReferenceType())
2191 return false;
2192 if (T->isPODType())
2193 return true;
2194 if (const RecordType *RT = T->getAs<RecordType>()) {
2195 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2196 if (RD->hasTrivialCopyAssignment())
2197 return true;
2198
2199 bool FoundAssign = false;
2200 bool AllNoThrow = true;
2201 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redlf8aca862010-09-14 23:40:14 +00002202 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2203 Sema::LookupOrdinaryName);
2204 if (Self.LookupQualifiedName(Res, RD)) {
2205 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2206 Op != OpEnd; ++Op) {
2207 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2208 if (Operator->isCopyAssignmentOperator()) {
2209 FoundAssign = true;
2210 const FunctionProtoType *CPT
2211 = Operator->getType()->getAs<FunctionProtoType>();
2212 if (!CPT->hasEmptyExceptionSpec()) {
2213 AllNoThrow = false;
2214 break;
2215 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002216 }
2217 }
2218 }
2219
2220 return FoundAssign && AllNoThrow;
2221 }
2222 return false;
2223 case UTT_HasNothrowCopy:
2224 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2225 // If __has_trivial_copy (type) is true then the trait is true, else
2226 // if type is a cv class or union type with copy constructors that are
2227 // known not to throw an exception then the trait is true, else it is
2228 // false.
2229 if (T->isPODType() || T->isReferenceType())
2230 return true;
2231 if (const RecordType *RT = T->getAs<RecordType>()) {
2232 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2233 if (RD->hasTrivialCopyConstructor())
2234 return true;
2235
2236 bool FoundConstructor = false;
2237 bool AllNoThrow = true;
2238 unsigned FoundTQs;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002239 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl5f4e8992010-09-13 21:10:20 +00002240 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002241 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002242 // A template constructor is never a copy constructor.
2243 // FIXME: However, it may actually be selected at the actual overload
2244 // resolution point.
2245 if (isa<FunctionTemplateDecl>(*Con))
2246 continue;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002247 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2248 if (Constructor->isCopyConstructor(FoundTQs)) {
2249 FoundConstructor = true;
2250 const FunctionProtoType *CPT
2251 = Constructor->getType()->getAs<FunctionProtoType>();
Sebastian Redl751025d2010-09-13 22:02:47 +00002252 // TODO: check whether evaluating default arguments can throw.
2253 // For now, we'll be conservative and assume that they can throw.
2254 if (!CPT->hasEmptyExceptionSpec() || CPT->getNumArgs() > 1) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002255 AllNoThrow = false;
2256 break;
2257 }
2258 }
2259 }
2260
2261 return FoundConstructor && AllNoThrow;
2262 }
2263 return false;
2264 case UTT_HasNothrowConstructor:
2265 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2266 // If __has_trivial_constructor (type) is true then the trait is
2267 // true, else if type is a cv class or union type (or array
2268 // thereof) with a default constructor that is known not to
2269 // throw an exception then the trait is true, else it is false.
2270 if (T->isPODType())
2271 return true;
2272 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
2273 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2274 if (RD->hasTrivialConstructor())
2275 return true;
2276
Sebastian Redl751025d2010-09-13 22:02:47 +00002277 DeclContext::lookup_const_iterator Con, ConEnd;
2278 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2279 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002280 // FIXME: In C++0x, a constructor template can be a default constructor.
2281 if (isa<FunctionTemplateDecl>(*Con))
2282 continue;
Sebastian Redl751025d2010-09-13 22:02:47 +00002283 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2284 if (Constructor->isDefaultConstructor()) {
2285 const FunctionProtoType *CPT
2286 = Constructor->getType()->getAs<FunctionProtoType>();
2287 // TODO: check whether evaluating default arguments can throw.
2288 // For now, we'll be conservative and assume that they can throw.
2289 return CPT->hasEmptyExceptionSpec() && CPT->getNumArgs() == 0;
2290 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002291 }
2292 }
2293 return false;
2294 case UTT_HasVirtualDestructor:
2295 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2296 // If type is a class type with a virtual destructor ([class.dtor])
2297 // then the trait is true, else it is false.
2298 if (const RecordType *Record = T->getAs<RecordType>()) {
2299 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redlf8aca862010-09-14 23:40:14 +00002300 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002301 return Destructor->isVirtual();
2302 }
2303 return false;
2304 }
2305}
2306
2307ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002308 SourceLocation KWLoc,
2309 TypeSourceInfo *TSInfo,
2310 SourceLocation RParen) {
2311 QualType T = TSInfo->getType();
2312
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002313 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
2314 // all traits except __is_class, __is_enum and __is_union require a the type
Sebastian Redl607a1782010-09-08 00:48:43 +00002315 // to be complete, an array of unknown bound, or void.
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002316 if (UTT != UTT_IsClass && UTT != UTT_IsEnum && UTT != UTT_IsUnion) {
Sebastian Redl607a1782010-09-08 00:48:43 +00002317 QualType E = T;
2318 if (T->isIncompleteArrayType())
2319 E = Context.getAsArrayType(T)->getElementType();
2320 if (!T->isVoidType() &&
2321 RequireCompleteType(KWLoc, E,
Anders Carlssond497ba72009-08-26 22:59:12 +00002322 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002323 return ExprError();
2324 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00002325
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002326 bool Value = false;
2327 if (!T->isDependentType())
Sebastian Redlf8aca862010-09-14 23:40:14 +00002328 Value = EvaluateUnaryTypeTrait(*this, UTT, T, KWLoc);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002329
2330 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002331 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00002332}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002333
2334QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00002335 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002336 const char *OpSpelling = isIndirect ? "->*" : ".*";
2337 // C++ 5.5p2
2338 // The binary operator .* [p3: ->*] binds its second operand, which shall
2339 // be of type "pointer to member of T" (where T is a completely-defined
2340 // class type) [...]
2341 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002342 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00002343 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002344 Diag(Loc, diag::err_bad_memptr_rhs)
2345 << OpSpelling << RType << rex->getSourceRange();
2346 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00002347 }
Douglas Gregore7450f52009-03-24 19:52:54 +00002348
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002349 QualType Class(MemPtr->getClass(), 0);
2350
Douglas Gregor7d520ba2010-10-13 20:41:14 +00002351 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
2352 // member pointer points must be completely-defined. However, there is no
2353 // reason for this semantic distinction, and the rule is not enforced by
2354 // other compilers. Therefore, we do not check this property, as it is
2355 // likely to be considered a defect.
Sebastian Redl59fc2692010-04-10 10:14:54 +00002356
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002357 // C++ 5.5p2
2358 // [...] to its first operand, which shall be of class T or of a class of
2359 // which T is an unambiguous and accessible base class. [p3: a pointer to
2360 // such a class]
2361 QualType LType = lex->getType();
2362 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002363 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002364 LType = Ptr->getPointeeType().getNonReferenceType();
2365 else {
2366 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00002367 << OpSpelling << 1 << LType
Douglas Gregor849b2432010-03-31 17:46:05 +00002368 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002369 return QualType();
2370 }
2371 }
2372
Douglas Gregora4923eb2009-11-16 21:35:15 +00002373 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00002374 // If we want to check the hierarchy, we need a complete type.
2375 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
2376 << OpSpelling << (int)isIndirect)) {
2377 return QualType();
2378 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002379 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002380 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00002381 // FIXME: Would it be useful to print full ambiguity paths, or is that
2382 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002383 if (!IsDerivedFrom(LType, Class, Paths) ||
2384 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
2385 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00002386 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002387 return QualType();
2388 }
Eli Friedman3005efe2010-01-16 00:00:48 +00002389 // Cast LHS to type of use.
2390 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
John McCall5baba9d2010-08-25 10:28:54 +00002391 ExprValueKind VK =
2392 isIndirect ? VK_RValue : CastCategory(lex);
Sebastian Redl906082e2010-07-20 04:20:21 +00002393
John McCallf871d0c2010-08-07 06:22:56 +00002394 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002395 BuildBasePathArray(Paths, BasePath);
John McCall5baba9d2010-08-25 10:28:54 +00002396 ImpCastExprToType(lex, UseType, CK_DerivedToBase, VK, &BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002397 }
2398
Douglas Gregored8abf12010-07-08 06:14:04 +00002399 if (isa<CXXScalarValueInitExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00002400 // Diagnose use of pointer-to-member type which when used as
2401 // the functional cast in a pointer-to-member expression.
2402 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
2403 return QualType();
2404 }
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002405 // C++ 5.5p2
2406 // The result is an object or a function of the type specified by the
2407 // second operand.
2408 // The cv qualifiers are the union of those in the pointer and the left side,
2409 // in accordance with 5.5p5 and 5.2.5.
2410 // FIXME: This returns a dereferenced member function pointer as a normal
2411 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00002412 // calling them. There's also a GCC extension to get a function pointer to the
2413 // thing, which is another complication, because this type - unlike the type
2414 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002415 // argument.
2416 // We probably need a "MemberFunctionClosureType" or something like that.
2417 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00002418 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002419 return Result;
2420}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002421
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002422/// \brief Try to convert a type to another according to C++0x 5.16p3.
2423///
2424/// This is part of the parameter validation for the ? operator. If either
2425/// value operand is a class type, the two operands are attempted to be
2426/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002427/// It returns true if the program is ill-formed and has already been diagnosed
2428/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002429static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
2430 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00002431 bool &HaveConversion,
2432 QualType &ToType) {
2433 HaveConversion = false;
2434 ToType = To->getType();
2435
2436 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
2437 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002438 // C++0x 5.16p3
2439 // The process for determining whether an operand expression E1 of type T1
2440 // can be converted to match an operand expression E2 of type T2 is defined
2441 // as follows:
2442 // -- If E2 is an lvalue:
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002443 bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid);
2444 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002445 // E1 can be converted to match E2 if E1 can be implicitly converted to
2446 // type "lvalue reference to T2", subject to the constraint that in the
2447 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002448 QualType T = Self.Context.getLValueReferenceType(ToType);
2449 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2450
2451 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2452 if (InitSeq.isDirectReferenceBinding()) {
2453 ToType = T;
2454 HaveConversion = true;
2455 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002456 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002457
2458 if (InitSeq.isAmbiguous())
2459 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002460 }
John McCallb1bdc622010-02-25 01:37:24 +00002461
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002462 // -- If E2 is an rvalue, or if the conversion above cannot be done:
2463 // -- if E1 and E2 have class type, and the underlying class types are
2464 // the same or one is a base class of the other:
2465 QualType FTy = From->getType();
2466 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002467 const RecordType *FRec = FTy->getAs<RecordType>();
2468 const RecordType *TRec = TTy->getAs<RecordType>();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002469 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
2470 Self.IsDerivedFrom(FTy, TTy);
2471 if (FRec && TRec &&
2472 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002473 // E1 can be converted to match E2 if the class of T2 is the
2474 // same type as, or a base class of, the class of T1, and
2475 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00002476 if (FRec == TRec || FDerivedFromT) {
2477 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002478 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2479 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2480 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2481 HaveConversion = true;
2482 return false;
2483 }
2484
2485 if (InitSeq.isAmbiguous())
2486 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2487 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002488 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002489
2490 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002491 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002492
2493 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2494 // implicitly converted to the type that expression E2 would have
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002495 // if E2 were converted to an rvalue (or the type it has, if E2 is
2496 // an rvalue).
2497 //
2498 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2499 // to the array-to-pointer or function-to-pointer conversions.
2500 if (!TTy->getAs<TagType>())
2501 TTy = TTy.getUnqualifiedType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002502
2503 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2504 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2505 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
2506 ToType = TTy;
2507 if (InitSeq.isAmbiguous())
2508 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2509
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002510 return false;
2511}
2512
2513/// \brief Try to find a common type for two according to C++0x 5.16p5.
2514///
2515/// This is part of the parameter validation for the ? operator. If either
2516/// value operand is a class type, overload resolution is used to find a
2517/// conversion to a common type.
2518static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2519 SourceLocation Loc) {
2520 Expr *Args[2] = { LHS, RHS };
John McCall5769d612010-02-08 23:07:23 +00002521 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor573d9c32009-10-21 23:19:44 +00002522 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002523
2524 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00002525 switch (CandidateSet.BestViableFunction(Self, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002526 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002527 // We found a match. Perform the conversions on the arguments and move on.
2528 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00002529 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002530 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00002531 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002532 break;
2533 return false;
2534
Douglas Gregor20093b42009-12-09 23:02:17 +00002535 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002536 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2537 << LHS->getType() << RHS->getType()
2538 << LHS->getSourceRange() << RHS->getSourceRange();
2539 return true;
2540
Douglas Gregor20093b42009-12-09 23:02:17 +00002541 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002542 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2543 << LHS->getType() << RHS->getType()
2544 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00002545 // FIXME: Print the possible common types by printing the return types of
2546 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002547 break;
2548
Douglas Gregor20093b42009-12-09 23:02:17 +00002549 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002550 assert(false && "Conditional operator has only built-in overloads");
2551 break;
2552 }
2553 return true;
2554}
2555
Sebastian Redl76458502009-04-17 16:30:52 +00002556/// \brief Perform an "extended" implicit conversion as returned by
2557/// TryClassUnification.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002558static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2559 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2560 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2561 SourceLocation());
2562 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
John McCallf312b1e2010-08-26 23:41:50 +00002563 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&E, 1));
Douglas Gregorb70cf442010-03-26 20:14:36 +00002564 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00002565 return true;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002566
2567 E = Result.takeAs<Expr>();
Sebastian Redl76458502009-04-17 16:30:52 +00002568 return false;
2569}
2570
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002571/// \brief Check the operands of ?: under C++ semantics.
2572///
2573/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2574/// extension. In this case, LHS == Cond. (But they're not aliases.)
2575QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
Fariborz Jahanian1fb019b2010-09-18 19:38:38 +00002576 Expr *&SAVE,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002577 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002578 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2579 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002580
2581 // C++0x 5.16p1
2582 // The first expression is contextually converted to bool.
2583 if (!Cond->isTypeDependent()) {
Fariborz Jahanian1fb019b2010-09-18 19:38:38 +00002584 if (SAVE && Cond->getType()->isArrayType()) {
2585 QualType CondTy = Cond->getType();
2586 CondTy = Context.getArrayDecayedType(CondTy);
2587 ImpCastExprToType(Cond, CondTy, CK_ArrayToPointerDecay);
2588 SAVE = LHS = Cond;
2589 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002590 if (CheckCXXBooleanCondition(Cond))
2591 return QualType();
2592 }
2593
2594 // Either of the arguments dependent?
2595 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2596 return Context.DependentTy;
2597
2598 // C++0x 5.16p2
2599 // If either the second or the third operand has type (cv) void, ...
2600 QualType LTy = LHS->getType();
2601 QualType RTy = RHS->getType();
2602 bool LVoid = LTy->isVoidType();
2603 bool RVoid = RTy->isVoidType();
2604 if (LVoid || RVoid) {
2605 // ... then the [l2r] conversions are performed on the second and third
2606 // operands ...
Douglas Gregora873dfc2010-02-03 00:27:59 +00002607 DefaultFunctionArrayLvalueConversion(LHS);
2608 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002609 LTy = LHS->getType();
2610 RTy = RHS->getType();
2611
2612 // ... and one of the following shall hold:
2613 // -- The second or the third operand (but not both) is a throw-
2614 // expression; the result is of the type of the other and is an rvalue.
2615 bool LThrow = isa<CXXThrowExpr>(LHS);
2616 bool RThrow = isa<CXXThrowExpr>(RHS);
2617 if (LThrow && !RThrow)
2618 return RTy;
2619 if (RThrow && !LThrow)
2620 return LTy;
2621
2622 // -- Both the second and third operands have type void; the result is of
2623 // type void and is an rvalue.
2624 if (LVoid && RVoid)
2625 return Context.VoidTy;
2626
2627 // Neither holds, error.
2628 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2629 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2630 << LHS->getSourceRange() << RHS->getSourceRange();
2631 return QualType();
2632 }
2633
2634 // Neither is void.
2635
2636 // C++0x 5.16p3
2637 // Otherwise, if the second and third operand have different types, and
2638 // either has (cv) class type, and attempt is made to convert each of those
2639 // operands to the other.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002640 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002641 (LTy->isRecordType() || RTy->isRecordType())) {
2642 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2643 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002644 QualType L2RType, R2LType;
2645 bool HaveL2R, HaveR2L;
2646 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002647 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002648 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002649 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002650
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002651 // If both can be converted, [...] the program is ill-formed.
2652 if (HaveL2R && HaveR2L) {
2653 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2654 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2655 return QualType();
2656 }
2657
2658 // If exactly one conversion is possible, that conversion is applied to
2659 // the chosen operand and the converted operands are used in place of the
2660 // original operands for the remainder of this section.
2661 if (HaveL2R) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002662 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002663 return QualType();
2664 LTy = LHS->getType();
2665 } else if (HaveR2L) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002666 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002667 return QualType();
2668 RTy = RHS->getType();
2669 }
2670 }
2671
2672 // C++0x 5.16p4
2673 // If the second and third operands are lvalues and have the same type,
2674 // the result is of that type [...]
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002675 bool Same = Context.hasSameType(LTy, RTy);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002676 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
Fariborz Jahanian3911a1a2010-09-25 01:08:05 +00002677 RHS->isLvalue(Context) == Expr::LV_Valid) {
2678 // In this context, property reference is really a message call and
2679 // is not considered an l-value.
2680 bool lhsProperty = (isa<ObjCPropertyRefExpr>(LHS) ||
2681 isa<ObjCImplicitSetterGetterRefExpr>(LHS));
2682 bool rhsProperty = (isa<ObjCPropertyRefExpr>(RHS) ||
2683 isa<ObjCImplicitSetterGetterRefExpr>(RHS));
2684 if (!lhsProperty && !rhsProperty)
2685 return LTy;
2686 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002687
2688 // C++0x 5.16p5
2689 // Otherwise, the result is an rvalue. If the second and third operands
2690 // do not have the same type, and either has (cv) class type, ...
2691 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2692 // ... overload resolution is used to determine the conversions (if any)
2693 // to be applied to the operands. If the overload resolution fails, the
2694 // program is ill-formed.
2695 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2696 return QualType();
2697 }
2698
2699 // C++0x 5.16p6
2700 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2701 // conversions are performed on the second and third operands.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002702 DefaultFunctionArrayLvalueConversion(LHS);
2703 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002704 LTy = LHS->getType();
2705 RTy = RHS->getType();
2706
2707 // After those conversions, one of the following shall hold:
2708 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00002709 // is of that type. If the operands have class type, the result
2710 // is a prvalue temporary of the result type, which is
2711 // copy-initialized from either the second operand or the third
2712 // operand depending on the value of the first operand.
2713 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
2714 if (LTy->isRecordType()) {
2715 // The operands have class type. Make a temporary copy.
2716 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
John McCall60d7b3a2010-08-24 06:29:42 +00002717 ExprResult LHSCopy = PerformCopyInitialization(Entity,
Douglas Gregorb65a4582010-05-19 23:40:50 +00002718 SourceLocation(),
2719 Owned(LHS));
2720 if (LHSCopy.isInvalid())
2721 return QualType();
2722
John McCall60d7b3a2010-08-24 06:29:42 +00002723 ExprResult RHSCopy = PerformCopyInitialization(Entity,
Douglas Gregorb65a4582010-05-19 23:40:50 +00002724 SourceLocation(),
2725 Owned(RHS));
2726 if (RHSCopy.isInvalid())
2727 return QualType();
2728
2729 LHS = LHSCopy.takeAs<Expr>();
2730 RHS = RHSCopy.takeAs<Expr>();
2731 }
2732
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002733 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00002734 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002735
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002736 // Extension: conditional operator involving vector types.
2737 if (LTy->isVectorType() || RTy->isVectorType())
2738 return CheckVectorOperands(QuestionLoc, LHS, RHS);
2739
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002740 // -- The second and third operands have arithmetic or enumeration type;
2741 // the usual arithmetic conversions are performed to bring them to a
2742 // common type, and the result is of that type.
2743 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2744 UsualArithmeticConversions(LHS, RHS);
2745 return LHS->getType();
2746 }
2747
2748 // -- The second and third operands have pointer type, or one has pointer
2749 // type and the other is a null pointer constant; pointer conversions
2750 // and qualification conversions are performed to bring them to their
2751 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00002752 // -- The second and third operands have pointer to member type, or one has
2753 // pointer to member type and the other is a null pointer constant;
2754 // pointer to member conversions and qualification conversions are
2755 // performed to bring them to a common type, whose cv-qualification
2756 // shall match the cv-qualification of either the second or the third
2757 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002758 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002759 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002760 isSFINAEContext()? 0 : &NonStandardCompositeType);
2761 if (!Composite.isNull()) {
2762 if (NonStandardCompositeType)
2763 Diag(QuestionLoc,
2764 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2765 << LTy << RTy << Composite
2766 << LHS->getSourceRange() << RHS->getSourceRange();
2767
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002768 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002769 }
Fariborz Jahanian55016362009-12-10 20:46:08 +00002770
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002771 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00002772 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2773 if (!Composite.isNull())
2774 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002775
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002776 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2777 << LHS->getType() << RHS->getType()
2778 << LHS->getSourceRange() << RHS->getSourceRange();
2779 return QualType();
2780}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002781
2782/// \brief Find a merged pointer type and convert the two expressions to it.
2783///
Douglas Gregor20b3e992009-08-24 17:42:35 +00002784/// This finds the composite pointer type (or member pointer type) for @p E1
2785/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2786/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002787/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002788///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002789/// \param Loc The location of the operator requiring these two expressions to
2790/// be converted to the composite pointer type.
2791///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002792/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2793/// a non-standard (but still sane) composite type to which both expressions
2794/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2795/// will be set true.
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002796QualType Sema::FindCompositePointerType(SourceLocation Loc,
2797 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002798 bool *NonStandardCompositeType) {
2799 if (NonStandardCompositeType)
2800 *NonStandardCompositeType = false;
2801
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002802 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2803 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002804
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00002805 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2806 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00002807 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002808
2809 // C++0x 5.9p2
2810 // Pointer conversions and qualification conversions are performed on
2811 // pointer operands to bring them to their composite pointer type. If
2812 // one operand is a null pointer constant, the composite pointer type is
2813 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00002814 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002815 if (T2->isMemberPointerType())
John McCall2de56d12010-08-25 11:45:40 +00002816 ImpCastExprToType(E1, T2, CK_NullToMemberPointer);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002817 else
John McCall404cd162010-11-13 01:35:44 +00002818 ImpCastExprToType(E1, T2, CK_NullToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002819 return T2;
2820 }
Douglas Gregorce940492009-09-25 04:25:58 +00002821 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002822 if (T1->isMemberPointerType())
John McCall2de56d12010-08-25 11:45:40 +00002823 ImpCastExprToType(E2, T1, CK_NullToMemberPointer);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002824 else
John McCall404cd162010-11-13 01:35:44 +00002825 ImpCastExprToType(E2, T1, CK_NullToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002826 return T1;
2827 }
Mike Stump1eb44332009-09-09 15:08:12 +00002828
Douglas Gregor20b3e992009-08-24 17:42:35 +00002829 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002830 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2831 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002832 return QualType();
2833
2834 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2835 // the other has type "pointer to cv2 T" and the composite pointer type is
2836 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2837 // Otherwise, the composite pointer type is a pointer type similar to the
2838 // type of one of the operands, with a cv-qualification signature that is
2839 // the union of the cv-qualification signatures of the operand types.
2840 // In practice, the first part here is redundant; it's subsumed by the second.
2841 // What we do here is, we build the two possible composite types, and try the
2842 // conversions in both directions. If only one works, or if the two composite
2843 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00002844 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00002845 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2846 QualifierVector QualifierUnion;
2847 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2848 ContainingClassVector;
2849 ContainingClassVector MemberOfClass;
2850 QualType Composite1 = Context.getCanonicalType(T1),
2851 Composite2 = Context.getCanonicalType(T2);
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002852 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00002853 do {
2854 const PointerType *Ptr1, *Ptr2;
2855 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2856 (Ptr2 = Composite2->getAs<PointerType>())) {
2857 Composite1 = Ptr1->getPointeeType();
2858 Composite2 = Ptr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002859
2860 // If we're allowed to create a non-standard composite type, keep track
2861 // of where we need to fill in additional 'const' qualifiers.
2862 if (NonStandardCompositeType &&
2863 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2864 NeedConstBefore = QualifierUnion.size();
2865
Douglas Gregor20b3e992009-08-24 17:42:35 +00002866 QualifierUnion.push_back(
2867 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2868 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2869 continue;
2870 }
Mike Stump1eb44332009-09-09 15:08:12 +00002871
Douglas Gregor20b3e992009-08-24 17:42:35 +00002872 const MemberPointerType *MemPtr1, *MemPtr2;
2873 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2874 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2875 Composite1 = MemPtr1->getPointeeType();
2876 Composite2 = MemPtr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002877
2878 // If we're allowed to create a non-standard composite type, keep track
2879 // of where we need to fill in additional 'const' qualifiers.
2880 if (NonStandardCompositeType &&
2881 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2882 NeedConstBefore = QualifierUnion.size();
2883
Douglas Gregor20b3e992009-08-24 17:42:35 +00002884 QualifierUnion.push_back(
2885 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2886 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2887 MemPtr2->getClass()));
2888 continue;
2889 }
Mike Stump1eb44332009-09-09 15:08:12 +00002890
Douglas Gregor20b3e992009-08-24 17:42:35 +00002891 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00002892
Douglas Gregor20b3e992009-08-24 17:42:35 +00002893 // Cannot unwrap any more types.
2894 break;
2895 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00002896
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002897 if (NeedConstBefore && NonStandardCompositeType) {
2898 // Extension: Add 'const' to qualifiers that come before the first qualifier
2899 // mismatch, so that our (non-standard!) composite type meets the
2900 // requirements of C++ [conv.qual]p4 bullet 3.
2901 for (unsigned I = 0; I != NeedConstBefore; ++I) {
2902 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
2903 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
2904 *NonStandardCompositeType = true;
2905 }
2906 }
2907 }
2908
Douglas Gregor20b3e992009-08-24 17:42:35 +00002909 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002910 ContainingClassVector::reverse_iterator MOC
2911 = MemberOfClass.rbegin();
2912 for (QualifierVector::reverse_iterator
2913 I = QualifierUnion.rbegin(),
2914 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00002915 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00002916 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002917 if (MOC->first && MOC->second) {
2918 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00002919 Composite1 = Context.getMemberPointerType(
2920 Context.getQualifiedType(Composite1, Quals),
2921 MOC->first);
2922 Composite2 = Context.getMemberPointerType(
2923 Context.getQualifiedType(Composite2, Quals),
2924 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002925 } else {
2926 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00002927 Composite1
2928 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2929 Composite2
2930 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00002931 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002932 }
2933
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002934 // Try to convert to the first composite pointer type.
2935 InitializedEntity Entity1
2936 = InitializedEntity::InitializeTemporary(Composite1);
2937 InitializationKind Kind
2938 = InitializationKind::CreateCopy(Loc, SourceLocation());
2939 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
2940 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00002941
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002942 if (E1ToC1 && E2ToC1) {
2943 // Conversion to Composite1 is viable.
2944 if (!Context.hasSameType(Composite1, Composite2)) {
2945 // Composite2 is a different type from Composite1. Check whether
2946 // Composite2 is also viable.
2947 InitializedEntity Entity2
2948 = InitializedEntity::InitializeTemporary(Composite2);
2949 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2950 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2951 if (E1ToC2 && E2ToC2) {
2952 // Both Composite1 and Composite2 are viable and are different;
2953 // this is an ambiguity.
2954 return QualType();
2955 }
2956 }
2957
2958 // Convert E1 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00002959 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00002960 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002961 if (E1Result.isInvalid())
2962 return QualType();
2963 E1 = E1Result.takeAs<Expr>();
2964
2965 // Convert E2 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00002966 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00002967 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002968 if (E2Result.isInvalid())
2969 return QualType();
2970 E2 = E2Result.takeAs<Expr>();
2971
2972 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002973 }
2974
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002975 // Check whether Composite2 is viable.
2976 InitializedEntity Entity2
2977 = InitializedEntity::InitializeTemporary(Composite2);
2978 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2979 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2980 if (!E1ToC2 || !E2ToC2)
2981 return QualType();
2982
2983 // Convert E1 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00002984 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00002985 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002986 if (E1Result.isInvalid())
2987 return QualType();
2988 E1 = E1Result.takeAs<Expr>();
2989
2990 // Convert E2 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00002991 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00002992 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002993 if (E2Result.isInvalid())
2994 return QualType();
2995 E2 = E2Result.takeAs<Expr>();
2996
2997 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002998}
Anders Carlsson165a0a02009-05-17 18:41:29 +00002999
John McCall60d7b3a2010-08-24 06:29:42 +00003000ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor19cc1c72010-11-01 21:10:29 +00003001 if (!E)
3002 return ExprError();
3003
Anders Carlsson089c2602009-08-15 23:41:35 +00003004 if (!Context.getLangOptions().CPlusPlus)
3005 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003006
Douglas Gregor51326552009-12-24 18:51:59 +00003007 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
3008
Ted Kremenek6217b802009-07-29 21:53:49 +00003009 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00003010 if (!RT)
3011 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003012
Anders Carlsson0ea4dfd2010-07-16 21:18:37 +00003013 // If this is the result of a call or an Objective-C message send expression,
3014 // our source might actually be a reference, in which case we shouldn't bind.
Anders Carlsson283e4d52009-09-14 01:30:44 +00003015 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
Anders Carlsson0ea4dfd2010-07-16 21:18:37 +00003016 if (CE->getCallReturnType()->isReferenceType())
Anders Carlsson283e4d52009-09-14 01:30:44 +00003017 return Owned(E);
Anders Carlsson0ea4dfd2010-07-16 21:18:37 +00003018 } else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
3019 if (const ObjCMethodDecl *MD = ME->getMethodDecl()) {
3020 if (MD->getResultType()->isReferenceType())
3021 return Owned(E);
3022 }
Anders Carlsson283e4d52009-09-14 01:30:44 +00003023 }
John McCall86ff3082010-02-04 22:26:26 +00003024
3025 // That should be enough to guarantee that this type is complete.
3026 // If it has a trivial destructor, we can avoid the extra copy.
3027 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall507384f2010-08-12 02:40:37 +00003028 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall86ff3082010-02-04 22:26:26 +00003029 return Owned(E);
3030
Douglas Gregordb89f282010-07-01 22:47:18 +00003031 CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD));
Anders Carlsson860306e2009-05-30 21:21:49 +00003032 ExprTemporaries.push_back(Temp);
Douglas Gregordb89f282010-07-01 22:47:18 +00003033 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003034 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00003035 CheckDestructorAccess(E->getExprLoc(), Destructor,
3036 PDiag(diag::err_access_dtor_temp)
3037 << E->getType());
3038 }
Anders Carlssondef11992009-05-30 20:36:53 +00003039 // FIXME: Add the temporary to the temporaries vector.
3040 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
3041}
3042
Anders Carlsson0ece4912009-12-15 20:51:39 +00003043Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003044 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00003045
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00003046 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3047 assert(ExprTemporaries.size() >= FirstTemporary);
3048 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003049 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003050
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003051 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00003052 &ExprTemporaries[FirstTemporary],
Anders Carlsson0ece4912009-12-15 20:51:39 +00003053 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00003054 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
3055 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00003056
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003057 return E;
3058}
3059
John McCall60d7b3a2010-08-24 06:29:42 +00003060ExprResult
3061Sema::MaybeCreateCXXExprWithTemporaries(ExprResult SubExpr) {
Douglas Gregor90f93822009-12-22 22:17:25 +00003062 if (SubExpr.isInvalid())
3063 return ExprError();
3064
3065 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
3066}
3067
Anders Carlsson5ee56e92009-12-16 02:09:40 +00003068FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
3069 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3070 assert(ExprTemporaries.size() >= FirstTemporary);
3071
3072 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
3073 CXXTemporary **Temporaries =
3074 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
3075
3076 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
3077
3078 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
3079 ExprTemporaries.end());
3080
3081 return E;
3082}
3083
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003084Stmt *Sema::MaybeCreateCXXStmtWithTemporaries(Stmt *SubStmt) {
3085 assert(SubStmt && "sub statement can't be null!");
3086
3087 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3088 assert(ExprTemporaries.size() >= FirstTemporary);
3089 if (ExprTemporaries.size() == FirstTemporary)
3090 return SubStmt;
3091
3092 // FIXME: In order to attach the temporaries, wrap the statement into
3093 // a StmtExpr; currently this is only used for asm statements.
3094 // This is hacky, either create a new CXXStmtWithTemporaries statement or
3095 // a new AsmStmtWithTemporaries.
3096 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
3097 SourceLocation(),
3098 SourceLocation());
3099 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
3100 SourceLocation());
3101 return MaybeCreateCXXExprWithTemporaries(E);
3102}
3103
John McCall60d7b3a2010-08-24 06:29:42 +00003104ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003105Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallb3d87482010-08-24 05:47:05 +00003106 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00003107 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003108 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003109 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003110 if (Result.isInvalid()) return ExprError();
3111 Base = Result.get();
Mike Stump1eb44332009-09-09 15:08:12 +00003112
John McCall9ae2f072010-08-23 23:25:46 +00003113 QualType BaseType = Base->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00003114 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003115 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00003116 // If we have a pointer to a dependent type and are using the -> operator,
3117 // the object type is the type that the pointer points to. We might still
3118 // have enough information about that type to do something useful.
3119 if (OpKind == tok::arrow)
3120 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3121 BaseType = Ptr->getPointeeType();
3122
John McCallb3d87482010-08-24 05:47:05 +00003123 ObjectType = ParsedType::make(BaseType);
Douglas Gregord4dca082010-02-24 18:44:31 +00003124 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00003125 return Owned(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003126 }
Mike Stump1eb44332009-09-09 15:08:12 +00003127
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003128 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00003129 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003130 // returned, with the original second operand.
3131 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00003132 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00003133 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00003134 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00003135 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00003136
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003137 while (BaseType->isRecordType()) {
John McCall9ae2f072010-08-23 23:25:46 +00003138 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
3139 if (Result.isInvalid())
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003140 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00003141 Base = Result.get();
3142 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonde699e52009-10-13 22:55:59 +00003143 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCall9ae2f072010-08-23 23:25:46 +00003144 BaseType = Base->getType();
John McCallc4e83212009-09-30 01:01:30 +00003145 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00003146 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00003147 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00003148 for (unsigned i = 0; i < Locations.size(); i++)
3149 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00003150 return ExprError();
3151 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003152 }
Mike Stump1eb44332009-09-09 15:08:12 +00003153
Douglas Gregor31658df2009-11-20 19:58:21 +00003154 if (BaseType->isPointerType())
3155 BaseType = BaseType->getPointeeType();
3156 }
Mike Stump1eb44332009-09-09 15:08:12 +00003157
3158 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003159 // vector types or Objective-C interfaces. Just return early and let
3160 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00003161 if (!BaseType->isRecordType()) {
3162 // C++ [basic.lookup.classref]p2:
3163 // [...] If the type of the object expression is of pointer to scalar
3164 // type, the unqualified-id is looked up in the context of the complete
3165 // postfix-expression.
Douglas Gregord4dca082010-02-24 18:44:31 +00003166 //
3167 // This also indicates that we should be parsing a
3168 // pseudo-destructor-name.
John McCallb3d87482010-08-24 05:47:05 +00003169 ObjectType = ParsedType();
Douglas Gregord4dca082010-02-24 18:44:31 +00003170 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00003171 return Owned(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00003172 }
Mike Stump1eb44332009-09-09 15:08:12 +00003173
Douglas Gregor03c57052009-11-17 05:17:33 +00003174 // The object type must be complete (or dependent).
3175 if (!BaseType->isDependentType() &&
3176 RequireCompleteType(OpLoc, BaseType,
3177 PDiag(diag::err_incomplete_member_access)))
3178 return ExprError();
3179
Douglas Gregorc68afe22009-09-03 21:38:09 +00003180 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00003181 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00003182 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00003183 // type C (or of pointer to a class type C), the unqualified-id is looked
3184 // up in the scope of class C. [...]
John McCallb3d87482010-08-24 05:47:05 +00003185 ObjectType = ParsedType::make(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00003186 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003187}
3188
John McCall60d7b3a2010-08-24 06:29:42 +00003189ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003190 Expr *MemExpr) {
Douglas Gregor77549082010-02-24 21:29:12 +00003191 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCall9ae2f072010-08-23 23:25:46 +00003192 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
3193 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregor849b2432010-03-31 17:46:05 +00003194 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
Douglas Gregor77549082010-02-24 21:29:12 +00003195
3196 return ActOnCallExpr(/*Scope*/ 0,
John McCall9ae2f072010-08-23 23:25:46 +00003197 MemExpr,
Douglas Gregor77549082010-02-24 21:29:12 +00003198 /*LPLoc*/ ExpectedLParenLoc,
John McCallf312b1e2010-08-26 23:41:50 +00003199 MultiExprArg(),
Douglas Gregor77549082010-02-24 21:29:12 +00003200 /*RPLoc*/ ExpectedLParenLoc);
3201}
Douglas Gregord4dca082010-02-24 18:44:31 +00003202
John McCall60d7b3a2010-08-24 06:29:42 +00003203ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003204 SourceLocation OpLoc,
3205 tok::TokenKind OpKind,
3206 const CXXScopeSpec &SS,
Douglas Gregor26d4ac92010-02-24 23:40:28 +00003207 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003208 SourceLocation CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00003209 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003210 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003211 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003212 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
Douglas Gregorb57fb492010-02-24 22:38:50 +00003213
3214 // C++ [expr.pseudo]p2:
3215 // The left-hand side of the dot operator shall be of scalar type. The
3216 // left-hand side of the arrow operator shall be of pointer to scalar type.
3217 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00003218 QualType ObjectType = Base->getType();
Douglas Gregorb57fb492010-02-24 22:38:50 +00003219 if (OpKind == tok::arrow) {
3220 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3221 ObjectType = Ptr->getPointeeType();
John McCall9ae2f072010-08-23 23:25:46 +00003222 } else if (!Base->isTypeDependent()) {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003223 // The user wrote "p->" when she probably meant "p."; fix it.
3224 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3225 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00003226 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb57fb492010-02-24 22:38:50 +00003227 if (isSFINAEContext())
3228 return ExprError();
3229
3230 OpKind = tok::period;
3231 }
3232 }
3233
3234 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
3235 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
John McCall9ae2f072010-08-23 23:25:46 +00003236 << ObjectType << Base->getSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00003237 return ExprError();
3238 }
3239
3240 // C++ [expr.pseudo]p2:
3241 // [...] The cv-unqualified versions of the object type and of the type
3242 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003243 if (DestructedTypeInfo) {
3244 QualType DestructedType = DestructedTypeInfo->getType();
3245 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003246 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003247 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
3248 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
3249 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00003250 << ObjectType << DestructedType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003251 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003252
3253 // Recover by setting the destructed type to the object type.
3254 DestructedType = ObjectType;
3255 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
3256 DestructedTypeStart);
3257 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3258 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00003259 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003260
Douglas Gregorb57fb492010-02-24 22:38:50 +00003261 // C++ [expr.pseudo]p2:
3262 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
3263 // form
3264 //
3265 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
3266 //
3267 // shall designate the same scalar type.
3268 if (ScopeTypeInfo) {
3269 QualType ScopeType = ScopeTypeInfo->getType();
3270 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00003271 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003272
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003273 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00003274 diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00003275 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003276 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00003277
3278 ScopeType = QualType();
3279 ScopeTypeInfo = 0;
3280 }
3281 }
3282
John McCall9ae2f072010-08-23 23:25:46 +00003283 Expr *Result
3284 = new (Context) CXXPseudoDestructorExpr(Context, Base,
3285 OpKind == tok::arrow, OpLoc,
3286 SS.getScopeRep(), SS.getRange(),
3287 ScopeTypeInfo,
3288 CCLoc,
3289 TildeLoc,
3290 Destructed);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003291
Douglas Gregorb57fb492010-02-24 22:38:50 +00003292 if (HasTrailingLParen)
John McCall9ae2f072010-08-23 23:25:46 +00003293 return Owned(Result);
Douglas Gregorb57fb492010-02-24 22:38:50 +00003294
John McCall9ae2f072010-08-23 23:25:46 +00003295 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor77549082010-02-24 21:29:12 +00003296}
3297
John McCall60d7b3a2010-08-24 06:29:42 +00003298ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
Douglas Gregor77549082010-02-24 21:29:12 +00003299 SourceLocation OpLoc,
3300 tok::TokenKind OpKind,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003301 CXXScopeSpec &SS,
Douglas Gregor77549082010-02-24 21:29:12 +00003302 UnqualifiedId &FirstTypeName,
3303 SourceLocation CCLoc,
3304 SourceLocation TildeLoc,
3305 UnqualifiedId &SecondTypeName,
3306 bool HasTrailingLParen) {
3307 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3308 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3309 "Invalid first type name in pseudo-destructor");
3310 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3311 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3312 "Invalid second type name in pseudo-destructor");
3313
Douglas Gregor77549082010-02-24 21:29:12 +00003314 // C++ [expr.pseudo]p2:
3315 // The left-hand side of the dot operator shall be of scalar type. The
3316 // left-hand side of the arrow operator shall be of pointer to scalar type.
3317 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00003318 QualType ObjectType = Base->getType();
Douglas Gregor77549082010-02-24 21:29:12 +00003319 if (OpKind == tok::arrow) {
3320 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3321 ObjectType = Ptr->getPointeeType();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003322 } else if (!ObjectType->isDependentType()) {
Douglas Gregor77549082010-02-24 21:29:12 +00003323 // The user wrote "p->" when she probably meant "p."; fix it.
3324 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003325 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00003326 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor77549082010-02-24 21:29:12 +00003327 if (isSFINAEContext())
3328 return ExprError();
3329
3330 OpKind = tok::period;
3331 }
3332 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003333
3334 // Compute the object type that we should use for name lookup purposes. Only
3335 // record types and dependent types matter.
John McCallb3d87482010-08-24 05:47:05 +00003336 ParsedType ObjectTypePtrForLookup;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003337 if (!SS.isSet()) {
John McCallb3d87482010-08-24 05:47:05 +00003338 if (const Type *T = ObjectType->getAs<RecordType>())
3339 ObjectTypePtrForLookup = ParsedType::make(QualType(T, 0));
3340 else if (ObjectType->isDependentType())
3341 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003342 }
Douglas Gregor77549082010-02-24 21:29:12 +00003343
Douglas Gregorb57fb492010-02-24 22:38:50 +00003344 // Convert the name of the type being destructed (following the ~) into a
3345 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00003346 QualType DestructedType;
3347 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003348 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00003349 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
John McCallb3d87482010-08-24 05:47:05 +00003350 ParsedType T = getTypeName(*SecondTypeName.Identifier,
3351 SecondTypeName.StartLocation,
3352 S, &SS, true, ObjectTypePtrForLookup);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003353 if (!T &&
3354 ((SS.isSet() && !computeDeclContext(SS, false)) ||
3355 (!SS.isSet() && ObjectType->isDependentType()))) {
3356 // The name of the type being destroyed is a dependent name, and we
3357 // couldn't find anything useful in scope. Just store the identifier and
3358 // it's location, and we'll perform (qualified) name lookup again at
3359 // template instantiation time.
3360 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
3361 SecondTypeName.StartLocation);
3362 } else if (!T) {
Douglas Gregor77549082010-02-24 21:29:12 +00003363 Diag(SecondTypeName.StartLocation,
3364 diag::err_pseudo_dtor_destructor_non_type)
3365 << SecondTypeName.Identifier << ObjectType;
3366 if (isSFINAEContext())
3367 return ExprError();
3368
3369 // Recover by assuming we had the right type all along.
3370 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003371 } else
Douglas Gregor77549082010-02-24 21:29:12 +00003372 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003373 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003374 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00003375 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003376 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3377 TemplateId->getTemplateArgs(),
3378 TemplateId->NumArgs);
John McCall2b5289b2010-08-23 07:28:44 +00003379 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003380 TemplateId->TemplateNameLoc,
3381 TemplateId->LAngleLoc,
3382 TemplateArgsPtr,
3383 TemplateId->RAngleLoc);
3384 if (T.isInvalid() || !T.get()) {
3385 // Recover by assuming we had the right type all along.
3386 DestructedType = ObjectType;
3387 } else
3388 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003389 }
3390
Douglas Gregorb57fb492010-02-24 22:38:50 +00003391 // If we've performed some kind of recovery, (re-)build the type source
3392 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003393 if (!DestructedType.isNull()) {
3394 if (!DestructedTypeInfo)
3395 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003396 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003397 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3398 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00003399
3400 // Convert the name of the scope type (the type prior to '::') into a type.
3401 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00003402 QualType ScopeType;
3403 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3404 FirstTypeName.Identifier) {
3405 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
John McCallb3d87482010-08-24 05:47:05 +00003406 ParsedType T = getTypeName(*FirstTypeName.Identifier,
3407 FirstTypeName.StartLocation,
3408 S, &SS, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00003409 if (!T) {
3410 Diag(FirstTypeName.StartLocation,
3411 diag::err_pseudo_dtor_destructor_non_type)
3412 << FirstTypeName.Identifier << ObjectType;
Douglas Gregor77549082010-02-24 21:29:12 +00003413
Douglas Gregorb57fb492010-02-24 22:38:50 +00003414 if (isSFINAEContext())
3415 return ExprError();
3416
3417 // Just drop this type. It's unnecessary anyway.
3418 ScopeType = QualType();
3419 } else
3420 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003421 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003422 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00003423 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003424 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3425 TemplateId->getTemplateArgs(),
3426 TemplateId->NumArgs);
John McCall2b5289b2010-08-23 07:28:44 +00003427 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003428 TemplateId->TemplateNameLoc,
3429 TemplateId->LAngleLoc,
3430 TemplateArgsPtr,
3431 TemplateId->RAngleLoc);
3432 if (T.isInvalid() || !T.get()) {
3433 // Recover by dropping this type.
3434 ScopeType = QualType();
3435 } else
3436 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003437 }
3438 }
Douglas Gregorb4a418f2010-02-24 23:02:30 +00003439
3440 if (!ScopeType.isNull() && !ScopeTypeInfo)
3441 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
3442 FirstTypeName.StartLocation);
3443
3444
John McCall9ae2f072010-08-23 23:25:46 +00003445 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00003446 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003447 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00003448}
3449
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003450CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
John McCall6bb80172010-03-30 21:47:33 +00003451 NamedDecl *FoundDecl,
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003452 CXXMethodDecl *Method) {
John McCall6bb80172010-03-30 21:47:33 +00003453 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
3454 FoundDecl, Method))
Eli Friedman772fffa2009-12-09 04:53:56 +00003455 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
3456
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003457 MemberExpr *ME =
Abramo Bagnara25777432010-08-11 22:01:17 +00003458 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003459 SourceLocation(), Method->getType());
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003460 QualType ResultType = Method->getCallResultType();
Douglas Gregor7edfb692009-11-23 12:27:39 +00003461 MarkDeclarationReferenced(Exp->getLocStart(), Method);
3462 CXXMemberCallExpr *CE =
3463 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
3464 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003465 return CE;
3466}
3467
Sebastian Redl2e156222010-09-10 20:55:43 +00003468ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
3469 SourceLocation RParen) {
Sebastian Redl2e156222010-09-10 20:55:43 +00003470 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
3471 Operand->CanThrow(Context),
3472 KeyLoc, RParen));
3473}
3474
3475ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
3476 Expr *Operand, SourceLocation RParen) {
3477 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl02bc21a2010-09-10 20:55:37 +00003478}
3479
John McCall60d7b3a2010-08-24 06:29:42 +00003480ExprResult Sema::ActOnFinishFullExpr(Expr *FullExpr) {
John McCall9ae2f072010-08-23 23:25:46 +00003481 if (!FullExpr) return ExprError();
John McCallb4eb64d2010-10-08 02:01:28 +00003482
3483 CheckImplicitConversions(FullExpr);
John McCall9ae2f072010-08-23 23:25:46 +00003484 return MaybeCreateCXXExprWithTemporaries(FullExpr);
Anders Carlsson165a0a02009-05-17 18:41:29 +00003485}
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003486
3487StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
3488 if (!FullStmt) return StmtError();
3489
3490 return MaybeCreateCXXStmtWithTemporaries(FullStmt);
3491}