blob: eec2fc88db6340c2c8c2620f4dc7ff84566cb358 [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 McCallf89e55a2010-11-18 06:31:45 +0000608 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +0000609 CXXCastPath BasePath;
Douglas Gregorab6677e2010-09-08 00:15:04 +0000610 if (CheckCastTypes(TInfo->getTypeLoc().getSourceRange(), Ty, Exprs[0],
John McCallf89e55a2010-11-18 06:31:45 +0000611 Kind, VK, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000612 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000613 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000614
615 exprs.release();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000616
John McCallf871d0c2010-08-07 06:22:56 +0000617 return Owned(CXXFunctionalCastExpr::Create(Context,
Douglas Gregorab6677e2010-09-08 00:15:04 +0000618 Ty.getNonLValueExprType(Context),
John McCallf89e55a2010-11-18 06:31:45 +0000619 VK, TInfo, TyBeginLoc, Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000620 Exprs[0], &BasePath,
621 RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000622 }
623
Douglas Gregor19311e72010-09-08 21:40:08 +0000624 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
625 InitializationKind Kind
626 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
627 LParenLoc, RParenLoc)
628 : InitializationKind::CreateValue(TyBeginLoc,
629 LParenLoc, RParenLoc);
630 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
631 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redlf53597f2009-03-15 17:47:39 +0000632
Douglas Gregor19311e72010-09-08 21:40:08 +0000633 // FIXME: Improve AST representation?
634 return move(Result);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000635}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000636
637
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000638/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
639/// @code new (memory) int[size][4] @endcode
640/// or
641/// @code ::new Foo(23, "hello") @endcode
642/// For the interpretation of this heap of arguments, consult the base version.
John McCall60d7b3a2010-08-24 06:29:42 +0000643ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000644Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000645 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000646 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000647 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000648 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000649 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000650 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000651 // If the specified type is an array, unwrap it and save the expression.
652 if (D.getNumTypeObjects() > 0 &&
653 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
654 DeclaratorChunk &Chunk = D.getTypeObject(0);
655 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000656 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
657 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000658 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000659 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
660 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000661
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000662 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000663 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000664 }
665
Douglas Gregor043cad22009-09-11 00:18:58 +0000666 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000667 if (ArraySize) {
668 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000669 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
670 break;
671
672 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
673 if (Expr *NumElts = (Expr *)Array.NumElts) {
674 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
675 !NumElts->isIntegerConstantExpr(Context)) {
676 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
677 << NumElts->getSourceRange();
678 return ExprError();
679 }
680 }
681 }
682 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000683
John McCallbf1a0282010-06-04 23:28:52 +0000684 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
685 QualType AllocType = TInfo->getType();
Chris Lattnereaaebc72009-04-25 08:06:05 +0000686 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000687 return ExprError();
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000688
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000689 if (!TInfo)
690 TInfo = Context.getTrivialTypeSourceInfo(AllocType);
691
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000692 SourceRange R = TInfo->getTypeLoc().getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000693 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000694 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000695 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000696 PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000697 TypeIdParens,
Mike Stump1eb44332009-09-09 15:08:12 +0000698 AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000699 TInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000700 ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000701 ConstructorLParen,
702 move(ConstructorArgs),
703 ConstructorRParen);
704}
705
John McCall60d7b3a2010-08-24 06:29:42 +0000706ExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000707Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
708 SourceLocation PlacementLParen,
709 MultiExprArg PlacementArgs,
710 SourceLocation PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000711 SourceRange TypeIdParens,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000712 QualType AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000713 TypeSourceInfo *AllocTypeInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000714 Expr *ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000715 SourceLocation ConstructorLParen,
716 MultiExprArg ConstructorArgs,
717 SourceLocation ConstructorRParen) {
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000718 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000719
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000720 // Per C++0x [expr.new]p5, the type being constructed may be a
721 // typedef of an array type.
John McCall9ae2f072010-08-23 23:25:46 +0000722 if (!ArraySize) {
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000723 if (const ConstantArrayType *Array
724 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000725 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
726 Context.getSizeType(),
727 TypeRange.getEnd());
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000728 AllocType = Array->getElementType();
729 }
730 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000731
Douglas Gregora0750762010-10-06 16:00:31 +0000732 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
733 return ExprError();
734
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000735 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000736
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000737 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
738 // or enumeration type with a non-negative value."
Sebastian Redl28507842009-02-26 14:39:58 +0000739 if (ArraySize && !ArraySize->isTypeDependent()) {
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000740
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000741 QualType SizeType = ArraySize->getType();
Douglas Gregorc30614b2010-06-29 23:17:37 +0000742
John McCall60d7b3a2010-08-24 06:29:42 +0000743 ExprResult ConvertedSize
John McCall9ae2f072010-08-23 23:25:46 +0000744 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000745 PDiag(diag::err_array_size_not_integral),
746 PDiag(diag::err_array_size_incomplete_type)
747 << ArraySize->getSourceRange(),
748 PDiag(diag::err_array_size_explicit_conversion),
749 PDiag(diag::note_array_size_conversion),
750 PDiag(diag::err_array_size_ambiguous_conversion),
751 PDiag(diag::note_array_size_conversion),
752 PDiag(getLangOptions().CPlusPlus0x? 0
753 : diag::ext_array_size_conversion));
754 if (ConvertedSize.isInvalid())
755 return ExprError();
756
John McCall9ae2f072010-08-23 23:25:46 +0000757 ArraySize = ConvertedSize.take();
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000758 SizeType = ArraySize->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000759 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000760 return ExprError();
761
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000762 // Let's see if this is a constant < 0. If so, we reject it out of hand.
763 // We don't care about special rules, so we tell the machinery it's not
764 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000765 if (!ArraySize->isValueDependent()) {
766 llvm::APSInt Value;
767 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
768 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000769 llvm::APInt::getNullValue(Value.getBitWidth()),
770 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000771 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +0000772 diag::err_typecheck_negative_array_size)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000773 << ArraySize->getSourceRange());
Douglas Gregor2767ce22010-08-18 00:39:00 +0000774
775 if (!AllocType->isDependentType()) {
776 unsigned ActiveSizeBits
777 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
778 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
779 Diag(ArraySize->getSourceRange().getBegin(),
780 diag::err_array_too_large)
781 << Value.toString(10)
782 << ArraySize->getSourceRange();
783 return ExprError();
784 }
785 }
Douglas Gregor4bd40312010-07-13 15:54:32 +0000786 } else if (TypeIdParens.isValid()) {
787 // Can't have dynamic array size when the type-id is in parentheses.
788 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
789 << ArraySize->getSourceRange()
790 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
791 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
792
793 TypeIdParens = SourceRange();
Sebastian Redl28507842009-02-26 14:39:58 +0000794 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000795 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000796
Eli Friedman73c39ab2009-10-20 08:27:19 +0000797 ImpCastExprToType(ArraySize, Context.getSizeType(),
John McCall2de56d12010-08-25 11:45:40 +0000798 CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000799 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000800
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000801 FunctionDecl *OperatorNew = 0;
802 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000803 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
804 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000805
Sebastian Redl28507842009-02-26 14:39:58 +0000806 if (!AllocType->isDependentType() &&
807 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
808 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000809 SourceRange(PlacementLParen, PlacementRParen),
810 UseGlobal, AllocType, ArraySize, PlaceArgs,
811 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000812 return ExprError();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000813 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000814 if (OperatorNew) {
815 // Add default arguments, if any.
816 const FunctionProtoType *Proto =
817 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000818 VariadicCallType CallType =
819 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Anders Carlsson28e94832010-05-03 02:07:56 +0000820
821 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
822 Proto, 1, PlaceArgs, NumPlaceArgs,
823 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000824 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000825
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000826 NumPlaceArgs = AllPlaceArgs.size();
827 if (NumPlaceArgs > 0)
828 PlaceArgs = &AllPlaceArgs[0];
829 }
830
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000831 bool Init = ConstructorLParen.isValid();
832 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000833 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000834 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
835 unsigned NumConsArgs = ConstructorArgs.size();
John McCallca0408f2010-08-23 06:44:23 +0000836 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000837
Anders Carlsson48c95012010-05-03 15:45:23 +0000838 // Array 'new' can't have any initializers.
Anders Carlsson55cbd6e2010-05-16 16:24:20 +0000839 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlsson48c95012010-05-03 15:45:23 +0000840 SourceRange InitRange(ConsArgs[0]->getLocStart(),
841 ConsArgs[NumConsArgs - 1]->getLocEnd());
842
843 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
844 return ExprError();
845 }
846
Douglas Gregor99a2e602009-12-16 01:38:02 +0000847 if (!AllocType->isDependentType() &&
848 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
849 // C++0x [expr.new]p15:
850 // A new-expression that creates an object of type T initializes that
851 // object as follows:
852 InitializationKind Kind
853 // - If the new-initializer is omitted, the object is default-
854 // initialized (8.5); if no initialization is performed,
855 // the object has indeterminate value
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000856 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
Douglas Gregor99a2e602009-12-16 01:38:02 +0000857 // - Otherwise, the new-initializer is interpreted according to the
858 // initialization rules of 8.5 for direct-initialization.
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000859 : InitializationKind::CreateDirect(TypeRange.getBegin(),
Douglas Gregor99a2e602009-12-16 01:38:02 +0000860 ConstructorLParen,
861 ConstructorRParen);
862
Douglas Gregor99a2e602009-12-16 01:38:02 +0000863 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +0000864 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000865 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
John McCall60d7b3a2010-08-24 06:29:42 +0000866 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor99a2e602009-12-16 01:38:02 +0000867 move(ConstructorArgs));
868 if (FullInit.isInvalid())
869 return ExprError();
870
871 // FullInit is our initializer; walk through it to determine if it's a
872 // constructor call, which CXXNewExpr handles directly.
873 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
874 if (CXXBindTemporaryExpr *Binder
875 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
876 FullInitExpr = Binder->getSubExpr();
877 if (CXXConstructExpr *Construct
878 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
879 Constructor = Construct->getConstructor();
880 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
881 AEnd = Construct->arg_end();
882 A != AEnd; ++A)
John McCall3fa5cae2010-10-26 07:05:15 +0000883 ConvertedConstructorArgs.push_back(*A);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000884 } else {
885 // Take the converted initializer.
886 ConvertedConstructorArgs.push_back(FullInit.release());
887 }
888 } else {
889 // No initialization required.
890 }
891
892 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +0000893 NumConsArgs = ConvertedConstructorArgs.size();
894 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000895 }
Douglas Gregor99a2e602009-12-16 01:38:02 +0000896
Douglas Gregor6d908702010-02-26 05:06:18 +0000897 // Mark the new and delete operators as referenced.
898 if (OperatorNew)
899 MarkDeclarationReferenced(StartLoc, OperatorNew);
900 if (OperatorDelete)
901 MarkDeclarationReferenced(StartLoc, OperatorDelete);
902
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000903 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000904
Sebastian Redlf53597f2009-03-15 17:47:39 +0000905 PlacementArgs.release();
906 ConstructorArgs.release();
Ted Kremenekf9d5bac2010-06-25 22:48:49 +0000907
Ted Kremenekad7fe862010-02-11 22:51:03 +0000908 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000909 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenekad7fe862010-02-11 22:51:03 +0000910 ArraySize, Constructor, Init,
911 ConsArgs, NumConsArgs, OperatorDelete,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000912 ResultType, AllocTypeInfo,
913 StartLoc,
Ted Kremenekad7fe862010-02-11 22:51:03 +0000914 Init ? ConstructorRParen :
Chandler Carruth428edaf2010-10-25 08:47:36 +0000915 TypeRange.getEnd(),
916 ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000917}
918
919/// CheckAllocatedType - Checks that a type is suitable as the allocated type
920/// in a new-expression.
921/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000922bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000923 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000924 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
925 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000926 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000927 return Diag(Loc, diag::err_bad_new_type)
928 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000929 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000930 return Diag(Loc, diag::err_bad_new_type)
931 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000932 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000933 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000934 PDiag(diag::err_new_incomplete_type)
935 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000936 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000937 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000938 diag::err_allocation_of_abstract_type))
939 return true;
Douglas Gregora0750762010-10-06 16:00:31 +0000940 else if (AllocType->isVariablyModifiedType())
941 return Diag(Loc, diag::err_variably_modified_new_type)
942 << AllocType;
943
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000944 return false;
945}
946
Douglas Gregor6d908702010-02-26 05:06:18 +0000947/// \brief Determine whether the given function is a non-placement
948/// deallocation function.
949static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
950 if (FD->isInvalidDecl())
951 return false;
952
953 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
954 return Method->isUsualDeallocationFunction();
955
956 return ((FD->getOverloadedOperator() == OO_Delete ||
957 FD->getOverloadedOperator() == OO_Array_Delete) &&
958 FD->getNumParams() == 1);
959}
960
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000961/// FindAllocationFunctions - Finds the overloads of operator new and delete
962/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000963bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
964 bool UseGlobal, QualType AllocType,
965 bool IsArray, Expr **PlaceArgs,
966 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000967 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000968 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000969 // --- Choosing an allocation function ---
970 // C++ 5.3.4p8 - 14 & 18
971 // 1) If UseGlobal is true, only look in the global scope. Else, also look
972 // in the scope of the allocated class.
973 // 2) If an array size is given, look for operator new[], else look for
974 // operator new.
975 // 3) The first argument is always size_t. Append the arguments from the
976 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000977
978 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
979 // We don't care about the actual value of this argument.
980 // FIXME: Should the Sema create the expression and embed it in the syntax
981 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000982 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Anders Carlssond67c4c32009-08-16 20:29:29 +0000983 Context.Target.getPointerWidth(0)),
984 Context.getSizeType(),
985 SourceLocation());
986 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000987 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
988
Douglas Gregor6d908702010-02-26 05:06:18 +0000989 // C++ [expr.new]p8:
990 // If the allocated type is a non-array type, the allocation
991 // function’s name is operator new and the deallocation function’s
992 // name is operator delete. If the allocated type is an array
993 // type, the allocation function’s name is operator new[] and the
994 // deallocation function’s name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000995 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
996 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +0000997 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
998 IsArray ? OO_Array_Delete : OO_Delete);
999
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001000 QualType AllocElemType = Context.getBaseElementType(AllocType);
1001
1002 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +00001003 CXXRecordDecl *Record
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001004 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +00001005 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001006 AllocArgs.size(), Record, /*AllowMissing=*/true,
1007 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001008 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001009 }
1010 if (!OperatorNew) {
1011 // Didn't find a member overload. Look for a global one.
1012 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +00001013 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +00001014 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001015 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1016 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001017 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001018 }
1019
John McCall9c82afc2010-04-20 02:18:25 +00001020 // We don't need an operator delete if we're running under
1021 // -fno-exceptions.
1022 if (!getLangOptions().Exceptions) {
1023 OperatorDelete = 0;
1024 return false;
1025 }
1026
Anders Carlssond9583892009-05-31 20:26:12 +00001027 // FindAllocationOverload can change the passed in arguments, so we need to
1028 // copy them back.
1029 if (NumPlaceArgs > 0)
1030 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001031
Douglas Gregor6d908702010-02-26 05:06:18 +00001032 // C++ [expr.new]p19:
1033 //
1034 // If the new-expression begins with a unary :: operator, the
1035 // deallocation function’s name is looked up in the global
1036 // scope. Otherwise, if the allocated type is a class type T or an
1037 // array thereof, the deallocation function’s name is looked up in
1038 // the scope of T. If this lookup fails to find the name, or if
1039 // the allocated type is not a class type or array thereof, the
1040 // deallocation function’s name is looked up in the global scope.
1041 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001042 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001043 CXXRecordDecl *RD
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001044 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6d908702010-02-26 05:06:18 +00001045 LookupQualifiedName(FoundDelete, RD);
1046 }
John McCall90c8c572010-03-18 08:19:33 +00001047 if (FoundDelete.isAmbiguous())
1048 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +00001049
1050 if (FoundDelete.empty()) {
1051 DeclareGlobalNewDelete();
1052 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1053 }
1054
1055 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +00001056
1057 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1058
John McCalledeb6c92010-09-14 21:34:24 +00001059 // Whether we're looking for a placement operator delete is dictated
1060 // by whether we selected a placement operator new, not by whether
1061 // we had explicit placement arguments. This matters for things like
1062 // struct A { void *operator new(size_t, int = 0); ... };
1063 // A *a = new A()
1064 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1065
1066 if (isPlacementNew) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001067 // C++ [expr.new]p20:
1068 // A declaration of a placement deallocation function matches the
1069 // declaration of a placement allocation function if it has the
1070 // same number of parameters and, after parameter transformations
1071 // (8.3.5), all parameter types except the first are
1072 // identical. [...]
1073 //
1074 // To perform this comparison, we compute the function type that
1075 // the deallocation function should have, and use that type both
1076 // for template argument deduction and for comparison purposes.
1077 QualType ExpectedFunctionType;
1078 {
1079 const FunctionProtoType *Proto
1080 = OperatorNew->getType()->getAs<FunctionProtoType>();
1081 llvm::SmallVector<QualType, 4> ArgTypes;
1082 ArgTypes.push_back(Context.VoidPtrTy);
1083 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1084 ArgTypes.push_back(Proto->getArgType(I));
1085
1086 ExpectedFunctionType
1087 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
1088 ArgTypes.size(),
1089 Proto->isVariadic(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001090 0, false, false, 0, 0,
1091 FunctionType::ExtInfo());
Douglas Gregor6d908702010-02-26 05:06:18 +00001092 }
1093
1094 for (LookupResult::iterator D = FoundDelete.begin(),
1095 DEnd = FoundDelete.end();
1096 D != DEnd; ++D) {
1097 FunctionDecl *Fn = 0;
1098 if (FunctionTemplateDecl *FnTmpl
1099 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1100 // Perform template argument deduction to try to match the
1101 // expected function type.
1102 TemplateDeductionInfo Info(Context, StartLoc);
1103 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1104 continue;
1105 } else
1106 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1107
1108 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001109 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001110 }
1111 } else {
1112 // C++ [expr.new]p20:
1113 // [...] Any non-placement deallocation function matches a
1114 // non-placement allocation function. [...]
1115 for (LookupResult::iterator D = FoundDelete.begin(),
1116 DEnd = FoundDelete.end();
1117 D != DEnd; ++D) {
1118 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1119 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001120 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001121 }
1122 }
1123
1124 // C++ [expr.new]p20:
1125 // [...] If the lookup finds a single matching deallocation
1126 // function, that function will be called; otherwise, no
1127 // deallocation function will be called.
1128 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001129 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001130
1131 // C++0x [expr.new]p20:
1132 // If the lookup finds the two-parameter form of a usual
1133 // deallocation function (3.7.4.2) and that function, considered
1134 // as a placement deallocation function, would have been
1135 // selected as a match for the allocation function, the program
1136 // is ill-formed.
1137 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1138 isNonPlacementDeallocationFunction(OperatorDelete)) {
1139 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1140 << SourceRange(PlaceArgs[0]->getLocStart(),
1141 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1142 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1143 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001144 } else {
1145 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001146 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001147 }
1148 }
1149
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001150 return false;
1151}
1152
Sebastian Redl7f662392008-12-04 22:20:51 +00001153/// FindAllocationOverload - Find an fitting overload for the allocation
1154/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001155bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1156 DeclarationName Name, Expr** Args,
1157 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +00001158 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001159 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1160 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001161 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001162 if (AllowMissing)
1163 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001164 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001165 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001166 }
1167
John McCall90c8c572010-03-18 08:19:33 +00001168 if (R.isAmbiguous())
1169 return true;
1170
1171 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001172
John McCall5769d612010-02-08 23:07:23 +00001173 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001174 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1175 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001176 // Even member operator new/delete are implicitly treated as
1177 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001178 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001179
John McCall9aa472c2010-03-19 07:35:19 +00001180 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1181 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001182 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1183 Candidates,
1184 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001185 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001186 }
1187
John McCall9aa472c2010-03-19 07:35:19 +00001188 FunctionDecl *Fn = cast<FunctionDecl>(D);
1189 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001190 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001191 }
1192
1193 // Do the resolution.
1194 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00001195 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001196 case OR_Success: {
1197 // Got one!
1198 FunctionDecl *FnDecl = Best->Function;
1199 // The first argument is size_t, and the first parameter must be size_t,
1200 // too. This is checked on declaration and can be assumed. (It can't be
1201 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001202 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001203 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1204 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
John McCall60d7b3a2010-08-24 06:29:42 +00001205 ExprResult Result
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001206 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001207 Context,
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001208 FnDecl->getParamDecl(i)),
1209 SourceLocation(),
John McCall3fa5cae2010-10-26 07:05:15 +00001210 Owned(Args[i]));
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001211 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001212 return true;
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001213
1214 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001215 }
1216 Operator = FnDecl;
John McCall9aa472c2010-03-19 07:35:19 +00001217 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001218 return false;
1219 }
1220
1221 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +00001222 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001223 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001224 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001225 return true;
1226
1227 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +00001228 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +00001229 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001230 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001231 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001232
1233 case OR_Deleted:
1234 Diag(StartLoc, diag::err_ovl_deleted_call)
1235 << Best->Function->isDeleted()
1236 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001237 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001238 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001239 }
1240 assert(false && "Unreachable, bad result from BestViableFunction");
1241 return true;
1242}
1243
1244
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001245/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1246/// delete. These are:
1247/// @code
1248/// void* operator new(std::size_t) throw(std::bad_alloc);
1249/// void* operator new[](std::size_t) throw(std::bad_alloc);
1250/// void operator delete(void *) throw();
1251/// void operator delete[](void *) throw();
1252/// @endcode
1253/// Note that the placement and nothrow forms of new are *not* implicitly
1254/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001255void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001256 if (GlobalNewDeleteDeclared)
1257 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001258
1259 // C++ [basic.std.dynamic]p2:
1260 // [...] The following allocation and deallocation functions (18.4) are
1261 // implicitly declared in global scope in each translation unit of a
1262 // program
1263 //
1264 // void* operator new(std::size_t) throw(std::bad_alloc);
1265 // void* operator new[](std::size_t) throw(std::bad_alloc);
1266 // void operator delete(void*) throw();
1267 // void operator delete[](void*) throw();
1268 //
1269 // These implicit declarations introduce only the function names operator
1270 // new, operator new[], operator delete, operator delete[].
1271 //
1272 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1273 // "std" or "bad_alloc" as necessary to form the exception specification.
1274 // However, we do not make these implicit declarations visible to name
1275 // lookup.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001276 if (!StdBadAlloc) {
1277 // The "std::bad_alloc" class has not yet been declared, so build it
1278 // implicitly.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001279 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00001280 getOrCreateStdNamespace(),
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001281 SourceLocation(),
1282 &PP.getIdentifierTable().get("bad_alloc"),
1283 SourceLocation(), 0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001284 getStdBadAlloc()->setImplicit(true);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001285 }
1286
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001287 GlobalNewDeleteDeclared = true;
1288
1289 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1290 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001291 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001292
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001293 DeclareGlobalAllocationFunction(
1294 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001295 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001296 DeclareGlobalAllocationFunction(
1297 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001298 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001299 DeclareGlobalAllocationFunction(
1300 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1301 Context.VoidTy, VoidPtr);
1302 DeclareGlobalAllocationFunction(
1303 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1304 Context.VoidTy, VoidPtr);
1305}
1306
1307/// DeclareGlobalAllocationFunction - Declares a single implicit global
1308/// allocation function if it doesn't already exist.
1309void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001310 QualType Return, QualType Argument,
1311 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001312 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1313
1314 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001315 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001316 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001317 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001318 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001319 // Only look at non-template functions, as it is the predefined,
1320 // non-templated allocation function we are trying to declare here.
1321 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1322 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001323 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001324 Func->getParamDecl(0)->getType().getUnqualifiedType());
1325 // FIXME: Do we need to check for default arguments here?
Douglas Gregor7b868622010-08-18 15:06:25 +00001326 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1327 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00001328 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001329 return;
Douglas Gregor7b868622010-08-18 15:06:25 +00001330 }
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001331 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001332 }
1333 }
1334
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001335 QualType BadAllocType;
1336 bool HasBadAllocExceptionSpec
1337 = (Name.getCXXOverloadedOperator() == OO_New ||
1338 Name.getCXXOverloadedOperator() == OO_Array_New);
1339 if (HasBadAllocExceptionSpec) {
1340 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001341 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001342 }
1343
1344 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1345 true, false,
1346 HasBadAllocExceptionSpec? 1 : 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00001347 &BadAllocType,
1348 FunctionType::ExtInfo());
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001349 FunctionDecl *Alloc =
1350 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCalld931b082010-08-26 03:08:43 +00001351 FnType, /*TInfo=*/0, SC_None,
1352 SC_None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001353 Alloc->setImplicit();
Nuno Lopesfc284482009-12-16 16:59:22 +00001354
1355 if (AddMallocAttr)
Sean Huntcf807c42010-08-18 23:23:40 +00001356 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Nuno Lopesfc284482009-12-16 16:59:22 +00001357
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001358 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00001359 0, Argument, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00001360 SC_None,
1361 SC_None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00001362 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001363
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001364 // FIXME: Also add this declaration to the IdentifierResolver, but
1365 // make sure it is at the end of the chain to coincide with the
1366 // global scope.
John McCall5f1e0942010-08-24 08:50:51 +00001367 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001368}
1369
Anders Carlsson78f74552009-11-15 18:45:20 +00001370bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1371 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00001372 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001373 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001374 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001375 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +00001376
John McCalla24dc2e2009-11-17 02:14:36 +00001377 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001378 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001379
Chandler Carruth23893242010-06-28 00:30:51 +00001380 Found.suppressDiagnostics();
1381
John McCall046a7462010-08-04 00:31:26 +00001382 llvm::SmallVector<DeclAccessPair,4> Matches;
Anders Carlsson78f74552009-11-15 18:45:20 +00001383 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1384 F != FEnd; ++F) {
Chandler Carruth09556fd2010-08-08 07:04:00 +00001385 NamedDecl *ND = (*F)->getUnderlyingDecl();
1386
1387 // Ignore template operator delete members from the check for a usual
1388 // deallocation function.
1389 if (isa<FunctionTemplateDecl>(ND))
1390 continue;
1391
1392 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall046a7462010-08-04 00:31:26 +00001393 Matches.push_back(F.getPair());
1394 }
1395
1396 // There's exactly one suitable operator; pick it.
1397 if (Matches.size() == 1) {
1398 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
1399 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1400 Matches[0]);
1401 return false;
1402
1403 // We found multiple suitable operators; complain about the ambiguity.
1404 } else if (!Matches.empty()) {
1405 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1406 << Name << RD;
1407
1408 for (llvm::SmallVectorImpl<DeclAccessPair>::iterator
1409 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1410 Diag((*F)->getUnderlyingDecl()->getLocation(),
1411 diag::note_member_declared_here) << Name;
1412 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001413 }
1414
1415 // We did find operator delete/operator delete[] declarations, but
1416 // none of them were suitable.
1417 if (!Found.empty()) {
1418 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1419 << Name << RD;
1420
1421 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
John McCall046a7462010-08-04 00:31:26 +00001422 F != FEnd; ++F)
1423 Diag((*F)->getUnderlyingDecl()->getLocation(),
1424 diag::note_member_declared_here) << Name;
Anders Carlsson78f74552009-11-15 18:45:20 +00001425
1426 return true;
1427 }
1428
1429 // Look for a global declaration.
1430 DeclareGlobalNewDelete();
1431 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1432
1433 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1434 Expr* DeallocArgs[1];
1435 DeallocArgs[0] = &Null;
1436 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1437 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1438 Operator))
1439 return true;
1440
1441 assert(Operator && "Did not find a deallocation function!");
1442 return false;
1443}
1444
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001445/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1446/// @code ::delete ptr; @endcode
1447/// or
1448/// @code delete [] ptr; @endcode
John McCall60d7b3a2010-08-24 06:29:42 +00001449ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001450Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John McCall9ae2f072010-08-23 23:25:46 +00001451 bool ArrayForm, Expr *Ex) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001452 // C++ [expr.delete]p1:
1453 // The operand shall have a pointer type, or a class type having a single
1454 // conversion function to a pointer type. The result has type void.
1455 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001456 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1457
Anders Carlssond67c4c32009-08-16 20:29:29 +00001458 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001459 bool ArrayFormAsWritten = ArrayForm;
Mike Stump1eb44332009-09-09 15:08:12 +00001460
Sebastian Redl28507842009-02-26 14:39:58 +00001461 if (!Ex->isTypeDependent()) {
1462 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001463
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001464 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor254a9422010-07-29 14:44:35 +00001465 if (RequireCompleteType(StartLoc, Type,
1466 PDiag(diag::err_delete_incomplete_class_type)))
1467 return ExprError();
1468
John McCall32daa422010-03-31 01:36:47 +00001469 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1470
Fariborz Jahanian53462782009-09-11 21:44:33 +00001471 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCall32daa422010-03-31 01:36:47 +00001472 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001473 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001474 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001475 NamedDecl *D = I.getDecl();
1476 if (isa<UsingShadowDecl>(D))
1477 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1478
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001479 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001480 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001481 continue;
1482
John McCall32daa422010-03-31 01:36:47 +00001483 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001484
1485 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1486 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedman13578692010-08-05 02:49:48 +00001487 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001488 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001489 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001490 if (ObjectPtrConversions.size() == 1) {
1491 // We have a single conversion to a pointer-to-object type. Perform
1492 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001493 // TODO: don't redo the conversion calculation.
John McCall32daa422010-03-31 01:36:47 +00001494 if (!PerformImplicitConversion(Ex,
1495 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +00001496 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001497 Type = Ex->getType();
1498 }
1499 }
1500 else if (ObjectPtrConversions.size() > 1) {
1501 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1502 << Type << Ex->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001503 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1504 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001505 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001506 }
Sebastian Redl28507842009-02-26 14:39:58 +00001507 }
1508
Sebastian Redlf53597f2009-03-15 17:47:39 +00001509 if (!Type->isPointerType())
1510 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1511 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001512
Ted Kremenek6217b802009-07-29 21:53:49 +00001513 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor94a61572010-05-24 17:01:56 +00001514 if (Pointee->isVoidType() && !isSFINAEContext()) {
1515 // The C++ standard bans deleting a pointer to a non-object type, which
1516 // effectively bans deletion of "void*". However, most compilers support
1517 // this, so we treat it as a warning unless we're in a SFINAE context.
1518 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1519 << Type << Ex->getSourceRange();
1520 } else if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001521 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1522 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001523 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001524 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +00001525 PDiag(diag::warn_delete_incomplete)
1526 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001527 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +00001528
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001529 // C++ [expr.delete]p2:
1530 // [Note: a pointer to a const type can be the operand of a
1531 // delete-expression; it is not necessary to cast away the constness
1532 // (5.2.11) of the pointer expression before it is used as the operand
1533 // of the delete-expression. ]
1534 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
John McCall2de56d12010-08-25 11:45:40 +00001535 CK_NoOp);
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001536
1537 if (Pointee->isArrayType() && !ArrayForm) {
1538 Diag(StartLoc, diag::warn_delete_array_type)
1539 << Type << Ex->getSourceRange()
1540 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1541 ArrayForm = true;
1542 }
1543
Anders Carlssond67c4c32009-08-16 20:29:29 +00001544 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1545 ArrayForm ? OO_Array_Delete : OO_Delete);
1546
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001547 QualType PointeeElem = Context.getBaseElementType(Pointee);
1548 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001549 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1550
1551 if (!UseGlobal &&
1552 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001553 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001554
Anders Carlsson78f74552009-11-15 18:45:20 +00001555 if (!RD->hasTrivialDestructor())
Douglas Gregor9b623632010-10-12 23:32:35 +00001556 if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001557 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001558 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor9b623632010-10-12 23:32:35 +00001559 DiagnoseUseOfDecl(Dtor, StartLoc);
1560 }
Anders Carlssond67c4c32009-08-16 20:29:29 +00001561 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001562
Anders Carlssond67c4c32009-08-16 20:29:29 +00001563 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001564 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001565 DeclareGlobalNewDelete();
1566 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001567 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +00001568 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001569 OperatorDelete))
1570 return ExprError();
1571 }
Mike Stump1eb44332009-09-09 15:08:12 +00001572
John McCall9c82afc2010-04-20 02:18:25 +00001573 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1574
Sebastian Redl28507842009-02-26 14:39:58 +00001575 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001576 }
1577
Sebastian Redlf53597f2009-03-15 17:47:39 +00001578 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001579 ArrayFormAsWritten, OperatorDelete,
1580 Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001581}
1582
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001583/// \brief Check the use of the given variable as a C++ condition in an if,
1584/// while, do-while, or switch statement.
John McCall60d7b3a2010-08-24 06:29:42 +00001585ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCallf89e55a2010-11-18 06:31:45 +00001586 SourceLocation StmtLoc,
1587 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001588 QualType T = ConditionVar->getType();
1589
1590 // C++ [stmt.select]p2:
1591 // The declarator shall not specify a function or an array.
1592 if (T->isFunctionType())
1593 return ExprError(Diag(ConditionVar->getLocation(),
1594 diag::err_invalid_use_of_function_type)
1595 << ConditionVar->getSourceRange());
1596 else if (T->isArrayType())
1597 return ExprError(Diag(ConditionVar->getLocation(),
1598 diag::err_invalid_use_of_array_type)
1599 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001600
Douglas Gregor586596f2010-05-06 17:25:47 +00001601 Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1602 ConditionVar->getLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00001603 ConditionVar->getType().getNonReferenceType(),
John McCall09431682010-11-18 19:01:18 +00001604 VK_LValue);
Douglas Gregorff331c12010-07-25 18:17:45 +00001605 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc))
Douglas Gregor586596f2010-05-06 17:25:47 +00001606 return ExprError();
Douglas Gregor586596f2010-05-06 17:25:47 +00001607
1608 return Owned(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001609}
1610
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001611/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1612bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1613 // C++ 6.4p4:
1614 // The value of a condition that is an initialized declaration in a statement
1615 // other than a switch statement is the value of the declared variable
1616 // implicitly converted to type bool. If that conversion is ill-formed, the
1617 // program is ill-formed.
1618 // The value of a condition that is an expression is the value of the
1619 // expression, implicitly converted to bool.
1620 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001621 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001622}
Douglas Gregor77a52232008-09-12 00:47:35 +00001623
1624/// Helper function to determine whether this is the (deprecated) C++
1625/// conversion from a string literal to a pointer to non-const char or
1626/// non-const wchar_t (for narrow and wide string literals,
1627/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001628bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001629Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1630 // Look inside the implicit cast, if it exists.
1631 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1632 From = Cast->getSubExpr();
1633
1634 // A string literal (2.13.4) that is not a wide string literal can
1635 // be converted to an rvalue of type "pointer to char"; a wide
1636 // string literal can be converted to an rvalue of type "pointer
1637 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00001638 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00001639 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001640 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001641 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001642 // This conversion is considered only when there is an
1643 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001644 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001645 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1646 (!StrLit->isWide() &&
1647 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1648 ToPointeeType->getKind() == BuiltinType::Char_S))))
1649 return true;
1650 }
1651
1652 return false;
1653}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001654
John McCall60d7b3a2010-08-24 06:29:42 +00001655static ExprResult BuildCXXCastArgument(Sema &S,
John McCall2de56d12010-08-25 11:45:40 +00001656 SourceLocation CastLoc,
1657 QualType Ty,
1658 CastKind Kind,
1659 CXXMethodDecl *Method,
1660 Expr *From) {
Douglas Gregorba70ab62010-04-16 22:17:36 +00001661 switch (Kind) {
1662 default: assert(0 && "Unhandled cast kind!");
John McCall2de56d12010-08-25 11:45:40 +00001663 case CK_ConstructorConversion: {
John McCallca0408f2010-08-23 06:44:23 +00001664 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregorba70ab62010-04-16 22:17:36 +00001665
1666 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
John McCallf312b1e2010-08-26 23:41:50 +00001667 MultiExprArg(&From, 1),
Douglas Gregorba70ab62010-04-16 22:17:36 +00001668 CastLoc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00001669 return ExprError();
Douglas Gregorba70ab62010-04-16 22:17:36 +00001670
John McCall60d7b3a2010-08-24 06:29:42 +00001671 ExprResult Result =
Douglas Gregorba70ab62010-04-16 22:17:36 +00001672 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
John McCall7a1fad32010-08-24 07:32:53 +00001673 move_arg(ConstructorArgs),
Chandler Carruth428edaf2010-10-25 08:47:36 +00001674 /*ZeroInit*/ false, CXXConstructExpr::CK_Complete,
1675 SourceRange());
Douglas Gregorba70ab62010-04-16 22:17:36 +00001676 if (Result.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00001677 return ExprError();
Douglas Gregorba70ab62010-04-16 22:17:36 +00001678
1679 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1680 }
1681
John McCall2de56d12010-08-25 11:45:40 +00001682 case CK_UserDefinedConversion: {
Douglas Gregorba70ab62010-04-16 22:17:36 +00001683 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1684
1685 // Create an implicit call expr that calls it.
1686 // FIXME: pass the FoundDecl for the user-defined conversion here
1687 CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method);
1688 return S.MaybeBindToTemporary(CE);
1689 }
1690 }
1691}
1692
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001693/// PerformImplicitConversion - Perform an implicit conversion of the
1694/// expression From to the type ToType using the pre-computed implicit
1695/// conversion sequence ICS. Returns true if there was an error, false
1696/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001697/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001698/// used in the error message.
1699bool
1700Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1701 const ImplicitConversionSequence &ICS,
Douglas Gregor68647482009-12-16 03:45:30 +00001702 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall1d318332010-01-12 00:44:57 +00001703 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001704 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001705 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001706 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001707 return true;
1708 break;
1709
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001710 case ImplicitConversionSequence::UserDefinedConversion: {
1711
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001712 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCalldaa8e4e2010-11-15 09:13:47 +00001713 CastKind CastKind;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001714 QualType BeforeToType;
1715 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCall2de56d12010-08-25 11:45:40 +00001716 CastKind = CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001717
1718 // If the user-defined conversion is specified by a conversion function,
1719 // the initial standard conversion sequence converts the source type to
1720 // the implicit object parameter of the conversion function.
1721 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCall9ec94452010-12-04 09:57:16 +00001722 } else {
1723 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCall2de56d12010-08-25 11:45:40 +00001724 CastKind = CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001725 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001726 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001727 // If the user-defined conversion is specified by a constructor, the
1728 // initial standard conversion sequence converts the source type to the
1729 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001730 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1731 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001732 }
Douglas Gregora3998bd2010-12-02 21:47:04 +00001733 // Watch 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:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001846 // Nothing to do.
1847 break;
1848
John McCallf6a16482010-12-04 03:47:34 +00001849 case ICK_Lvalue_To_Rvalue:
1850 // Should this get its own ICK?
1851 if (From->getObjectKind() == OK_ObjCProperty) {
1852 ConvertPropertyForRValue(From);
1853 if (!From->isRValue()) break;
1854 }
1855
1856 FromType = FromType.getUnqualifiedType();
1857 From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
1858 From, 0, VK_RValue);
1859 break;
1860
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001861 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001862 FromType = Context.getArrayDecayedType(FromType);
John McCall2de56d12010-08-25 11:45:40 +00001863 ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001864 break;
1865
1866 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001867 FromType = Context.getPointerType(FromType);
John McCall2de56d12010-08-25 11:45:40 +00001868 ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001869 break;
1870
1871 default:
1872 assert(false && "Improper first standard conversion");
1873 break;
1874 }
1875
1876 // Perform the second implicit conversion
1877 switch (SCS.Second) {
1878 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001879 // If both sides are functions (or pointers/references to them), there could
1880 // be incompatible exception declarations.
1881 if (CheckExceptionSpecCompatibility(From, ToType))
1882 return true;
1883 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001884 break;
1885
Douglas Gregor43c79c22009-12-09 00:47:37 +00001886 case ICK_NoReturn_Adjustment:
1887 // If both sides are functions (or pointers/references to them), there could
1888 // be incompatible exception declarations.
1889 if (CheckExceptionSpecCompatibility(From, ToType))
1890 return true;
1891
1892 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
John McCall2de56d12010-08-25 11:45:40 +00001893 CK_NoOp);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001894 break;
1895
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001896 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001897 case ICK_Integral_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00001898 ImpCastExprToType(From, ToType, CK_IntegralCast);
Eli Friedman73c39ab2009-10-20 08:27:19 +00001899 break;
1900
1901 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001902 case ICK_Floating_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00001903 ImpCastExprToType(From, ToType, CK_FloatingCast);
Eli Friedman73c39ab2009-10-20 08:27:19 +00001904 break;
1905
1906 case ICK_Complex_Promotion:
John McCalldaa8e4e2010-11-15 09:13:47 +00001907 case ICK_Complex_Conversion: {
1908 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
1909 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
1910 CastKind CK;
1911 if (FromEl->isRealFloatingType()) {
1912 if (ToEl->isRealFloatingType())
1913 CK = CK_FloatingComplexCast;
1914 else
1915 CK = CK_FloatingComplexToIntegralComplex;
1916 } else if (ToEl->isRealFloatingType()) {
1917 CK = CK_IntegralComplexToFloatingComplex;
1918 } else {
1919 CK = CK_IntegralComplexCast;
1920 }
1921 ImpCastExprToType(From, ToType, CK);
Eli Friedman73c39ab2009-10-20 08:27:19 +00001922 break;
John McCalldaa8e4e2010-11-15 09:13:47 +00001923 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00001924
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001925 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001926 if (ToType->isRealFloatingType())
John McCall2de56d12010-08-25 11:45:40 +00001927 ImpCastExprToType(From, ToType, CK_IntegralToFloating);
Eli Friedman73c39ab2009-10-20 08:27:19 +00001928 else
John McCall2de56d12010-08-25 11:45:40 +00001929 ImpCastExprToType(From, ToType, CK_FloatingToIntegral);
Eli Friedman73c39ab2009-10-20 08:27:19 +00001930 break;
1931
Douglas Gregorf9201e02009-02-11 23:02:49 +00001932 case ICK_Compatible_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00001933 ImpCastExprToType(From, ToType, CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001934 break;
1935
Anders Carlsson61faec12009-09-12 04:46:44 +00001936 case ICK_Pointer_Conversion: {
Douglas Gregora3998bd2010-12-02 21:47:04 +00001937 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001938 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001939 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001940 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00001941 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00001942 << From->getSourceRange();
1943 }
Anders Carlsson61faec12009-09-12 04:46:44 +00001944
John McCalldaa8e4e2010-11-15 09:13:47 +00001945 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00001946 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001947 if (CheckPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001948 return true;
John McCall5baba9d2010-08-25 10:28:54 +00001949 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001950 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001951 }
1952
1953 case ICK_Pointer_Member: {
John McCalldaa8e4e2010-11-15 09:13:47 +00001954 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00001955 CXXCastPath BasePath;
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001956 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath,
1957 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001958 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001959 if (CheckExceptionSpecCompatibility(From, ToType))
1960 return true;
John McCall5baba9d2010-08-25 10:28:54 +00001961 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
Anders Carlsson61faec12009-09-12 04:46:44 +00001962 break;
1963 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001964 case ICK_Boolean_Conversion: {
John McCalldaa8e4e2010-11-15 09:13:47 +00001965 CastKind Kind = CK_Invalid;
1966 switch (FromType->getScalarTypeKind()) {
1967 case Type::STK_Pointer: Kind = CK_PointerToBoolean; break;
1968 case Type::STK_MemberPointer: Kind = CK_MemberPointerToBoolean; break;
1969 case Type::STK_Bool: llvm_unreachable("bool -> bool conversion?");
1970 case Type::STK_Integral: Kind = CK_IntegralToBoolean; break;
1971 case Type::STK_Floating: Kind = CK_FloatingToBoolean; break;
1972 case Type::STK_IntegralComplex: Kind = CK_IntegralComplexToBoolean; break;
1973 case Type::STK_FloatingComplex: Kind = CK_FloatingComplexToBoolean; break;
1974 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001975
1976 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001977 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001978 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001979
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001980 case ICK_Derived_To_Base: {
John McCallf871d0c2010-08-07 06:22:56 +00001981 CXXCastPath BasePath;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001982 if (CheckDerivedToBaseConversion(From->getType(),
1983 ToType.getNonReferenceType(),
1984 From->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001985 From->getSourceRange(),
1986 &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001987 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001988 return true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001989
Sebastian Redl906082e2010-07-20 04:20:21 +00001990 ImpCastExprToType(From, ToType.getNonReferenceType(),
John McCall2de56d12010-08-25 11:45:40 +00001991 CK_DerivedToBase, CastCategory(From),
John McCallf871d0c2010-08-07 06:22:56 +00001992 &BasePath);
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001993 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001994 }
1995
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001996 case ICK_Vector_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00001997 ImpCastExprToType(From, ToType, CK_BitCast);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001998 break;
1999
2000 case ICK_Vector_Splat:
John McCall2de56d12010-08-25 11:45:40 +00002001 ImpCastExprToType(From, ToType, CK_VectorSplat);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002002 break;
2003
2004 case ICK_Complex_Real:
John McCalldaa8e4e2010-11-15 09:13:47 +00002005 // Case 1. x -> _Complex y
2006 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2007 QualType ElType = ToComplex->getElementType();
2008 bool isFloatingComplex = ElType->isRealFloatingType();
2009
2010 // x -> y
2011 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2012 // do nothing
2013 } else if (From->getType()->isRealFloatingType()) {
2014 ImpCastExprToType(From, ElType,
2015 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral);
2016 } else {
2017 assert(From->getType()->isIntegerType());
2018 ImpCastExprToType(From, ElType,
2019 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast);
2020 }
2021 // y -> _Complex y
2022 ImpCastExprToType(From, ToType,
2023 isFloatingComplex ? CK_FloatingRealToComplex
2024 : CK_IntegralRealToComplex);
2025
2026 // Case 2. _Complex x -> y
2027 } else {
2028 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2029 assert(FromComplex);
2030
2031 QualType ElType = FromComplex->getElementType();
2032 bool isFloatingComplex = ElType->isRealFloatingType();
2033
2034 // _Complex x -> x
2035 ImpCastExprToType(From, ElType,
2036 isFloatingComplex ? CK_FloatingComplexToReal
2037 : CK_IntegralComplexToReal);
2038
2039 // x -> y
2040 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2041 // do nothing
2042 } else if (ToType->isRealFloatingType()) {
2043 ImpCastExprToType(From, ToType,
2044 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating);
2045 } else {
2046 assert(ToType->isIntegerType());
2047 ImpCastExprToType(From, ToType,
2048 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast);
2049 }
2050 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002051 break;
2052
2053 case ICK_Lvalue_To_Rvalue:
2054 case ICK_Array_To_Pointer:
2055 case ICK_Function_To_Pointer:
2056 case ICK_Qualification:
2057 case ICK_Num_Conversion_Kinds:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002058 assert(false && "Improper second standard conversion");
2059 break;
2060 }
2061
2062 switch (SCS.Third) {
2063 case ICK_Identity:
2064 // Nothing to do.
2065 break;
2066
Sebastian Redl906082e2010-07-20 04:20:21 +00002067 case ICK_Qualification: {
2068 // The qualification keeps the category of the inner expression, unless the
2069 // target type isn't a reference.
John McCall5baba9d2010-08-25 10:28:54 +00002070 ExprValueKind VK = ToType->isReferenceType() ?
2071 CastCategory(From) : VK_RValue;
Douglas Gregor63982352010-07-13 18:40:04 +00002072 ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
John McCall2de56d12010-08-25 11:45:40 +00002073 CK_NoOp, VK);
Douglas Gregora9bff302010-02-28 18:30:25 +00002074
2075 if (SCS.DeprecatedStringLiteralToCharPtr)
2076 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2077 << ToType.getNonReferenceType();
2078
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002079 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002080 }
2081
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002082 default:
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002083 assert(false && "Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002084 break;
2085 }
2086
2087 return false;
2088}
2089
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002090ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002091 SourceLocation KWLoc,
2092 ParsedType Ty,
2093 SourceLocation RParen) {
2094 TypeSourceInfo *TSInfo;
2095 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002096
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002097 if (!TSInfo)
2098 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002099 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002100}
2101
Sebastian Redlf8aca862010-09-14 23:40:14 +00002102static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT, QualType T,
2103 SourceLocation KeyLoc) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002104 assert(!T->isDependentType() &&
2105 "Cannot evaluate traits for dependent types.");
2106 ASTContext &C = Self.Context;
2107 switch(UTT) {
2108 default: assert(false && "Unknown type trait or not implemented");
2109 case UTT_IsPOD: return T->isPODType();
2110 case UTT_IsLiteral: return T->isLiteralType();
2111 case UTT_IsClass: // Fallthrough
2112 case UTT_IsUnion:
2113 if (const RecordType *Record = T->getAs<RecordType>()) {
2114 bool Union = Record->getDecl()->isUnion();
2115 return UTT == UTT_IsUnion ? Union : !Union;
2116 }
2117 return false;
2118 case UTT_IsEnum: return T->isEnumeralType();
2119 case UTT_IsPolymorphic:
2120 if (const RecordType *Record = T->getAs<RecordType>()) {
2121 // Type traits are only parsed in C++, so we've got CXXRecords.
2122 return cast<CXXRecordDecl>(Record->getDecl())->isPolymorphic();
2123 }
2124 return false;
2125 case UTT_IsAbstract:
2126 if (const RecordType *RT = T->getAs<RecordType>())
2127 return cast<CXXRecordDecl>(RT->getDecl())->isAbstract();
2128 return false;
2129 case UTT_IsEmpty:
2130 if (const RecordType *Record = T->getAs<RecordType>()) {
2131 return !Record->getDecl()->isUnion()
2132 && cast<CXXRecordDecl>(Record->getDecl())->isEmpty();
2133 }
2134 return false;
2135 case UTT_HasTrivialConstructor:
2136 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2137 // If __is_pod (type) is true then the trait is true, else if type is
2138 // a cv class or union type (or array thereof) with a trivial default
2139 // constructor ([class.ctor]) then the trait is true, else it is false.
2140 if (T->isPODType())
2141 return true;
2142 if (const RecordType *RT =
2143 C.getBaseElementType(T)->getAs<RecordType>())
2144 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialConstructor();
2145 return false;
2146 case UTT_HasTrivialCopy:
2147 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2148 // If __is_pod (type) is true or type is a reference type then
2149 // the trait is true, else if type is a cv class or union type
2150 // with a trivial copy constructor ([class.copy]) then the trait
2151 // is true, else it is false.
2152 if (T->isPODType() || T->isReferenceType())
2153 return true;
2154 if (const RecordType *RT = T->getAs<RecordType>())
2155 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2156 return false;
2157 case UTT_HasTrivialAssign:
2158 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2159 // If type is const qualified or is a reference type then the
2160 // trait is false. Otherwise if __is_pod (type) is true then the
2161 // trait is true, else if type is a cv class or union type with
2162 // a trivial copy assignment ([class.copy]) then the trait is
2163 // true, else it is false.
2164 // Note: the const and reference restrictions are interesting,
2165 // given that const and reference members don't prevent a class
2166 // from having a trivial copy assignment operator (but do cause
2167 // errors if the copy assignment operator is actually used, q.v.
2168 // [class.copy]p12).
2169
2170 if (C.getBaseElementType(T).isConstQualified())
2171 return false;
2172 if (T->isPODType())
2173 return true;
2174 if (const RecordType *RT = T->getAs<RecordType>())
2175 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2176 return false;
2177 case UTT_HasTrivialDestructor:
2178 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2179 // If __is_pod (type) is true or type is a reference type
2180 // then the trait is true, else if type is a cv class or union
2181 // type (or array thereof) with a trivial destructor
2182 // ([class.dtor]) then the trait is true, else it is
2183 // false.
2184 if (T->isPODType() || T->isReferenceType())
2185 return true;
2186 if (const RecordType *RT =
2187 C.getBaseElementType(T)->getAs<RecordType>())
2188 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2189 return false;
2190 // TODO: Propagate nothrowness for implicitly declared special members.
2191 case UTT_HasNothrowAssign:
2192 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2193 // If type is const qualified or is a reference type then the
2194 // trait is false. Otherwise if __has_trivial_assign (type)
2195 // is true then the trait is true, else if type is a cv class
2196 // or union type with copy assignment operators that are known
2197 // not to throw an exception then the trait is true, else it is
2198 // false.
2199 if (C.getBaseElementType(T).isConstQualified())
2200 return false;
2201 if (T->isReferenceType())
2202 return false;
2203 if (T->isPODType())
2204 return true;
2205 if (const RecordType *RT = T->getAs<RecordType>()) {
2206 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2207 if (RD->hasTrivialCopyAssignment())
2208 return true;
2209
2210 bool FoundAssign = false;
2211 bool AllNoThrow = true;
2212 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redlf8aca862010-09-14 23:40:14 +00002213 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2214 Sema::LookupOrdinaryName);
2215 if (Self.LookupQualifiedName(Res, RD)) {
2216 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2217 Op != OpEnd; ++Op) {
2218 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2219 if (Operator->isCopyAssignmentOperator()) {
2220 FoundAssign = true;
2221 const FunctionProtoType *CPT
2222 = Operator->getType()->getAs<FunctionProtoType>();
2223 if (!CPT->hasEmptyExceptionSpec()) {
2224 AllNoThrow = false;
2225 break;
2226 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002227 }
2228 }
2229 }
2230
2231 return FoundAssign && AllNoThrow;
2232 }
2233 return false;
2234 case UTT_HasNothrowCopy:
2235 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2236 // If __has_trivial_copy (type) is true then the trait is true, else
2237 // if type is a cv class or union type with copy constructors that are
2238 // known not to throw an exception then the trait is true, else it is
2239 // false.
2240 if (T->isPODType() || T->isReferenceType())
2241 return true;
2242 if (const RecordType *RT = T->getAs<RecordType>()) {
2243 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2244 if (RD->hasTrivialCopyConstructor())
2245 return true;
2246
2247 bool FoundConstructor = false;
2248 bool AllNoThrow = true;
2249 unsigned FoundTQs;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002250 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl5f4e8992010-09-13 21:10:20 +00002251 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002252 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002253 // A template constructor is never a copy constructor.
2254 // FIXME: However, it may actually be selected at the actual overload
2255 // resolution point.
2256 if (isa<FunctionTemplateDecl>(*Con))
2257 continue;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002258 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2259 if (Constructor->isCopyConstructor(FoundTQs)) {
2260 FoundConstructor = true;
2261 const FunctionProtoType *CPT
2262 = Constructor->getType()->getAs<FunctionProtoType>();
Sebastian Redl751025d2010-09-13 22:02:47 +00002263 // TODO: check whether evaluating default arguments can throw.
2264 // For now, we'll be conservative and assume that they can throw.
2265 if (!CPT->hasEmptyExceptionSpec() || CPT->getNumArgs() > 1) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002266 AllNoThrow = false;
2267 break;
2268 }
2269 }
2270 }
2271
2272 return FoundConstructor && AllNoThrow;
2273 }
2274 return false;
2275 case UTT_HasNothrowConstructor:
2276 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2277 // If __has_trivial_constructor (type) is true then the trait is
2278 // true, else if type is a cv class or union type (or array
2279 // thereof) with a default constructor that is known not to
2280 // throw an exception then the trait is true, else it is false.
2281 if (T->isPODType())
2282 return true;
2283 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
2284 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2285 if (RD->hasTrivialConstructor())
2286 return true;
2287
Sebastian Redl751025d2010-09-13 22:02:47 +00002288 DeclContext::lookup_const_iterator Con, ConEnd;
2289 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2290 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002291 // FIXME: In C++0x, a constructor template can be a default constructor.
2292 if (isa<FunctionTemplateDecl>(*Con))
2293 continue;
Sebastian Redl751025d2010-09-13 22:02:47 +00002294 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2295 if (Constructor->isDefaultConstructor()) {
2296 const FunctionProtoType *CPT
2297 = Constructor->getType()->getAs<FunctionProtoType>();
2298 // TODO: check whether evaluating default arguments can throw.
2299 // For now, we'll be conservative and assume that they can throw.
2300 return CPT->hasEmptyExceptionSpec() && CPT->getNumArgs() == 0;
2301 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002302 }
2303 }
2304 return false;
2305 case UTT_HasVirtualDestructor:
2306 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2307 // If type is a class type with a virtual destructor ([class.dtor])
2308 // then the trait is true, else it is false.
2309 if (const RecordType *Record = T->getAs<RecordType>()) {
2310 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redlf8aca862010-09-14 23:40:14 +00002311 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002312 return Destructor->isVirtual();
2313 }
2314 return false;
2315 }
2316}
2317
2318ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002319 SourceLocation KWLoc,
2320 TypeSourceInfo *TSInfo,
2321 SourceLocation RParen) {
2322 QualType T = TSInfo->getType();
2323
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002324 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
2325 // all traits except __is_class, __is_enum and __is_union require a the type
Sebastian Redl607a1782010-09-08 00:48:43 +00002326 // to be complete, an array of unknown bound, or void.
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002327 if (UTT != UTT_IsClass && UTT != UTT_IsEnum && UTT != UTT_IsUnion) {
Sebastian Redl607a1782010-09-08 00:48:43 +00002328 QualType E = T;
2329 if (T->isIncompleteArrayType())
2330 E = Context.getAsArrayType(T)->getElementType();
2331 if (!T->isVoidType() &&
2332 RequireCompleteType(KWLoc, E,
Anders Carlssond497ba72009-08-26 22:59:12 +00002333 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002334 return ExprError();
2335 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00002336
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002337 bool Value = false;
2338 if (!T->isDependentType())
Sebastian Redlf8aca862010-09-14 23:40:14 +00002339 Value = EvaluateUnaryTypeTrait(*this, UTT, T, KWLoc);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002340
2341 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002342 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00002343}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002344
John McCallf89e55a2010-11-18 06:31:45 +00002345QualType Sema::CheckPointerToMemberOperands(Expr *&lex, Expr *&rex,
2346 ExprValueKind &VK,
2347 SourceLocation Loc,
2348 bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002349 const char *OpSpelling = isIndirect ? "->*" : ".*";
2350 // C++ 5.5p2
2351 // The binary operator .* [p3: ->*] binds its second operand, which shall
2352 // be of type "pointer to member of T" (where T is a completely-defined
2353 // class type) [...]
2354 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002355 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00002356 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002357 Diag(Loc, diag::err_bad_memptr_rhs)
2358 << OpSpelling << RType << rex->getSourceRange();
2359 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00002360 }
Douglas Gregore7450f52009-03-24 19:52:54 +00002361
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002362 QualType Class(MemPtr->getClass(), 0);
2363
Douglas Gregor7d520ba2010-10-13 20:41:14 +00002364 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
2365 // member pointer points must be completely-defined. However, there is no
2366 // reason for this semantic distinction, and the rule is not enforced by
2367 // other compilers. Therefore, we do not check this property, as it is
2368 // likely to be considered a defect.
Sebastian Redl59fc2692010-04-10 10:14:54 +00002369
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002370 // C++ 5.5p2
2371 // [...] to its first operand, which shall be of class T or of a class of
2372 // which T is an unambiguous and accessible base class. [p3: a pointer to
2373 // such a class]
2374 QualType LType = lex->getType();
2375 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002376 if (const PointerType *Ptr = LType->getAs<PointerType>())
John McCallf89e55a2010-11-18 06:31:45 +00002377 LType = Ptr->getPointeeType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002378 else {
2379 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00002380 << OpSpelling << 1 << LType
Douglas Gregor849b2432010-03-31 17:46:05 +00002381 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002382 return QualType();
2383 }
2384 }
2385
Douglas Gregora4923eb2009-11-16 21:35:15 +00002386 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00002387 // If we want to check the hierarchy, we need a complete type.
2388 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
2389 << OpSpelling << (int)isIndirect)) {
2390 return QualType();
2391 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002392 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002393 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00002394 // FIXME: Would it be useful to print full ambiguity paths, or is that
2395 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002396 if (!IsDerivedFrom(LType, Class, Paths) ||
2397 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
2398 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00002399 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002400 return QualType();
2401 }
Eli Friedman3005efe2010-01-16 00:00:48 +00002402 // Cast LHS to type of use.
2403 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
John McCall5baba9d2010-08-25 10:28:54 +00002404 ExprValueKind VK =
2405 isIndirect ? VK_RValue : CastCategory(lex);
Sebastian Redl906082e2010-07-20 04:20:21 +00002406
John McCallf871d0c2010-08-07 06:22:56 +00002407 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002408 BuildBasePathArray(Paths, BasePath);
John McCall5baba9d2010-08-25 10:28:54 +00002409 ImpCastExprToType(lex, UseType, CK_DerivedToBase, VK, &BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002410 }
2411
Douglas Gregored8abf12010-07-08 06:14:04 +00002412 if (isa<CXXScalarValueInitExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00002413 // Diagnose use of pointer-to-member type which when used as
2414 // the functional cast in a pointer-to-member expression.
2415 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
2416 return QualType();
2417 }
John McCallf89e55a2010-11-18 06:31:45 +00002418
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002419 // C++ 5.5p2
2420 // The result is an object or a function of the type specified by the
2421 // second operand.
2422 // The cv qualifiers are the union of those in the pointer and the left side,
2423 // in accordance with 5.5p5 and 5.2.5.
2424 // FIXME: This returns a dereferenced member function pointer as a normal
2425 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00002426 // calling them. There's also a GCC extension to get a function pointer to the
2427 // thing, which is another complication, because this type - unlike the type
2428 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002429 // argument.
2430 // We probably need a "MemberFunctionClosureType" or something like that.
2431 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00002432 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
John McCallf89e55a2010-11-18 06:31:45 +00002433
2434 // C++ [expr.mptr.oper]p6:
2435 // The result of a .* expression whose second operand is a pointer
2436 // to a data member is of the same value category as its
2437 // first operand. The result of a .* expression whose second
2438 // operand is a pointer to a member function is a prvalue. The
2439 // result of an ->* expression is an lvalue if its second operand
2440 // is a pointer to data member and a prvalue otherwise.
2441 if (Result->isFunctionType())
2442 VK = VK_RValue;
2443 else if (isIndirect)
2444 VK = VK_LValue;
2445 else
2446 VK = lex->getValueKind();
2447
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002448 return Result;
2449}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002450
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002451/// \brief Try to convert a type to another according to C++0x 5.16p3.
2452///
2453/// This is part of the parameter validation for the ? operator. If either
2454/// value operand is a class type, the two operands are attempted to be
2455/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002456/// It returns true if the program is ill-formed and has already been diagnosed
2457/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002458static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
2459 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00002460 bool &HaveConversion,
2461 QualType &ToType) {
2462 HaveConversion = false;
2463 ToType = To->getType();
2464
2465 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
2466 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002467 // C++0x 5.16p3
2468 // The process for determining whether an operand expression E1 of type T1
2469 // can be converted to match an operand expression E2 of type T2 is defined
2470 // as follows:
2471 // -- If E2 is an lvalue:
John McCall7eb0a9e2010-11-24 05:12:34 +00002472 bool ToIsLvalue = To->isLValue();
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002473 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002474 // E1 can be converted to match E2 if E1 can be implicitly converted to
2475 // type "lvalue reference to T2", subject to the constraint that in the
2476 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002477 QualType T = Self.Context.getLValueReferenceType(ToType);
2478 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2479
2480 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2481 if (InitSeq.isDirectReferenceBinding()) {
2482 ToType = T;
2483 HaveConversion = true;
2484 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002485 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002486
2487 if (InitSeq.isAmbiguous())
2488 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002489 }
John McCallb1bdc622010-02-25 01:37:24 +00002490
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002491 // -- If E2 is an rvalue, or if the conversion above cannot be done:
2492 // -- if E1 and E2 have class type, and the underlying class types are
2493 // the same or one is a base class of the other:
2494 QualType FTy = From->getType();
2495 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002496 const RecordType *FRec = FTy->getAs<RecordType>();
2497 const RecordType *TRec = TTy->getAs<RecordType>();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002498 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
2499 Self.IsDerivedFrom(FTy, TTy);
2500 if (FRec && TRec &&
2501 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002502 // E1 can be converted to match E2 if the class of T2 is the
2503 // same type as, or a base class of, the class of T1, and
2504 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00002505 if (FRec == TRec || FDerivedFromT) {
2506 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002507 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2508 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2509 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2510 HaveConversion = true;
2511 return false;
2512 }
2513
2514 if (InitSeq.isAmbiguous())
2515 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2516 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002517 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002518
2519 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002520 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002521
2522 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2523 // implicitly converted to the type that expression E2 would have
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002524 // if E2 were converted to an rvalue (or the type it has, if E2 is
2525 // an rvalue).
2526 //
2527 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2528 // to the array-to-pointer or function-to-pointer conversions.
2529 if (!TTy->getAs<TagType>())
2530 TTy = TTy.getUnqualifiedType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002531
2532 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2533 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2534 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
2535 ToType = TTy;
2536 if (InitSeq.isAmbiguous())
2537 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2538
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002539 return false;
2540}
2541
2542/// \brief Try to find a common type for two according to C++0x 5.16p5.
2543///
2544/// This is part of the parameter validation for the ? operator. If either
2545/// value operand is a class type, overload resolution is used to find a
2546/// conversion to a common type.
2547static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2548 SourceLocation Loc) {
2549 Expr *Args[2] = { LHS, RHS };
John McCall5769d612010-02-08 23:07:23 +00002550 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor573d9c32009-10-21 23:19:44 +00002551 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002552
2553 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00002554 switch (CandidateSet.BestViableFunction(Self, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002555 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002556 // We found a match. Perform the conversions on the arguments and move on.
2557 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00002558 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002559 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00002560 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002561 break;
2562 return false;
2563
Douglas Gregor20093b42009-12-09 23:02:17 +00002564 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002565 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2566 << LHS->getType() << RHS->getType()
2567 << LHS->getSourceRange() << RHS->getSourceRange();
2568 return true;
2569
Douglas Gregor20093b42009-12-09 23:02:17 +00002570 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002571 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2572 << LHS->getType() << RHS->getType()
2573 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00002574 // FIXME: Print the possible common types by printing the return types of
2575 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002576 break;
2577
Douglas Gregor20093b42009-12-09 23:02:17 +00002578 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002579 assert(false && "Conditional operator has only built-in overloads");
2580 break;
2581 }
2582 return true;
2583}
2584
Sebastian Redl76458502009-04-17 16:30:52 +00002585/// \brief Perform an "extended" implicit conversion as returned by
2586/// TryClassUnification.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002587static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2588 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2589 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2590 SourceLocation());
2591 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
John McCallf312b1e2010-08-26 23:41:50 +00002592 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&E, 1));
Douglas Gregorb70cf442010-03-26 20:14:36 +00002593 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00002594 return true;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002595
2596 E = Result.takeAs<Expr>();
Sebastian Redl76458502009-04-17 16:30:52 +00002597 return false;
2598}
2599
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002600/// \brief Check the operands of ?: under C++ semantics.
2601///
2602/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2603/// extension. In this case, LHS == Cond. (But they're not aliases.)
2604QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
John McCallf89e55a2010-11-18 06:31:45 +00002605 Expr *&SAVE, ExprValueKind &VK,
John McCall09431682010-11-18 19:01:18 +00002606 ExprObjectKind &OK,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002607 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002608 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2609 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002610
2611 // C++0x 5.16p1
2612 // The first expression is contextually converted to bool.
2613 if (!Cond->isTypeDependent()) {
Fariborz Jahanian1fb019b2010-09-18 19:38:38 +00002614 if (SAVE && Cond->getType()->isArrayType()) {
2615 QualType CondTy = Cond->getType();
2616 CondTy = Context.getArrayDecayedType(CondTy);
2617 ImpCastExprToType(Cond, CondTy, CK_ArrayToPointerDecay);
2618 SAVE = LHS = Cond;
2619 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002620 if (CheckCXXBooleanCondition(Cond))
2621 return QualType();
2622 }
2623
John McCallf89e55a2010-11-18 06:31:45 +00002624 // Assume r-value.
2625 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00002626 OK = OK_Ordinary;
John McCallf89e55a2010-11-18 06:31:45 +00002627
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002628 // Either of the arguments dependent?
2629 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2630 return Context.DependentTy;
2631
2632 // C++0x 5.16p2
2633 // If either the second or the third operand has type (cv) void, ...
2634 QualType LTy = LHS->getType();
2635 QualType RTy = RHS->getType();
2636 bool LVoid = LTy->isVoidType();
2637 bool RVoid = RTy->isVoidType();
2638 if (LVoid || RVoid) {
2639 // ... then the [l2r] conversions are performed on the second and third
2640 // operands ...
Douglas Gregora873dfc2010-02-03 00:27:59 +00002641 DefaultFunctionArrayLvalueConversion(LHS);
2642 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002643 LTy = LHS->getType();
2644 RTy = RHS->getType();
2645
2646 // ... and one of the following shall hold:
2647 // -- The second or the third operand (but not both) is a throw-
2648 // expression; the result is of the type of the other and is an rvalue.
2649 bool LThrow = isa<CXXThrowExpr>(LHS);
2650 bool RThrow = isa<CXXThrowExpr>(RHS);
2651 if (LThrow && !RThrow)
2652 return RTy;
2653 if (RThrow && !LThrow)
2654 return LTy;
2655
2656 // -- Both the second and third operands have type void; the result is of
2657 // type void and is an rvalue.
2658 if (LVoid && RVoid)
2659 return Context.VoidTy;
2660
2661 // Neither holds, error.
2662 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2663 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2664 << LHS->getSourceRange() << RHS->getSourceRange();
2665 return QualType();
2666 }
2667
2668 // Neither is void.
2669
2670 // C++0x 5.16p3
2671 // Otherwise, if the second and third operand have different types, and
2672 // either has (cv) class type, and attempt is made to convert each of those
2673 // operands to the other.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002674 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002675 (LTy->isRecordType() || RTy->isRecordType())) {
2676 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2677 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002678 QualType L2RType, R2LType;
2679 bool HaveL2R, HaveR2L;
2680 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002681 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002682 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002683 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002684
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002685 // If both can be converted, [...] the program is ill-formed.
2686 if (HaveL2R && HaveR2L) {
2687 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2688 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2689 return QualType();
2690 }
2691
2692 // If exactly one conversion is possible, that conversion is applied to
2693 // the chosen operand and the converted operands are used in place of the
2694 // original operands for the remainder of this section.
2695 if (HaveL2R) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002696 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002697 return QualType();
2698 LTy = LHS->getType();
2699 } else if (HaveR2L) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002700 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002701 return QualType();
2702 RTy = RHS->getType();
2703 }
2704 }
2705
2706 // C++0x 5.16p4
John McCallf89e55a2010-11-18 06:31:45 +00002707 // If the second and third operands are glvalues of the same value
2708 // category and have the same type, the result is of that type and
2709 // value category and it is a bit-field if the second or the third
2710 // operand is a bit-field, or if both are bit-fields.
John McCall09431682010-11-18 19:01:18 +00002711 // We only extend this to bitfields, not to the crazy other kinds of
2712 // l-values.
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002713 bool Same = Context.hasSameType(LTy, RTy);
John McCallf89e55a2010-11-18 06:31:45 +00002714 if (Same &&
2715 LHS->getValueKind() != VK_RValue &&
2716 LHS->getValueKind() == RHS->getValueKind() &&
John McCall09431682010-11-18 19:01:18 +00002717 (LHS->getObjectKind() == OK_Ordinary ||
2718 LHS->getObjectKind() == OK_BitField) &&
2719 (RHS->getObjectKind() == OK_Ordinary ||
2720 RHS->getObjectKind() == OK_BitField)) {
John McCallf89e55a2010-11-18 06:31:45 +00002721 VK = LHS->getValueKind();
John McCall09431682010-11-18 19:01:18 +00002722 if (LHS->getObjectKind() == OK_BitField ||
2723 RHS->getObjectKind() == OK_BitField)
2724 OK = OK_BitField;
John McCallf89e55a2010-11-18 06:31:45 +00002725 return LTy;
Fariborz Jahanian3911a1a2010-09-25 01:08:05 +00002726 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002727
2728 // C++0x 5.16p5
2729 // Otherwise, the result is an rvalue. If the second and third operands
2730 // do not have the same type, and either has (cv) class type, ...
2731 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2732 // ... overload resolution is used to determine the conversions (if any)
2733 // to be applied to the operands. If the overload resolution fails, the
2734 // program is ill-formed.
2735 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2736 return QualType();
2737 }
2738
2739 // C++0x 5.16p6
2740 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2741 // conversions are performed on the second and third operands.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002742 DefaultFunctionArrayLvalueConversion(LHS);
2743 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002744 LTy = LHS->getType();
2745 RTy = RHS->getType();
2746
2747 // After those conversions, one of the following shall hold:
2748 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00002749 // is of that type. If the operands have class type, the result
2750 // is a prvalue temporary of the result type, which is
2751 // copy-initialized from either the second operand or the third
2752 // operand depending on the value of the first operand.
2753 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
2754 if (LTy->isRecordType()) {
2755 // The operands have class type. Make a temporary copy.
2756 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
John McCall60d7b3a2010-08-24 06:29:42 +00002757 ExprResult LHSCopy = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00002758 SourceLocation(),
2759 Owned(LHS));
Douglas Gregorb65a4582010-05-19 23:40:50 +00002760 if (LHSCopy.isInvalid())
2761 return QualType();
2762
John McCall60d7b3a2010-08-24 06:29:42 +00002763 ExprResult RHSCopy = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00002764 SourceLocation(),
2765 Owned(RHS));
Douglas Gregorb65a4582010-05-19 23:40:50 +00002766 if (RHSCopy.isInvalid())
2767 return QualType();
2768
2769 LHS = LHSCopy.takeAs<Expr>();
2770 RHS = RHSCopy.takeAs<Expr>();
2771 }
2772
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002773 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00002774 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002775
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002776 // Extension: conditional operator involving vector types.
2777 if (LTy->isVectorType() || RTy->isVectorType())
2778 return CheckVectorOperands(QuestionLoc, LHS, RHS);
2779
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002780 // -- The second and third operands have arithmetic or enumeration type;
2781 // the usual arithmetic conversions are performed to bring them to a
2782 // common type, and the result is of that type.
2783 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2784 UsualArithmeticConversions(LHS, RHS);
2785 return LHS->getType();
2786 }
2787
2788 // -- The second and third operands have pointer type, or one has pointer
2789 // type and the other is a null pointer constant; pointer conversions
2790 // and qualification conversions are performed to bring them to their
2791 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00002792 // -- The second and third operands have pointer to member type, or one has
2793 // pointer to member type and the other is a null pointer constant;
2794 // pointer to member conversions and qualification conversions are
2795 // performed to bring them to a common type, whose cv-qualification
2796 // shall match the cv-qualification of either the second or the third
2797 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002798 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002799 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002800 isSFINAEContext()? 0 : &NonStandardCompositeType);
2801 if (!Composite.isNull()) {
2802 if (NonStandardCompositeType)
2803 Diag(QuestionLoc,
2804 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2805 << LTy << RTy << Composite
2806 << LHS->getSourceRange() << RHS->getSourceRange();
2807
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002808 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002809 }
Fariborz Jahanian55016362009-12-10 20:46:08 +00002810
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002811 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00002812 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2813 if (!Composite.isNull())
2814 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002815
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002816 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2817 << LHS->getType() << RHS->getType()
2818 << LHS->getSourceRange() << RHS->getSourceRange();
2819 return QualType();
2820}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002821
2822/// \brief Find a merged pointer type and convert the two expressions to it.
2823///
Douglas Gregor20b3e992009-08-24 17:42:35 +00002824/// This finds the composite pointer type (or member pointer type) for @p E1
2825/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2826/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002827/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002828///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002829/// \param Loc The location of the operator requiring these two expressions to
2830/// be converted to the composite pointer type.
2831///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002832/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2833/// a non-standard (but still sane) composite type to which both expressions
2834/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2835/// will be set true.
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002836QualType Sema::FindCompositePointerType(SourceLocation Loc,
2837 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002838 bool *NonStandardCompositeType) {
2839 if (NonStandardCompositeType)
2840 *NonStandardCompositeType = false;
2841
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002842 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2843 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002844
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00002845 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2846 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00002847 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002848
2849 // C++0x 5.9p2
2850 // Pointer conversions and qualification conversions are performed on
2851 // pointer operands to bring them to their composite pointer type. If
2852 // one operand is a null pointer constant, the composite pointer type is
2853 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00002854 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002855 if (T2->isMemberPointerType())
John McCall2de56d12010-08-25 11:45:40 +00002856 ImpCastExprToType(E1, T2, CK_NullToMemberPointer);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002857 else
John McCall404cd162010-11-13 01:35:44 +00002858 ImpCastExprToType(E1, T2, CK_NullToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002859 return T2;
2860 }
Douglas Gregorce940492009-09-25 04:25:58 +00002861 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002862 if (T1->isMemberPointerType())
John McCall2de56d12010-08-25 11:45:40 +00002863 ImpCastExprToType(E2, T1, CK_NullToMemberPointer);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002864 else
John McCall404cd162010-11-13 01:35:44 +00002865 ImpCastExprToType(E2, T1, CK_NullToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002866 return T1;
2867 }
Mike Stump1eb44332009-09-09 15:08:12 +00002868
Douglas Gregor20b3e992009-08-24 17:42:35 +00002869 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002870 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2871 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002872 return QualType();
2873
2874 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2875 // the other has type "pointer to cv2 T" and the composite pointer type is
2876 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2877 // Otherwise, the composite pointer type is a pointer type similar to the
2878 // type of one of the operands, with a cv-qualification signature that is
2879 // the union of the cv-qualification signatures of the operand types.
2880 // In practice, the first part here is redundant; it's subsumed by the second.
2881 // What we do here is, we build the two possible composite types, and try the
2882 // conversions in both directions. If only one works, or if the two composite
2883 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00002884 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00002885 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2886 QualifierVector QualifierUnion;
2887 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2888 ContainingClassVector;
2889 ContainingClassVector MemberOfClass;
2890 QualType Composite1 = Context.getCanonicalType(T1),
2891 Composite2 = Context.getCanonicalType(T2);
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002892 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00002893 do {
2894 const PointerType *Ptr1, *Ptr2;
2895 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2896 (Ptr2 = Composite2->getAs<PointerType>())) {
2897 Composite1 = Ptr1->getPointeeType();
2898 Composite2 = Ptr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002899
2900 // If we're allowed to create a non-standard composite type, keep track
2901 // of where we need to fill in additional 'const' qualifiers.
2902 if (NonStandardCompositeType &&
2903 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2904 NeedConstBefore = QualifierUnion.size();
2905
Douglas Gregor20b3e992009-08-24 17:42:35 +00002906 QualifierUnion.push_back(
2907 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2908 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2909 continue;
2910 }
Mike Stump1eb44332009-09-09 15:08:12 +00002911
Douglas Gregor20b3e992009-08-24 17:42:35 +00002912 const MemberPointerType *MemPtr1, *MemPtr2;
2913 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2914 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2915 Composite1 = MemPtr1->getPointeeType();
2916 Composite2 = MemPtr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002917
2918 // If we're allowed to create a non-standard composite type, keep track
2919 // of where we need to fill in additional 'const' qualifiers.
2920 if (NonStandardCompositeType &&
2921 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2922 NeedConstBefore = QualifierUnion.size();
2923
Douglas Gregor20b3e992009-08-24 17:42:35 +00002924 QualifierUnion.push_back(
2925 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2926 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2927 MemPtr2->getClass()));
2928 continue;
2929 }
Mike Stump1eb44332009-09-09 15:08:12 +00002930
Douglas Gregor20b3e992009-08-24 17:42:35 +00002931 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00002932
Douglas Gregor20b3e992009-08-24 17:42:35 +00002933 // Cannot unwrap any more types.
2934 break;
2935 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00002936
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002937 if (NeedConstBefore && NonStandardCompositeType) {
2938 // Extension: Add 'const' to qualifiers that come before the first qualifier
2939 // mismatch, so that our (non-standard!) composite type meets the
2940 // requirements of C++ [conv.qual]p4 bullet 3.
2941 for (unsigned I = 0; I != NeedConstBefore; ++I) {
2942 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
2943 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
2944 *NonStandardCompositeType = true;
2945 }
2946 }
2947 }
2948
Douglas Gregor20b3e992009-08-24 17:42:35 +00002949 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002950 ContainingClassVector::reverse_iterator MOC
2951 = MemberOfClass.rbegin();
2952 for (QualifierVector::reverse_iterator
2953 I = QualifierUnion.rbegin(),
2954 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00002955 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00002956 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002957 if (MOC->first && MOC->second) {
2958 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00002959 Composite1 = Context.getMemberPointerType(
2960 Context.getQualifiedType(Composite1, Quals),
2961 MOC->first);
2962 Composite2 = Context.getMemberPointerType(
2963 Context.getQualifiedType(Composite2, Quals),
2964 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002965 } else {
2966 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00002967 Composite1
2968 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2969 Composite2
2970 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00002971 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002972 }
2973
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002974 // Try to convert to the first composite pointer type.
2975 InitializedEntity Entity1
2976 = InitializedEntity::InitializeTemporary(Composite1);
2977 InitializationKind Kind
2978 = InitializationKind::CreateCopy(Loc, SourceLocation());
2979 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
2980 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00002981
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002982 if (E1ToC1 && E2ToC1) {
2983 // Conversion to Composite1 is viable.
2984 if (!Context.hasSameType(Composite1, Composite2)) {
2985 // Composite2 is a different type from Composite1. Check whether
2986 // Composite2 is also viable.
2987 InitializedEntity Entity2
2988 = InitializedEntity::InitializeTemporary(Composite2);
2989 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2990 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2991 if (E1ToC2 && E2ToC2) {
2992 // Both Composite1 and Composite2 are viable and are different;
2993 // this is an ambiguity.
2994 return QualType();
2995 }
2996 }
2997
2998 // Convert E1 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00002999 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00003000 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003001 if (E1Result.isInvalid())
3002 return QualType();
3003 E1 = E1Result.takeAs<Expr>();
3004
3005 // Convert E2 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00003006 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00003007 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003008 if (E2Result.isInvalid())
3009 return QualType();
3010 E2 = E2Result.takeAs<Expr>();
3011
3012 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003013 }
3014
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003015 // Check whether Composite2 is viable.
3016 InitializedEntity Entity2
3017 = InitializedEntity::InitializeTemporary(Composite2);
3018 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3019 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3020 if (!E1ToC2 || !E2ToC2)
3021 return QualType();
3022
3023 // Convert E1 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00003024 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00003025 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003026 if (E1Result.isInvalid())
3027 return QualType();
3028 E1 = E1Result.takeAs<Expr>();
3029
3030 // Convert E2 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00003031 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00003032 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003033 if (E2Result.isInvalid())
3034 return QualType();
3035 E2 = E2Result.takeAs<Expr>();
3036
3037 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003038}
Anders Carlsson165a0a02009-05-17 18:41:29 +00003039
John McCall60d7b3a2010-08-24 06:29:42 +00003040ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor19cc1c72010-11-01 21:10:29 +00003041 if (!E)
3042 return ExprError();
3043
Anders Carlsson089c2602009-08-15 23:41:35 +00003044 if (!Context.getLangOptions().CPlusPlus)
3045 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003046
Douglas Gregor51326552009-12-24 18:51:59 +00003047 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
3048
Ted Kremenek6217b802009-07-29 21:53:49 +00003049 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00003050 if (!RT)
3051 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003052
Anders Carlsson0ea4dfd2010-07-16 21:18:37 +00003053 // If this is the result of a call or an Objective-C message send expression,
3054 // our source might actually be a reference, in which case we shouldn't bind.
Anders Carlsson283e4d52009-09-14 01:30:44 +00003055 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
Anders Carlsson0ea4dfd2010-07-16 21:18:37 +00003056 if (CE->getCallReturnType()->isReferenceType())
Anders Carlsson283e4d52009-09-14 01:30:44 +00003057 return Owned(E);
Anders Carlsson0ea4dfd2010-07-16 21:18:37 +00003058 } else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
3059 if (const ObjCMethodDecl *MD = ME->getMethodDecl()) {
3060 if (MD->getResultType()->isReferenceType())
3061 return Owned(E);
3062 }
Anders Carlsson283e4d52009-09-14 01:30:44 +00003063 }
John McCall86ff3082010-02-04 22:26:26 +00003064
3065 // That should be enough to guarantee that this type is complete.
3066 // If it has a trivial destructor, we can avoid the extra copy.
3067 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall507384f2010-08-12 02:40:37 +00003068 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall86ff3082010-02-04 22:26:26 +00003069 return Owned(E);
3070
Douglas Gregordb89f282010-07-01 22:47:18 +00003071 CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD));
Anders Carlsson860306e2009-05-30 21:21:49 +00003072 ExprTemporaries.push_back(Temp);
Douglas Gregordb89f282010-07-01 22:47:18 +00003073 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003074 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00003075 CheckDestructorAccess(E->getExprLoc(), Destructor,
3076 PDiag(diag::err_access_dtor_temp)
3077 << E->getType());
3078 }
Anders Carlssondef11992009-05-30 20:36:53 +00003079 // FIXME: Add the temporary to the temporaries vector.
3080 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
3081}
3082
Anders Carlsson0ece4912009-12-15 20:51:39 +00003083Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003084 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00003085
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00003086 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3087 assert(ExprTemporaries.size() >= FirstTemporary);
3088 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003089 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003090
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003091 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00003092 &ExprTemporaries[FirstTemporary],
Anders Carlsson0ece4912009-12-15 20:51:39 +00003093 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00003094 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
3095 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00003096
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003097 return E;
3098}
3099
John McCall60d7b3a2010-08-24 06:29:42 +00003100ExprResult
3101Sema::MaybeCreateCXXExprWithTemporaries(ExprResult SubExpr) {
Douglas Gregor90f93822009-12-22 22:17:25 +00003102 if (SubExpr.isInvalid())
3103 return ExprError();
3104
3105 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
3106}
3107
Anders Carlsson5ee56e92009-12-16 02:09:40 +00003108FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
3109 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3110 assert(ExprTemporaries.size() >= FirstTemporary);
3111
3112 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
3113 CXXTemporary **Temporaries =
3114 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
3115
3116 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
3117
3118 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
3119 ExprTemporaries.end());
3120
3121 return E;
3122}
3123
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003124Stmt *Sema::MaybeCreateCXXStmtWithTemporaries(Stmt *SubStmt) {
3125 assert(SubStmt && "sub statement can't be null!");
3126
3127 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3128 assert(ExprTemporaries.size() >= FirstTemporary);
3129 if (ExprTemporaries.size() == FirstTemporary)
3130 return SubStmt;
3131
3132 // FIXME: In order to attach the temporaries, wrap the statement into
3133 // a StmtExpr; currently this is only used for asm statements.
3134 // This is hacky, either create a new CXXStmtWithTemporaries statement or
3135 // a new AsmStmtWithTemporaries.
3136 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
3137 SourceLocation(),
3138 SourceLocation());
3139 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
3140 SourceLocation());
3141 return MaybeCreateCXXExprWithTemporaries(E);
3142}
3143
John McCall60d7b3a2010-08-24 06:29:42 +00003144ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003145Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallb3d87482010-08-24 05:47:05 +00003146 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00003147 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003148 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003149 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003150 if (Result.isInvalid()) return ExprError();
3151 Base = Result.get();
Mike Stump1eb44332009-09-09 15:08:12 +00003152
John McCall9ae2f072010-08-23 23:25:46 +00003153 QualType BaseType = Base->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00003154 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003155 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00003156 // If we have a pointer to a dependent type and are using the -> operator,
3157 // the object type is the type that the pointer points to. We might still
3158 // have enough information about that type to do something useful.
3159 if (OpKind == tok::arrow)
3160 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3161 BaseType = Ptr->getPointeeType();
3162
John McCallb3d87482010-08-24 05:47:05 +00003163 ObjectType = ParsedType::make(BaseType);
Douglas Gregord4dca082010-02-24 18:44:31 +00003164 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00003165 return Owned(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003166 }
Mike Stump1eb44332009-09-09 15:08:12 +00003167
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003168 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00003169 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003170 // returned, with the original second operand.
3171 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00003172 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00003173 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00003174 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00003175 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00003176
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003177 while (BaseType->isRecordType()) {
John McCall9ae2f072010-08-23 23:25:46 +00003178 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
3179 if (Result.isInvalid())
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003180 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00003181 Base = Result.get();
3182 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonde699e52009-10-13 22:55:59 +00003183 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCall9ae2f072010-08-23 23:25:46 +00003184 BaseType = Base->getType();
John McCallc4e83212009-09-30 01:01:30 +00003185 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00003186 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00003187 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00003188 for (unsigned i = 0; i < Locations.size(); i++)
3189 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00003190 return ExprError();
3191 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003192 }
Mike Stump1eb44332009-09-09 15:08:12 +00003193
Douglas Gregor31658df2009-11-20 19:58:21 +00003194 if (BaseType->isPointerType())
3195 BaseType = BaseType->getPointeeType();
3196 }
Mike Stump1eb44332009-09-09 15:08:12 +00003197
3198 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003199 // vector types or Objective-C interfaces. Just return early and let
3200 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00003201 if (!BaseType->isRecordType()) {
3202 // C++ [basic.lookup.classref]p2:
3203 // [...] If the type of the object expression is of pointer to scalar
3204 // type, the unqualified-id is looked up in the context of the complete
3205 // postfix-expression.
Douglas Gregord4dca082010-02-24 18:44:31 +00003206 //
3207 // This also indicates that we should be parsing a
3208 // pseudo-destructor-name.
John McCallb3d87482010-08-24 05:47:05 +00003209 ObjectType = ParsedType();
Douglas Gregord4dca082010-02-24 18:44:31 +00003210 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00003211 return Owned(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00003212 }
Mike Stump1eb44332009-09-09 15:08:12 +00003213
Douglas Gregor03c57052009-11-17 05:17:33 +00003214 // The object type must be complete (or dependent).
3215 if (!BaseType->isDependentType() &&
3216 RequireCompleteType(OpLoc, BaseType,
3217 PDiag(diag::err_incomplete_member_access)))
3218 return ExprError();
3219
Douglas Gregorc68afe22009-09-03 21:38:09 +00003220 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00003221 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00003222 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00003223 // type C (or of pointer to a class type C), the unqualified-id is looked
3224 // up in the scope of class C. [...]
John McCallb3d87482010-08-24 05:47:05 +00003225 ObjectType = ParsedType::make(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00003226 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003227}
3228
John McCall60d7b3a2010-08-24 06:29:42 +00003229ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003230 Expr *MemExpr) {
Douglas Gregor77549082010-02-24 21:29:12 +00003231 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCall9ae2f072010-08-23 23:25:46 +00003232 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
3233 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregor849b2432010-03-31 17:46:05 +00003234 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
Douglas Gregor77549082010-02-24 21:29:12 +00003235
3236 return ActOnCallExpr(/*Scope*/ 0,
John McCall9ae2f072010-08-23 23:25:46 +00003237 MemExpr,
Douglas Gregor77549082010-02-24 21:29:12 +00003238 /*LPLoc*/ ExpectedLParenLoc,
John McCallf312b1e2010-08-26 23:41:50 +00003239 MultiExprArg(),
Douglas Gregor77549082010-02-24 21:29:12 +00003240 /*RPLoc*/ ExpectedLParenLoc);
3241}
Douglas Gregord4dca082010-02-24 18:44:31 +00003242
John McCall60d7b3a2010-08-24 06:29:42 +00003243ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003244 SourceLocation OpLoc,
3245 tok::TokenKind OpKind,
3246 const CXXScopeSpec &SS,
Douglas Gregor26d4ac92010-02-24 23:40:28 +00003247 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003248 SourceLocation CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00003249 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003250 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003251 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003252 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
Douglas Gregorb57fb492010-02-24 22:38:50 +00003253
3254 // C++ [expr.pseudo]p2:
3255 // The left-hand side of the dot operator shall be of scalar type. The
3256 // left-hand side of the arrow operator shall be of pointer to scalar type.
3257 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00003258 QualType ObjectType = Base->getType();
Douglas Gregorb57fb492010-02-24 22:38:50 +00003259 if (OpKind == tok::arrow) {
3260 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3261 ObjectType = Ptr->getPointeeType();
John McCall9ae2f072010-08-23 23:25:46 +00003262 } else if (!Base->isTypeDependent()) {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003263 // The user wrote "p->" when she probably meant "p."; fix it.
3264 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3265 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00003266 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb57fb492010-02-24 22:38:50 +00003267 if (isSFINAEContext())
3268 return ExprError();
3269
3270 OpKind = tok::period;
3271 }
3272 }
3273
3274 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
3275 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
John McCall9ae2f072010-08-23 23:25:46 +00003276 << ObjectType << Base->getSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00003277 return ExprError();
3278 }
3279
3280 // C++ [expr.pseudo]p2:
3281 // [...] The cv-unqualified versions of the object type and of the type
3282 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003283 if (DestructedTypeInfo) {
3284 QualType DestructedType = DestructedTypeInfo->getType();
3285 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003286 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003287 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
3288 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
3289 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00003290 << ObjectType << DestructedType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003291 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003292
3293 // Recover by setting the destructed type to the object type.
3294 DestructedType = ObjectType;
3295 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
3296 DestructedTypeStart);
3297 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3298 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00003299 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003300
Douglas Gregorb57fb492010-02-24 22:38:50 +00003301 // C++ [expr.pseudo]p2:
3302 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
3303 // form
3304 //
3305 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
3306 //
3307 // shall designate the same scalar type.
3308 if (ScopeTypeInfo) {
3309 QualType ScopeType = ScopeTypeInfo->getType();
3310 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00003311 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003312
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003313 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00003314 diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00003315 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003316 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00003317
3318 ScopeType = QualType();
3319 ScopeTypeInfo = 0;
3320 }
3321 }
3322
John McCall9ae2f072010-08-23 23:25:46 +00003323 Expr *Result
3324 = new (Context) CXXPseudoDestructorExpr(Context, Base,
3325 OpKind == tok::arrow, OpLoc,
3326 SS.getScopeRep(), SS.getRange(),
3327 ScopeTypeInfo,
3328 CCLoc,
3329 TildeLoc,
3330 Destructed);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003331
Douglas Gregorb57fb492010-02-24 22:38:50 +00003332 if (HasTrailingLParen)
John McCall9ae2f072010-08-23 23:25:46 +00003333 return Owned(Result);
Douglas Gregorb57fb492010-02-24 22:38:50 +00003334
John McCall9ae2f072010-08-23 23:25:46 +00003335 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor77549082010-02-24 21:29:12 +00003336}
3337
John McCall60d7b3a2010-08-24 06:29:42 +00003338ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
Douglas Gregor77549082010-02-24 21:29:12 +00003339 SourceLocation OpLoc,
3340 tok::TokenKind OpKind,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003341 CXXScopeSpec &SS,
Douglas Gregor77549082010-02-24 21:29:12 +00003342 UnqualifiedId &FirstTypeName,
3343 SourceLocation CCLoc,
3344 SourceLocation TildeLoc,
3345 UnqualifiedId &SecondTypeName,
3346 bool HasTrailingLParen) {
3347 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3348 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3349 "Invalid first type name in pseudo-destructor");
3350 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3351 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3352 "Invalid second type name in pseudo-destructor");
3353
Douglas Gregor77549082010-02-24 21:29:12 +00003354 // C++ [expr.pseudo]p2:
3355 // The left-hand side of the dot operator shall be of scalar type. The
3356 // left-hand side of the arrow operator shall be of pointer to scalar type.
3357 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00003358 QualType ObjectType = Base->getType();
Douglas Gregor77549082010-02-24 21:29:12 +00003359 if (OpKind == tok::arrow) {
3360 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3361 ObjectType = Ptr->getPointeeType();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003362 } else if (!ObjectType->isDependentType()) {
Douglas Gregor77549082010-02-24 21:29:12 +00003363 // The user wrote "p->" when she probably meant "p."; fix it.
3364 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003365 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00003366 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor77549082010-02-24 21:29:12 +00003367 if (isSFINAEContext())
3368 return ExprError();
3369
3370 OpKind = tok::period;
3371 }
3372 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003373
3374 // Compute the object type that we should use for name lookup purposes. Only
3375 // record types and dependent types matter.
John McCallb3d87482010-08-24 05:47:05 +00003376 ParsedType ObjectTypePtrForLookup;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003377 if (!SS.isSet()) {
John McCallb3d87482010-08-24 05:47:05 +00003378 if (const Type *T = ObjectType->getAs<RecordType>())
3379 ObjectTypePtrForLookup = ParsedType::make(QualType(T, 0));
3380 else if (ObjectType->isDependentType())
3381 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003382 }
Douglas Gregor77549082010-02-24 21:29:12 +00003383
Douglas Gregorb57fb492010-02-24 22:38:50 +00003384 // Convert the name of the type being destructed (following the ~) into a
3385 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00003386 QualType DestructedType;
3387 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003388 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00003389 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
John McCallb3d87482010-08-24 05:47:05 +00003390 ParsedType T = getTypeName(*SecondTypeName.Identifier,
3391 SecondTypeName.StartLocation,
3392 S, &SS, true, ObjectTypePtrForLookup);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003393 if (!T &&
3394 ((SS.isSet() && !computeDeclContext(SS, false)) ||
3395 (!SS.isSet() && ObjectType->isDependentType()))) {
3396 // The name of the type being destroyed is a dependent name, and we
3397 // couldn't find anything useful in scope. Just store the identifier and
3398 // it's location, and we'll perform (qualified) name lookup again at
3399 // template instantiation time.
3400 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
3401 SecondTypeName.StartLocation);
3402 } else if (!T) {
Douglas Gregor77549082010-02-24 21:29:12 +00003403 Diag(SecondTypeName.StartLocation,
3404 diag::err_pseudo_dtor_destructor_non_type)
3405 << SecondTypeName.Identifier << ObjectType;
3406 if (isSFINAEContext())
3407 return ExprError();
3408
3409 // Recover by assuming we had the right type all along.
3410 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003411 } else
Douglas Gregor77549082010-02-24 21:29:12 +00003412 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003413 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003414 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00003415 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003416 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3417 TemplateId->getTemplateArgs(),
3418 TemplateId->NumArgs);
John McCall2b5289b2010-08-23 07:28:44 +00003419 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003420 TemplateId->TemplateNameLoc,
3421 TemplateId->LAngleLoc,
3422 TemplateArgsPtr,
3423 TemplateId->RAngleLoc);
3424 if (T.isInvalid() || !T.get()) {
3425 // Recover by assuming we had the right type all along.
3426 DestructedType = ObjectType;
3427 } else
3428 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003429 }
3430
Douglas Gregorb57fb492010-02-24 22:38:50 +00003431 // If we've performed some kind of recovery, (re-)build the type source
3432 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003433 if (!DestructedType.isNull()) {
3434 if (!DestructedTypeInfo)
3435 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003436 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003437 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3438 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00003439
3440 // Convert the name of the scope type (the type prior to '::') into a type.
3441 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00003442 QualType ScopeType;
3443 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3444 FirstTypeName.Identifier) {
3445 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
John McCallb3d87482010-08-24 05:47:05 +00003446 ParsedType T = getTypeName(*FirstTypeName.Identifier,
3447 FirstTypeName.StartLocation,
3448 S, &SS, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00003449 if (!T) {
3450 Diag(FirstTypeName.StartLocation,
3451 diag::err_pseudo_dtor_destructor_non_type)
3452 << FirstTypeName.Identifier << ObjectType;
Douglas Gregor77549082010-02-24 21:29:12 +00003453
Douglas Gregorb57fb492010-02-24 22:38:50 +00003454 if (isSFINAEContext())
3455 return ExprError();
3456
3457 // Just drop this type. It's unnecessary anyway.
3458 ScopeType = QualType();
3459 } else
3460 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003461 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003462 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00003463 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003464 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3465 TemplateId->getTemplateArgs(),
3466 TemplateId->NumArgs);
John McCall2b5289b2010-08-23 07:28:44 +00003467 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003468 TemplateId->TemplateNameLoc,
3469 TemplateId->LAngleLoc,
3470 TemplateArgsPtr,
3471 TemplateId->RAngleLoc);
3472 if (T.isInvalid() || !T.get()) {
3473 // Recover by dropping this type.
3474 ScopeType = QualType();
3475 } else
3476 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003477 }
3478 }
Douglas Gregorb4a418f2010-02-24 23:02:30 +00003479
3480 if (!ScopeType.isNull() && !ScopeTypeInfo)
3481 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
3482 FirstTypeName.StartLocation);
3483
3484
John McCall9ae2f072010-08-23 23:25:46 +00003485 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00003486 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003487 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00003488}
3489
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003490CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
John McCall6bb80172010-03-30 21:47:33 +00003491 NamedDecl *FoundDecl,
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003492 CXXMethodDecl *Method) {
John McCall6bb80172010-03-30 21:47:33 +00003493 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
3494 FoundDecl, Method))
Eli Friedman772fffa2009-12-09 04:53:56 +00003495 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
3496
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003497 MemberExpr *ME =
Abramo Bagnara25777432010-08-11 22:01:17 +00003498 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
John McCallf89e55a2010-11-18 06:31:45 +00003499 SourceLocation(), Method->getType(),
3500 VK_RValue, OK_Ordinary);
3501 QualType ResultType = Method->getResultType();
3502 ExprValueKind VK = Expr::getValueKindForType(ResultType);
3503 ResultType = ResultType.getNonLValueExprType(Context);
3504
Douglas Gregor7edfb692009-11-23 12:27:39 +00003505 MarkDeclarationReferenced(Exp->getLocStart(), Method);
3506 CXXMemberCallExpr *CE =
John McCallf89e55a2010-11-18 06:31:45 +00003507 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
Douglas Gregor7edfb692009-11-23 12:27:39 +00003508 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003509 return CE;
3510}
3511
Sebastian Redl2e156222010-09-10 20:55:43 +00003512ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
3513 SourceLocation RParen) {
Sebastian Redl2e156222010-09-10 20:55:43 +00003514 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
3515 Operand->CanThrow(Context),
3516 KeyLoc, RParen));
3517}
3518
3519ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
3520 Expr *Operand, SourceLocation RParen) {
3521 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl02bc21a2010-09-10 20:55:37 +00003522}
3523
John McCallf6a16482010-12-04 03:47:34 +00003524/// Perform the conversions required for an expression used in a
3525/// context that ignores the result.
3526void Sema::IgnoredValueConversions(Expr *&E) {
John McCalla878cda2010-12-02 02:07:15 +00003527 // C99 6.3.2.1:
3528 // [Except in specific positions,] an lvalue that does not have
3529 // array type is converted to the value stored in the
3530 // designated object (and is no longer an lvalue).
John McCallf6a16482010-12-04 03:47:34 +00003531 if (E->isRValue()) return;
John McCalla878cda2010-12-02 02:07:15 +00003532
John McCallf6a16482010-12-04 03:47:34 +00003533 // We always want to do this on ObjC property references.
3534 if (E->getObjectKind() == OK_ObjCProperty) {
3535 ConvertPropertyForRValue(E);
3536 if (E->isRValue()) return;
3537 }
3538
3539 // Otherwise, this rule does not apply in C++, at least not for the moment.
3540 if (getLangOptions().CPlusPlus) return;
3541
3542 // GCC seems to also exclude expressions of incomplete enum type.
3543 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
3544 if (!T->getDecl()->isComplete()) {
3545 // FIXME: stupid workaround for a codegen bug!
3546 ImpCastExprToType(E, Context.VoidTy, CK_ToVoid);
3547 return;
3548 }
3549 }
3550
3551 DefaultFunctionArrayLvalueConversion(E);
John McCall85515d62010-12-04 12:29:11 +00003552 if (!E->getType()->isVoidType())
3553 RequireCompleteType(E->getExprLoc(), E->getType(),
3554 diag::err_incomplete_type);
John McCallf6a16482010-12-04 03:47:34 +00003555}
3556
3557ExprResult Sema::ActOnFinishFullExpr(Expr *FullExpr) {
3558 if (!FullExpr) return ExprError();
3559
3560 IgnoredValueConversions(FullExpr);
John McCallb4eb64d2010-10-08 02:01:28 +00003561 CheckImplicitConversions(FullExpr);
John McCall9ae2f072010-08-23 23:25:46 +00003562 return MaybeCreateCXXExprWithTemporaries(FullExpr);
Anders Carlsson165a0a02009-05-17 18:41:29 +00003563}
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003564
3565StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
3566 if (!FullStmt) return StmtError();
3567
3568 return MaybeCreateCXXStmtWithTemporaries(FullStmt);
3569}