blob: 7bc9af1191e66a192d571c8d5360d7c8cc6bc01c [file] [log] [blame]
Chris Lattner29375652006-12-04 18:06:35 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner29375652006-12-04 18:06:35 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall19c1bfd2010-08-25 05:32:35 +000015#include "clang/Sema/DeclSpec.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000016#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
John McCall19c1bfd2010-08-25 05:32:35 +000018#include "clang/Sema/ParsedTemplate.h"
19#include "clang/Sema/TemplateDeduction.h"
Steve Naroffaac94152007-08-25 14:02:58 +000020#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000021#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000023#include "clang/AST/ExprCXX.h"
Fariborz Jahanian1d446082010-06-16 18:56:04 +000024#include "clang/AST/ExprObjC.h"
Douglas Gregorb1dd23f2010-02-24 22:38:50 +000025#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000026#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlfaf68082008-12-03 20:26:15 +000027#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000028#include "clang/Lex/Preprocessor.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000029#include "llvm/ADT/STLExtras.h"
Chris Lattner29375652006-12-04 18:06:35 +000030using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000031using namespace sema;
Chris Lattner29375652006-12-04 18:06:35 +000032
John McCallba7bf592010-08-24 05:47:05 +000033ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000034 IdentifierInfo &II,
John McCallba7bf592010-08-24 05:47:05 +000035 SourceLocation NameLoc,
36 Scope *S, CXXScopeSpec &SS,
37 ParsedType ObjectTypePtr,
38 bool EnteringContext) {
Douglas Gregorfe17d252010-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 Gregor46841e12010-02-23 00:15:22 +000058 // See also PR6358 and PR6359.
Sebastian Redla771d222010-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 Gregorfe17d252010-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 Gregor46841e12010-02-23 00:15:22 +000073 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000074
Douglas Gregor46841e12010-02-23 00:15:22 +000075 bool AlreadySearched = false;
76 bool LookAtPrefix = true;
Sebastian Redla771d222010-07-07 23:17:38 +000077 // C++ [basic.lookup.qual]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000078 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redla771d222010-07-07 23:17:38 +000079 // 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:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +000081 //
82 // ::[opt] nested-name-specifier ~ class-name
Sebastian Redla771d222010-07-07 23:17:38 +000083 //
84 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth8f254812010-02-21 10:19:54 +000085 // a qualified-id of the form:
Douglas Gregorfe17d252010-02-16 19:09:40 +000086 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +000087 // ::opt nested-name-specifier class-name :: ~ class-name
Douglas Gregorfe17d252010-02-16 19:09:40 +000088 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000089 // the class-names are looked up as types in the scope designated by
Sebastian Redla771d222010-07-07 23:17:38 +000090 // the nested-name-specifier.
Douglas Gregorfe17d252010-02-16 19:09:40 +000091 //
Sebastian Redla771d222010-07-07 23:17:38 +000092 // Here, we check the first case (completely) and determine whether the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000093 // code below is permitted to look at the prefix of the
Sebastian Redla771d222010-07-07 23:17:38 +000094 // 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;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000102
Sebastian Redla771d222010-07-07 23:17:38 +0000103 // The second case from the C++03 rules quoted further above.
Douglas Gregor46841e12010-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 Gregor46841e12010-02-23 00:15:22 +0000112 } else if (ObjectTypePtr) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000113 LookupCtx = computeDeclContext(SearchType);
114 isDependent = SearchType->isDependentType();
115 } else {
116 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor46841e12010-02-23 00:15:22 +0000117 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000118 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000119
Douglas Gregorcd3f49f2010-02-25 04:46:04 +0000120 LookInScope = false;
Douglas Gregorfe17d252010-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();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000131 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregorfe17d252010-02-16 19:09:40 +0000132 "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 Gregor678f90d2010-02-25 01:56:36 +0000148 else if (Step == 1 && LookInScope && S)
Douglas Gregorfe17d252010-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 McCallba7bf592010-08-24 05:47:05 +0000155 return ParsedType();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000156
157 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
158 QualType T = Context.getTypeDeclType(Type);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000159
160 if (SearchType.isNull() || SearchType->isDependentType() ||
161 Context.hasSameUnqualifiedType(T, SearchType)) {
162 // We found our type!
163
John McCallba7bf592010-08-24 05:47:05 +0000164 return ParsedType::make(T);
Douglas Gregorfe17d252010-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
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000173 // issue 399, for which there isn't even an obvious direction.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000174 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 McCalle78aac42010-03-10 03:28:59 +0000179 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
180 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000181 }
182 }
183 if (MemberOfType.isNull())
184 MemberOfType = SearchType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000185
Douglas Gregorfe17d252010-02-16 19:09:40 +0000186 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 McCallba7bf592010-08-24 05:47:05 +0000197 return ParsedType::make(MemberOfType);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000198 }
199
200 continue;
201 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000202
Douglas Gregorfe17d252010-02-16 19:09:40 +0000203 // 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 McCallba7bf592010-08-24 05:47:05 +0000216 return ParsedType::make(MemberOfType);
Douglas Gregorfe17d252010-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.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000223 if (DependentTemplateName *DepTemplate
Douglas Gregorfe17d252010-02-16 19:09:40 +0000224 = SpecName.getAsDependentTemplateName()) {
225 if (DepTemplate->isIdentifier() &&
226 DepTemplate->getIdentifier() == Template->getIdentifier())
John McCallba7bf592010-08-24 05:47:05 +0000227 return ParsedType::make(MemberOfType);
Douglas Gregorfe17d252010-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 McCallba7bf592010-08-24 05:47:05 +0000248 QualType T = CheckTypenameType(ETK_None, NNS, II,
249 SourceLocation(),
250 Range, NameLoc);
251 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000252 }
253
254 if (ObjectTypePtr)
255 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000256 << &II;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000257 else
258 Diag(NameLoc, diag::err_destructor_class_name);
259
John McCallba7bf592010-08-24 05:47:05 +0000260 return ParsedType();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000261}
262
Douglas Gregor9da64192010-04-26 22:37:10 +0000263/// \brief Build a C++ typeid expression with a type operand.
John McCalldadc5752010-08-24 06:29:42 +0000264ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000265 SourceLocation TypeidLoc,
266 TypeSourceInfo *Operand,
267 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000268 // C++ [expr.typeid]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000269 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor9da64192010-04-26 22:37:10 +0000270 // that is the operand of typeid are always ignored.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000271 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor9da64192010-04-26 22:37:10 +0000272 // type, the class shall be completely-defined.
Douglas Gregor876cec22010-06-02 06:16:02 +0000273 Qualifiers Quals;
274 QualType T
275 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
276 Quals);
Douglas Gregor9da64192010-04-26 22:37:10 +0000277 if (T->getAs<RecordType>() &&
278 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
279 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000280
Douglas Gregor9da64192010-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 McCalldadc5752010-08-24 06:29:42 +0000287ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000288 SourceLocation TypeidLoc,
289 Expr *E,
290 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000291 bool isUnevaluatedOperand = true;
Douglas Gregor9da64192010-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();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000301
Douglas Gregor9da64192010-04-26 22:37:10 +0000302 // C++ [expr.typeid]p3:
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000303 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor9da64192010-04-26 22:37:10 +0000304 // polymorphic class type [...] [the] expression is an unevaluated
305 // operand. [...]
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000306 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000307 isUnevaluatedOperand = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000308
309 // We require a vtable to query the type at run time.
310 MarkVTableUsed(TypeidLoc, RecordD);
311 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000312 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000313
Douglas Gregor9da64192010-04-26 22:37:10 +0000314 // C++ [expr.typeid]p4:
315 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000316 // cv-qualified type, the result of the typeid expression refers to a
317 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor9da64192010-04-26 22:37:10 +0000318 // type.
Douglas Gregor876cec22010-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 McCalle3027922010-08-25 11:45:40 +0000323 ImpCastExprToType(E, UnqualT, CK_NoOp, CastCategory(E));
Douglas Gregor9da64192010-04-26 22:37:10 +0000324 }
325 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000326
Douglas Gregor9da64192010-04-26 22:37:10 +0000327 // 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;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000332
Douglas Gregor9da64192010-04-26 22:37:10 +0000333 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCallb268a282010-08-23 23:25:46 +0000334 E,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000335 SourceRange(TypeidLoc, RParenLoc)));
Douglas Gregor9da64192010-04-26 22:37:10 +0000336}
337
338/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCalldadc5752010-08-24 06:29:42 +0000339ExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000340Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
341 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000342 // Find the std::type_info type.
Douglas Gregor87f54062009-09-15 22:30:29 +0000343 if (!StdNamespace)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000344 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000345
Douglas Gregor4c7c1092010-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 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000354
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000355 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000356
Douglas Gregor9da64192010-04-26 22:37:10 +0000357 if (isType) {
358 // The operand is a type; handle it as such.
359 TypeSourceInfo *TInfo = 0;
John McCallba7bf592010-08-24 05:47:05 +0000360 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
361 &TInfo);
Douglas Gregor9da64192010-04-26 22:37:10 +0000362 if (T.isNull())
363 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000364
Douglas Gregor9da64192010-04-26 22:37:10 +0000365 if (!TInfo)
366 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000367
Douglas Gregor9da64192010-04-26 22:37:10 +0000368 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000369 }
Mike Stump11289f42009-09-09 15:08:12 +0000370
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000371 // The operand is an expression.
John McCallb268a282010-08-23 23:25:46 +0000372 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000373}
374
Francois Pichetb7577652010-12-27 01:32:00 +0000375/// Retrieve the UuidAttr associated with QT.
376static UuidAttr *GetUuidAttrOfType(QualType QT) {
377 // Optionally remove one level of pointer, reference or array indirection.
John McCall424cec92011-01-19 06:33:43 +0000378 const Type *Ty = QT.getTypePtr();;
Francois Pichet9dddd402010-12-20 03:51:03 +0000379 if (QT->isPointerType() || QT->isReferenceType())
380 Ty = QT->getPointeeType().getTypePtr();
381 else if (QT->isArrayType())
382 Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
383
Francois Pichetb7577652010-12-27 01:32:00 +0000384 // Loop all class definition and declaration looking for an uuid attribute.
385 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
386 while (RD) {
387 if (UuidAttr *Uuid = RD->getAttr<UuidAttr>())
388 return Uuid;
389 RD = RD->getPreviousDeclaration();
390 }
391 return 0;
Francois Pichet9dddd402010-12-20 03:51:03 +0000392}
393
Francois Pichet9f4f2072010-09-08 12:20:18 +0000394/// \brief Build a Microsoft __uuidof expression with a type operand.
395ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
396 SourceLocation TypeidLoc,
397 TypeSourceInfo *Operand,
398 SourceLocation RParenLoc) {
Francois Pichetb7577652010-12-27 01:32:00 +0000399 if (!Operand->getType()->isDependentType()) {
400 if (!GetUuidAttrOfType(Operand->getType()))
401 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
402 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000403
Francois Pichet9f4f2072010-09-08 12:20:18 +0000404 // FIXME: add __uuidof semantic analysis for type operand.
405 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
406 Operand,
407 SourceRange(TypeidLoc, RParenLoc)));
408}
409
410/// \brief Build a Microsoft __uuidof expression with an expression operand.
411ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
412 SourceLocation TypeidLoc,
413 Expr *E,
414 SourceLocation RParenLoc) {
Francois Pichetb7577652010-12-27 01:32:00 +0000415 if (!E->getType()->isDependentType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000416 if (!GetUuidAttrOfType(E->getType()) &&
Francois Pichetb7577652010-12-27 01:32:00 +0000417 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
418 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
419 }
420 // FIXME: add __uuidof semantic analysis for type operand.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000421 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
422 E,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000423 SourceRange(TypeidLoc, RParenLoc)));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000424}
425
426/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
427ExprResult
428Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
429 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000430 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000431 if (!MSVCGuidDecl) {
432 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
433 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
434 LookupQualifiedName(R, Context.getTranslationUnitDecl());
435 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
436 if (!MSVCGuidDecl)
437 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000438 }
439
Francois Pichet9f4f2072010-09-08 12:20:18 +0000440 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000441
Francois Pichet9f4f2072010-09-08 12:20:18 +0000442 if (isType) {
443 // The operand is a type; handle it as such.
444 TypeSourceInfo *TInfo = 0;
445 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
446 &TInfo);
447 if (T.isNull())
448 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000449
Francois Pichet9f4f2072010-09-08 12:20:18 +0000450 if (!TInfo)
451 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
452
453 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
454 }
455
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000456 // The operand is an expression.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000457 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
458}
459
Steve Naroff66356bd2007-09-16 14:56:35 +0000460/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCalldadc5752010-08-24 06:29:42 +0000461ExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000462Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000463 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000464 "Unknown C++ Boolean value!");
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000465 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
466 Context.BoolTy, OpLoc));
Bill Wendling4073ed52007-02-13 01:51:42 +0000467}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000468
Sebastian Redl576fd422009-05-10 18:38:11 +0000469/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCalldadc5752010-08-24 06:29:42 +0000470ExprResult
Sebastian Redl576fd422009-05-10 18:38:11 +0000471Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
472 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
473}
474
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000475/// ActOnCXXThrow - Parse throw expressions.
John McCalldadc5752010-08-24 06:29:42 +0000476ExprResult
John McCallb268a282010-08-23 23:25:46 +0000477Sema::ActOnCXXThrow(SourceLocation OpLoc, Expr *Ex) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000478 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
479 return ExprError();
480 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
481}
482
483/// CheckCXXThrowOperand - Validate the operand of a throw.
484bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
485 // C++ [except.throw]p3:
Douglas Gregor247894b2009-12-23 22:04:40 +0000486 // A throw-expression initializes a temporary object, called the exception
487 // object, the type of which is determined by removing any top-level
488 // cv-qualifiers from the static type of the operand of throw and adjusting
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000489 // the type from "array of T" or "function returning T" to "pointer to T"
Douglas Gregor247894b2009-12-23 22:04:40 +0000490 // or "pointer to function returning T", [...]
491 if (E->getType().hasQualifiers())
John McCalle3027922010-08-25 11:45:40 +0000492 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000493 CastCategory(E));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000494
Sebastian Redl4de47b42009-04-27 20:27:31 +0000495 DefaultFunctionArrayConversion(E);
496
497 // If the type of the exception would be an incomplete type or a pointer
498 // to an incomplete type other than (cv) void the program is ill-formed.
499 QualType Ty = E->getType();
John McCall2e6567a2010-04-22 01:10:34 +0000500 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000501 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000502 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000503 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000504 }
505 if (!isPointer || !Ty->isVoidType()) {
506 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlsson029fc692009-08-26 22:59:12 +0000507 PDiag(isPointer ? diag::err_throw_incomplete_ptr
508 : diag::err_throw_incomplete)
509 << E->getSourceRange()))
Sebastian Redl4de47b42009-04-27 20:27:31 +0000510 return true;
Rafael Espindola70e040d2010-03-02 21:28:26 +0000511
Douglas Gregore8154332010-04-15 18:05:39 +0000512 if (RequireNonAbstractType(ThrowLoc, E->getType(),
513 PDiag(diag::err_throw_abstract_type)
514 << E->getSourceRange()))
515 return true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000516 }
517
John McCall2e6567a2010-04-22 01:10:34 +0000518 // Initialize the exception result. This implicitly weeds out
519 // abstract types or types with inaccessible copy constructors.
Douglas Gregorc74edc22011-01-21 22:46:35 +0000520 const VarDecl *NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
521
Douglas Gregor5d369002011-01-21 18:05:27 +0000522 // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p32.
John McCall2e6567a2010-04-22 01:10:34 +0000523 InitializedEntity Entity =
Douglas Gregorc74edc22011-01-21 22:46:35 +0000524 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
525 /*NRVO=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000526 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
Douglas Gregorc74edc22011-01-21 22:46:35 +0000527 QualType(), E);
John McCall2e6567a2010-04-22 01:10:34 +0000528 if (Res.isInvalid())
529 return true;
530 E = Res.takeAs<Expr>();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000531
Eli Friedman91a3d272010-06-03 20:39:03 +0000532 // If the exception has class type, we need additional handling.
533 const RecordType *RecordTy = Ty->getAs<RecordType>();
534 if (!RecordTy)
535 return false;
536 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
537
Douglas Gregor88d292c2010-05-13 16:44:06 +0000538 // If we are throwing a polymorphic class type or pointer thereof,
539 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000540 MarkVTableUsed(ThrowLoc, RD);
541
Eli Friedman36ebbec2010-10-12 20:32:36 +0000542 // If a pointer is thrown, the referenced object will not be destroyed.
543 if (isPointer)
544 return false;
545
Eli Friedman91a3d272010-06-03 20:39:03 +0000546 // If the class has a non-trivial destructor, we must be able to call it.
547 if (RD->hasTrivialDestructor())
548 return false;
549
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000550 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +0000551 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman91a3d272010-06-03 20:39:03 +0000552 if (!Destructor)
553 return false;
554
555 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
556 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregor747eb782010-07-08 06:14:04 +0000557 PDiag(diag::err_access_dtor_exception) << Ty);
Sebastian Redl4de47b42009-04-27 20:27:31 +0000558 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000559}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000560
John McCalldadc5752010-08-24 06:29:42 +0000561ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000562 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
563 /// is a non-lvalue expression whose value is the address of the object for
564 /// which the function is called.
565
John McCall87fe5d52010-05-20 01:18:31 +0000566 DeclContext *DC = getFunctionLevelDeclContext();
567 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000568 if (MD->isInstance())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000569 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregorb15af892010-01-07 23:12:05 +0000570 MD->getThisType(Context),
571 /*isImplicit=*/false));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000572
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000573 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000574}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000575
John McCalldadc5752010-08-24 06:29:42 +0000576ExprResult
Douglas Gregor2b88c112010-09-08 00:15:04 +0000577Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000578 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000579 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000580 SourceLocation RParenLoc) {
Douglas Gregor7df89f52010-02-05 19:11:37 +0000581 if (!TypeRep)
582 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000583
John McCall97513962010-01-15 18:39:57 +0000584 TypeSourceInfo *TInfo;
585 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
586 if (!TInfo)
587 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregor2b88c112010-09-08 00:15:04 +0000588
589 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
590}
591
592/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
593/// Can be interpreted either as function-style casting ("int(x)")
594/// or class type construction ("ClassType(x,y,z)")
595/// or creation of a value-initialized type ("int()").
596ExprResult
597Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
598 SourceLocation LParenLoc,
599 MultiExprArg exprs,
600 SourceLocation RParenLoc) {
601 QualType Ty = TInfo->getType();
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000602 unsigned NumExprs = exprs.size();
603 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregor2b88c112010-09-08 00:15:04 +0000604 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000605 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
606
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000607 if (Ty->isDependentType() ||
Douglas Gregor0950e412009-03-13 21:01:28 +0000608 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000609 exprs.release();
Mike Stump11289f42009-09-09 15:08:12 +0000610
Douglas Gregor2b88c112010-09-08 00:15:04 +0000611 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregorce934142009-05-20 18:46:25 +0000612 LParenLoc,
613 Exprs, NumExprs,
614 RParenLoc));
Douglas Gregor0950e412009-03-13 21:01:28 +0000615 }
616
Anders Carlsson55243162009-08-27 03:53:50 +0000617 if (Ty->isArrayType())
618 return ExprError(Diag(TyBeginLoc,
619 diag::err_value_init_for_array_type) << FullRange);
620 if (!Ty->isVoidType() &&
621 RequireCompleteType(TyBeginLoc, Ty,
622 PDiag(diag::err_invalid_incomplete_type_use)
623 << FullRange))
624 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000625
Anders Carlsson55243162009-08-27 03:53:50 +0000626 if (RequireNonAbstractType(TyBeginLoc, Ty,
627 diag::err_allocation_of_abstract_type))
628 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000629
630
Douglas Gregordd04d332009-01-16 18:33:17 +0000631 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000632 // If the expression list is a single expression, the type conversion
633 // expression is equivalent (in definedness, and if defined in meaning) to the
634 // corresponding cast expression.
635 //
636 if (NumExprs == 1) {
John McCall8cb679e2010-11-15 09:13:47 +0000637 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +0000638 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +0000639 CXXCastPath BasePath;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000640 if (CheckCastTypes(TInfo->getTypeLoc().getSourceRange(), Ty, Exprs[0],
John McCall7decc9e2010-11-18 06:31:45 +0000641 Kind, VK, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +0000642 /*FunctionalStyle=*/true))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000643 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +0000644
645 exprs.release();
Anders Carlssone9766d52009-09-09 21:33:21 +0000646
John McCallcf142162010-08-07 06:22:56 +0000647 return Owned(CXXFunctionalCastExpr::Create(Context,
Douglas Gregor2b88c112010-09-08 00:15:04 +0000648 Ty.getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +0000649 VK, TInfo, TyBeginLoc, Kind,
John McCallcf142162010-08-07 06:22:56 +0000650 Exprs[0], &BasePath,
651 RParenLoc));
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000652 }
653
Douglas Gregor8ec51732010-09-08 21:40:08 +0000654 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
655 InitializationKind Kind
656 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
657 LParenLoc, RParenLoc)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000658 : InitializationKind::CreateValue(TyBeginLoc,
Douglas Gregor8ec51732010-09-08 21:40:08 +0000659 LParenLoc, RParenLoc);
660 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
661 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000662
Douglas Gregor8ec51732010-09-08 21:40:08 +0000663 // FIXME: Improve AST representation?
664 return move(Result);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000665}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000666
John McCall284c48f2011-01-27 09:37:56 +0000667/// doesUsualArrayDeleteWantSize - Answers whether the usual
668/// operator delete[] for the given type has a size_t parameter.
669static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
670 QualType allocType) {
671 const RecordType *record =
672 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
673 if (!record) return false;
674
675 // Try to find an operator delete[] in class scope.
676
677 DeclarationName deleteName =
678 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
679 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
680 S.LookupQualifiedName(ops, record->getDecl());
681
682 // We're just doing this for information.
683 ops.suppressDiagnostics();
684
685 // Very likely: there's no operator delete[].
686 if (ops.empty()) return false;
687
688 // If it's ambiguous, it should be illegal to call operator delete[]
689 // on this thing, so it doesn't matter if we allocate extra space or not.
690 if (ops.isAmbiguous()) return false;
691
692 LookupResult::Filter filter = ops.makeFilter();
693 while (filter.hasNext()) {
694 NamedDecl *del = filter.next()->getUnderlyingDecl();
695
696 // C++0x [basic.stc.dynamic.deallocation]p2:
697 // A template instance is never a usual deallocation function,
698 // regardless of its signature.
699 if (isa<FunctionTemplateDecl>(del)) {
700 filter.erase();
701 continue;
702 }
703
704 // C++0x [basic.stc.dynamic.deallocation]p2:
705 // If class T does not declare [an operator delete[] with one
706 // parameter] but does declare a member deallocation function
707 // named operator delete[] with exactly two parameters, the
708 // second of which has type std::size_t, then this function
709 // is a usual deallocation function.
710 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
711 filter.erase();
712 continue;
713 }
714 }
715 filter.done();
716
717 if (!ops.isSingleResult()) return false;
718
719 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
720 return (del->getNumParams() == 2);
721}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000722
Sebastian Redlbd150f42008-11-21 19:14:01 +0000723/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
724/// @code new (memory) int[size][4] @endcode
725/// or
726/// @code ::new Foo(23, "hello") @endcode
727/// For the interpretation of this heap of arguments, consult the base version.
John McCalldadc5752010-08-24 06:29:42 +0000728ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +0000729Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000730 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000731 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl351bb782008-12-02 14:43:59 +0000732 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000733 MultiExprArg ConstructorArgs,
Mike Stump11289f42009-09-09 15:08:12 +0000734 SourceLocation ConstructorRParen) {
Sebastian Redl351bb782008-12-02 14:43:59 +0000735 Expr *ArraySize = 0;
Sebastian Redl351bb782008-12-02 14:43:59 +0000736 // If the specified type is an array, unwrap it and save the expression.
737 if (D.getNumTypeObjects() > 0 &&
738 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
739 DeclaratorChunk &Chunk = D.getTypeObject(0);
740 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000741 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
742 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000743 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000744 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
745 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000746
Sebastian Redl351bb782008-12-02 14:43:59 +0000747 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000748 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +0000749 }
750
Douglas Gregor73341c42009-09-11 00:18:58 +0000751 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000752 if (ArraySize) {
753 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +0000754 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
755 break;
756
757 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
758 if (Expr *NumElts = (Expr *)Array.NumElts) {
759 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
760 !NumElts->isIntegerConstantExpr(Context)) {
761 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
762 << NumElts->getSourceRange();
763 return ExprError();
764 }
765 }
766 }
767 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000768
John McCall8cb7bdf2010-06-04 23:28:52 +0000769 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
770 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000771 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000772 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000773
Douglas Gregor0744ef62010-09-07 21:49:58 +0000774 if (!TInfo)
775 TInfo = Context.getTrivialTypeSourceInfo(AllocType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000776
Mike Stump11289f42009-09-09 15:08:12 +0000777 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000778 PlacementLParen,
Mike Stump11289f42009-09-09 15:08:12 +0000779 move(PlacementArgs),
Douglas Gregord0fefba2009-05-21 00:00:09 +0000780 PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +0000781 TypeIdParens,
Mike Stump11289f42009-09-09 15:08:12 +0000782 AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +0000783 TInfo,
John McCallb268a282010-08-23 23:25:46 +0000784 ArraySize,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000785 ConstructorLParen,
786 move(ConstructorArgs),
787 ConstructorRParen);
788}
789
John McCalldadc5752010-08-24 06:29:42 +0000790ExprResult
Douglas Gregord0fefba2009-05-21 00:00:09 +0000791Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
792 SourceLocation PlacementLParen,
793 MultiExprArg PlacementArgs,
794 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +0000795 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000796 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +0000797 TypeSourceInfo *AllocTypeInfo,
John McCallb268a282010-08-23 23:25:46 +0000798 Expr *ArraySize,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000799 SourceLocation ConstructorLParen,
800 MultiExprArg ConstructorArgs,
801 SourceLocation ConstructorRParen) {
Douglas Gregor0744ef62010-09-07 21:49:58 +0000802 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
Sebastian Redl351bb782008-12-02 14:43:59 +0000803
Douglas Gregorcda95f42010-05-16 16:01:03 +0000804 // Per C++0x [expr.new]p5, the type being constructed may be a
805 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +0000806 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +0000807 if (const ConstantArrayType *Array
808 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000809 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
810 Context.getSizeType(),
811 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +0000812 AllocType = Array->getElementType();
813 }
814 }
Sebastian Redlbd150f42008-11-21 19:14:01 +0000815
Douglas Gregor3999e152010-10-06 16:00:31 +0000816 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
817 return ExprError();
818
Douglas Gregorcda95f42010-05-16 16:01:03 +0000819 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl351bb782008-12-02 14:43:59 +0000820
Sebastian Redlbd150f42008-11-21 19:14:01 +0000821 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
822 // or enumeration type with a non-negative value."
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000823 if (ArraySize && !ArraySize->isTypeDependent()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000824
Sebastian Redl351bb782008-12-02 14:43:59 +0000825 QualType SizeType = ArraySize->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000826
John McCalldadc5752010-08-24 06:29:42 +0000827 ExprResult ConvertedSize
John McCallb268a282010-08-23 23:25:46 +0000828 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
Douglas Gregor4799d032010-06-30 00:20:43 +0000829 PDiag(diag::err_array_size_not_integral),
830 PDiag(diag::err_array_size_incomplete_type)
831 << ArraySize->getSourceRange(),
832 PDiag(diag::err_array_size_explicit_conversion),
833 PDiag(diag::note_array_size_conversion),
834 PDiag(diag::err_array_size_ambiguous_conversion),
835 PDiag(diag::note_array_size_conversion),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000836 PDiag(getLangOptions().CPlusPlus0x? 0
Douglas Gregor4799d032010-06-30 00:20:43 +0000837 : diag::ext_array_size_conversion));
838 if (ConvertedSize.isInvalid())
839 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000840
John McCallb268a282010-08-23 23:25:46 +0000841 ArraySize = ConvertedSize.take();
Douglas Gregor4799d032010-06-30 00:20:43 +0000842 SizeType = ArraySize->getType();
Douglas Gregor0bf31402010-10-08 23:50:27 +0000843 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +0000844 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000845
Sebastian Redl351bb782008-12-02 14:43:59 +0000846 // Let's see if this is a constant < 0. If so, we reject it out of hand.
847 // We don't care about special rules, so we tell the machinery it's not
848 // evaluated - it gives us a result in more cases.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000849 if (!ArraySize->isValueDependent()) {
850 llvm::APSInt Value;
851 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
852 if (Value < llvm::APSInt(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000853 llvm::APInt::getNullValue(Value.getBitWidth()),
Anders Carlsson8ab20bb2009-09-23 00:37:25 +0000854 Value.isUnsigned()))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000855 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregorcaa1bf42010-08-18 00:39:00 +0000856 diag::err_typecheck_negative_array_size)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000857 << ArraySize->getSourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000858
Douglas Gregorcaa1bf42010-08-18 00:39:00 +0000859 if (!AllocType->isDependentType()) {
860 unsigned ActiveSizeBits
861 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
862 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000863 Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregorcaa1bf42010-08-18 00:39:00 +0000864 diag::err_array_too_large)
865 << Value.toString(10)
866 << ArraySize->getSourceRange();
867 return ExprError();
868 }
869 }
Douglas Gregorf2753b32010-07-13 15:54:32 +0000870 } else if (TypeIdParens.isValid()) {
871 // Can't have dynamic array size when the type-id is in parentheses.
872 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
873 << ArraySize->getSourceRange()
874 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
875 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000876
Douglas Gregorf2753b32010-07-13 15:54:32 +0000877 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000878 }
Sebastian Redl351bb782008-12-02 14:43:59 +0000879 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000880
Eli Friedman06ed2a52009-10-20 08:27:19 +0000881 ImpCastExprToType(ArraySize, Context.getSizeType(),
John McCalle3027922010-08-25 11:45:40 +0000882 CK_IntegralCast);
Sebastian Redl351bb782008-12-02 14:43:59 +0000883 }
Sebastian Redlbd150f42008-11-21 19:14:01 +0000884
Sebastian Redlbd150f42008-11-21 19:14:01 +0000885 FunctionDecl *OperatorNew = 0;
886 FunctionDecl *OperatorDelete = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000887 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
888 unsigned NumPlaceArgs = PlacementArgs.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000889
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000890 if (!AllocType->isDependentType() &&
891 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
892 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000893 SourceRange(PlacementLParen, PlacementRParen),
894 UseGlobal, AllocType, ArraySize, PlaceArgs,
895 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000896 return ExprError();
John McCall284c48f2011-01-27 09:37:56 +0000897
898 // If this is an array allocation, compute whether the usual array
899 // deallocation function for the type has a size_t parameter.
900 bool UsualArrayDeleteWantsSize = false;
901 if (ArraySize && !AllocType->isDependentType())
902 UsualArrayDeleteWantsSize
903 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
904
Fariborz Jahanian835026e2009-11-24 18:29:37 +0000905 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000906 if (OperatorNew) {
907 // Add default arguments, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000908 const FunctionProtoType *Proto =
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000909 OperatorNew->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000910 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +0000911 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000912
Anders Carlssonc144bc22010-05-03 02:07:56 +0000913 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000914 Proto, 1, PlaceArgs, NumPlaceArgs,
Anders Carlssonc144bc22010-05-03 02:07:56 +0000915 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +0000916 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000917
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000918 NumPlaceArgs = AllPlaceArgs.size();
919 if (NumPlaceArgs > 0)
920 PlaceArgs = &AllPlaceArgs[0];
921 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000922
Sebastian Redlbd150f42008-11-21 19:14:01 +0000923 bool Init = ConstructorLParen.isValid();
924 // --- Choosing a constructor ---
Sebastian Redlbd150f42008-11-21 19:14:01 +0000925 CXXConstructorDecl *Constructor = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000926 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
927 unsigned NumConsArgs = ConstructorArgs.size();
John McCall37ad5512010-08-23 06:44:23 +0000928 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmanfd8d4e12009-11-08 22:15:39 +0000929
Anders Carlssonc6bb0e12010-05-03 15:45:23 +0000930 // Array 'new' can't have any initializers.
Anders Carlssone6ae81b2010-05-16 16:24:20 +0000931 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlssonc6bb0e12010-05-03 15:45:23 +0000932 SourceRange InitRange(ConsArgs[0]->getLocStart(),
933 ConsArgs[NumConsArgs - 1]->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000934
Anders Carlssonc6bb0e12010-05-03 15:45:23 +0000935 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
936 return ExprError();
937 }
938
Douglas Gregor85dabae2009-12-16 01:38:02 +0000939 if (!AllocType->isDependentType() &&
940 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
941 // C++0x [expr.new]p15:
942 // A new-expression that creates an object of type T initializes that
943 // object as follows:
944 InitializationKind Kind
945 // - If the new-initializer is omitted, the object is default-
946 // initialized (8.5); if no initialization is performed,
947 // the object has indeterminate value
Douglas Gregor0744ef62010-09-07 21:49:58 +0000948 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000949 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor85dabae2009-12-16 01:38:02 +0000950 // initialization rules of 8.5 for direct-initialization.
Douglas Gregor0744ef62010-09-07 21:49:58 +0000951 : InitializationKind::CreateDirect(TypeRange.getBegin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000952 ConstructorLParen,
Douglas Gregor85dabae2009-12-16 01:38:02 +0000953 ConstructorRParen);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000954
Douglas Gregor85dabae2009-12-16 01:38:02 +0000955 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +0000956 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000957 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000958 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor85dabae2009-12-16 01:38:02 +0000959 move(ConstructorArgs));
960 if (FullInit.isInvalid())
961 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000962
963 // FullInit is our initializer; walk through it to determine if it's a
Douglas Gregor85dabae2009-12-16 01:38:02 +0000964 // constructor call, which CXXNewExpr handles directly.
965 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
966 if (CXXBindTemporaryExpr *Binder
967 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
968 FullInitExpr = Binder->getSubExpr();
969 if (CXXConstructExpr *Construct
970 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
971 Constructor = Construct->getConstructor();
972 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
973 AEnd = Construct->arg_end();
974 A != AEnd; ++A)
John McCallc3007a22010-10-26 07:05:15 +0000975 ConvertedConstructorArgs.push_back(*A);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000976 } else {
977 // Take the converted initializer.
978 ConvertedConstructorArgs.push_back(FullInit.release());
979 }
980 } else {
981 // No initialization required.
982 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000983
Douglas Gregor85dabae2009-12-16 01:38:02 +0000984 // Take the converted arguments and use them for the new expression.
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000985 NumConsArgs = ConvertedConstructorArgs.size();
986 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redlbd150f42008-11-21 19:14:01 +0000987 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000988
Douglas Gregor6642ca22010-02-26 05:06:18 +0000989 // Mark the new and delete operators as referenced.
990 if (OperatorNew)
991 MarkDeclarationReferenced(StartLoc, OperatorNew);
992 if (OperatorDelete)
993 MarkDeclarationReferenced(StartLoc, OperatorDelete);
994
Sebastian Redlbd150f42008-11-21 19:14:01 +0000995 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000996
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000997 PlacementArgs.release();
998 ConstructorArgs.release();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000999
Ted Kremenek9d6eb402010-02-11 22:51:03 +00001000 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001001 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenek9d6eb402010-02-11 22:51:03 +00001002 ArraySize, Constructor, Init,
1003 ConsArgs, NumConsArgs, OperatorDelete,
John McCall284c48f2011-01-27 09:37:56 +00001004 UsualArrayDeleteWantsSize,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001005 ResultType, AllocTypeInfo,
1006 StartLoc,
Ted Kremenek9d6eb402010-02-11 22:51:03 +00001007 Init ? ConstructorRParen :
Chandler Carruth01718152010-10-25 08:47:36 +00001008 TypeRange.getEnd(),
1009 ConstructorLParen, ConstructorRParen));
Sebastian Redlbd150f42008-11-21 19:14:01 +00001010}
1011
1012/// CheckAllocatedType - Checks that a type is suitable as the allocated type
1013/// in a new-expression.
1014/// dimension off and stores the size expression in ArraySize.
Douglas Gregord0fefba2009-05-21 00:00:09 +00001015bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00001016 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00001017 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1018 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +00001019 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00001020 return Diag(Loc, diag::err_bad_new_type)
1021 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00001022 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00001023 return Diag(Loc, diag::err_bad_new_type)
1024 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00001025 else if (!AllocType->isDependentType() &&
Douglas Gregord0fefba2009-05-21 00:00:09 +00001026 RequireCompleteType(Loc, AllocType,
Anders Carlssond624e162009-08-26 23:45:07 +00001027 PDiag(diag::err_new_incomplete_type)
1028 << R))
Sebastian Redlbd150f42008-11-21 19:14:01 +00001029 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +00001030 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +00001031 diag::err_allocation_of_abstract_type))
1032 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +00001033 else if (AllocType->isVariablyModifiedType())
1034 return Diag(Loc, diag::err_variably_modified_new_type)
1035 << AllocType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001036
Sebastian Redlbd150f42008-11-21 19:14:01 +00001037 return false;
1038}
1039
Douglas Gregor6642ca22010-02-26 05:06:18 +00001040/// \brief Determine whether the given function is a non-placement
1041/// deallocation function.
1042static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1043 if (FD->isInvalidDecl())
1044 return false;
1045
1046 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1047 return Method->isUsualDeallocationFunction();
1048
1049 return ((FD->getOverloadedOperator() == OO_Delete ||
1050 FD->getOverloadedOperator() == OO_Array_Delete) &&
1051 FD->getNumParams() == 1);
1052}
1053
Sebastian Redlfaf68082008-12-03 20:26:15 +00001054/// FindAllocationFunctions - Finds the overloads of operator new and delete
1055/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001056bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1057 bool UseGlobal, QualType AllocType,
1058 bool IsArray, Expr **PlaceArgs,
1059 unsigned NumPlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +00001060 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +00001061 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001062 // --- Choosing an allocation function ---
1063 // C++ 5.3.4p8 - 14 & 18
1064 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1065 // in the scope of the allocated class.
1066 // 2) If an array size is given, look for operator new[], else look for
1067 // operator new.
1068 // 3) The first argument is always size_t. Append the arguments from the
1069 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +00001070
1071 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
1072 // We don't care about the actual value of this argument.
1073 // FIXME: Should the Sema create the expression and embed it in the syntax
1074 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001075 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Anders Carlssona471db02009-08-16 20:29:29 +00001076 Context.Target.getPointerWidth(0)),
1077 Context.getSizeType(),
1078 SourceLocation());
1079 AllocArgs[0] = &Size;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001080 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1081
Douglas Gregor6642ca22010-02-26 05:06:18 +00001082 // C++ [expr.new]p8:
1083 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001084 // function's name is operator new and the deallocation function's
Douglas Gregor6642ca22010-02-26 05:06:18 +00001085 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001086 // type, the allocation function's name is operator new[] and the
1087 // deallocation function's name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +00001088 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1089 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001090 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1091 IsArray ? OO_Array_Delete : OO_Delete);
1092
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001093 QualType AllocElemType = Context.getBaseElementType(AllocType);
1094
1095 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump11289f42009-09-09 15:08:12 +00001096 CXXRecordDecl *Record
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001097 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001098 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +00001099 AllocArgs.size(), Record, /*AllowMissing=*/true,
1100 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +00001101 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001102 }
1103 if (!OperatorNew) {
1104 // Didn't find a member overload. Look for a global one.
1105 DeclareGlobalNewDelete();
Sebastian Redl33a31012008-12-04 22:20:51 +00001106 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001107 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +00001108 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1109 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +00001110 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001111 }
1112
John McCall0f55a032010-04-20 02:18:25 +00001113 // We don't need an operator delete if we're running under
1114 // -fno-exceptions.
1115 if (!getLangOptions().Exceptions) {
1116 OperatorDelete = 0;
1117 return false;
1118 }
1119
Anders Carlsson6f9dabf2009-05-31 20:26:12 +00001120 // FindAllocationOverload can change the passed in arguments, so we need to
1121 // copy them back.
1122 if (NumPlaceArgs > 0)
1123 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001124
Douglas Gregor6642ca22010-02-26 05:06:18 +00001125 // C++ [expr.new]p19:
1126 //
1127 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001128 // deallocation function's name is looked up in the global
Douglas Gregor6642ca22010-02-26 05:06:18 +00001129 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001130 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6642ca22010-02-26 05:06:18 +00001131 // the scope of T. If this lookup fails to find the name, or if
1132 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001133 // deallocation function's name is looked up in the global scope.
Douglas Gregor6642ca22010-02-26 05:06:18 +00001134 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001135 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00001136 CXXRecordDecl *RD
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001137 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00001138 LookupQualifiedName(FoundDelete, RD);
1139 }
John McCallfb6f5262010-03-18 08:19:33 +00001140 if (FoundDelete.isAmbiguous())
1141 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00001142
1143 if (FoundDelete.empty()) {
1144 DeclareGlobalNewDelete();
1145 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1146 }
1147
1148 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00001149
1150 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1151
John McCalld3be2c82010-09-14 21:34:24 +00001152 // Whether we're looking for a placement operator delete is dictated
1153 // by whether we selected a placement operator new, not by whether
1154 // we had explicit placement arguments. This matters for things like
1155 // struct A { void *operator new(size_t, int = 0); ... };
1156 // A *a = new A()
1157 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1158
1159 if (isPlacementNew) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00001160 // C++ [expr.new]p20:
1161 // A declaration of a placement deallocation function matches the
1162 // declaration of a placement allocation function if it has the
1163 // same number of parameters and, after parameter transformations
1164 // (8.3.5), all parameter types except the first are
1165 // identical. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001166 //
Douglas Gregor6642ca22010-02-26 05:06:18 +00001167 // To perform this comparison, we compute the function type that
1168 // the deallocation function should have, and use that type both
1169 // for template argument deduction and for comparison purposes.
John McCalldb40c7f2010-12-14 08:05:40 +00001170 //
1171 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6642ca22010-02-26 05:06:18 +00001172 QualType ExpectedFunctionType;
1173 {
1174 const FunctionProtoType *Proto
1175 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00001176
Douglas Gregor6642ca22010-02-26 05:06:18 +00001177 llvm::SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001178 ArgTypes.push_back(Context.VoidPtrTy);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001179 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1180 ArgTypes.push_back(Proto->getArgType(I));
1181
John McCalldb40c7f2010-12-14 08:05:40 +00001182 FunctionProtoType::ExtProtoInfo EPI;
1183 EPI.Variadic = Proto->isVariadic();
1184
Douglas Gregor6642ca22010-02-26 05:06:18 +00001185 ExpectedFunctionType
1186 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
John McCalldb40c7f2010-12-14 08:05:40 +00001187 ArgTypes.size(), EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001188 }
1189
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001190 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00001191 DEnd = FoundDelete.end();
1192 D != DEnd; ++D) {
1193 FunctionDecl *Fn = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001194 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6642ca22010-02-26 05:06:18 +00001195 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1196 // Perform template argument deduction to try to match the
1197 // expected function type.
1198 TemplateDeductionInfo Info(Context, StartLoc);
1199 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1200 continue;
1201 } else
1202 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1203
1204 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00001205 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001206 }
1207 } else {
1208 // C++ [expr.new]p20:
1209 // [...] Any non-placement deallocation function matches a
1210 // non-placement allocation function. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001211 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00001212 DEnd = FoundDelete.end();
1213 D != DEnd; ++D) {
1214 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1215 if (isNonPlacementDeallocationFunction(Fn))
John McCalla0296f72010-03-19 07:35:19 +00001216 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001217 }
1218 }
1219
1220 // C++ [expr.new]p20:
1221 // [...] If the lookup finds a single matching deallocation
1222 // function, that function will be called; otherwise, no
1223 // deallocation function will be called.
1224 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00001225 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00001226
1227 // C++0x [expr.new]p20:
1228 // If the lookup finds the two-parameter form of a usual
1229 // deallocation function (3.7.4.2) and that function, considered
1230 // as a placement deallocation function, would have been
1231 // selected as a match for the allocation function, the program
1232 // is ill-formed.
1233 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1234 isNonPlacementDeallocationFunction(OperatorDelete)) {
1235 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001236 << SourceRange(PlaceArgs[0]->getLocStart(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00001237 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1238 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1239 << DeleteName;
John McCallfb6f5262010-03-18 08:19:33 +00001240 } else {
1241 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCalla0296f72010-03-19 07:35:19 +00001242 Matches[0].first);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001243 }
1244 }
1245
Sebastian Redlfaf68082008-12-03 20:26:15 +00001246 return false;
1247}
1248
Sebastian Redl33a31012008-12-04 22:20:51 +00001249/// FindAllocationOverload - Find an fitting overload for the allocation
1250/// function in the specified scope.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001251bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1252 DeclarationName Name, Expr** Args,
1253 unsigned NumArgs, DeclContext *Ctx,
Mike Stump11289f42009-09-09 15:08:12 +00001254 bool AllowMissing, FunctionDecl *&Operator) {
John McCall27b18f82009-11-17 02:14:36 +00001255 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1256 LookupQualifiedName(R, Ctx);
John McCall9f3059a2009-10-09 21:13:30 +00001257 if (R.empty()) {
Sebastian Redl33a31012008-12-04 22:20:51 +00001258 if (AllowMissing)
1259 return false;
Sebastian Redl33a31012008-12-04 22:20:51 +00001260 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00001261 << Name << Range;
Sebastian Redl33a31012008-12-04 22:20:51 +00001262 }
1263
John McCallfb6f5262010-03-18 08:19:33 +00001264 if (R.isAmbiguous())
1265 return true;
1266
1267 R.suppressDiagnostics();
John McCall9f3059a2009-10-09 21:13:30 +00001268
John McCallbc077cf2010-02-08 23:07:23 +00001269 OverloadCandidateSet Candidates(StartLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001270 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor80a6cc52009-09-30 00:03:47 +00001271 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor55297ac2008-12-23 00:26:44 +00001272 // Even member operator new/delete are implicitly treated as
1273 // static, so don't use AddMemberCandidate.
John McCalla0296f72010-03-19 07:35:19 +00001274 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth93538422010-02-03 11:02:14 +00001275
John McCalla0296f72010-03-19 07:35:19 +00001276 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1277 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth93538422010-02-03 11:02:14 +00001278 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1279 Candidates,
1280 /*SuppressUserConversions=*/false);
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001281 continue;
Chandler Carruth93538422010-02-03 11:02:14 +00001282 }
1283
John McCalla0296f72010-03-19 07:35:19 +00001284 FunctionDecl *Fn = cast<FunctionDecl>(D);
1285 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth93538422010-02-03 11:02:14 +00001286 /*SuppressUserConversions=*/false);
Sebastian Redl33a31012008-12-04 22:20:51 +00001287 }
1288
1289 // Do the resolution.
1290 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00001291 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl33a31012008-12-04 22:20:51 +00001292 case OR_Success: {
1293 // Got one!
1294 FunctionDecl *FnDecl = Best->Function;
1295 // The first argument is size_t, and the first parameter must be size_t,
1296 // too. This is checked on declaration and can be assumed. (It can't be
1297 // asserted on, though, since invalid decls are left in there.)
John McCallfb6f5262010-03-18 08:19:33 +00001298 // Watch out for variadic allocator function.
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001299 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1300 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
John McCalldadc5752010-08-24 06:29:42 +00001301 ExprResult Result
Douglas Gregor34147272010-03-26 20:35:59 +00001302 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001303 Context,
Douglas Gregor34147272010-03-26 20:35:59 +00001304 FnDecl->getParamDecl(i)),
1305 SourceLocation(),
John McCallc3007a22010-10-26 07:05:15 +00001306 Owned(Args[i]));
Douglas Gregor34147272010-03-26 20:35:59 +00001307 if (Result.isInvalid())
Sebastian Redl33a31012008-12-04 22:20:51 +00001308 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001309
Douglas Gregor34147272010-03-26 20:35:59 +00001310 Args[i] = Result.takeAs<Expr>();
Sebastian Redl33a31012008-12-04 22:20:51 +00001311 }
1312 Operator = FnDecl;
John McCalla0296f72010-03-19 07:35:19 +00001313 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl33a31012008-12-04 22:20:51 +00001314 return false;
1315 }
1316
1317 case OR_No_Viable_Function:
Sebastian Redl33a31012008-12-04 22:20:51 +00001318 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00001319 << Name << Range;
John McCall5c32be02010-08-24 20:38:10 +00001320 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl33a31012008-12-04 22:20:51 +00001321 return true;
1322
1323 case OR_Ambiguous:
Sebastian Redl33a31012008-12-04 22:20:51 +00001324 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001325 << Name << Range;
John McCall5c32be02010-08-24 20:38:10 +00001326 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl33a31012008-12-04 22:20:51 +00001327 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001328
1329 case OR_Deleted:
1330 Diag(StartLoc, diag::err_ovl_deleted_call)
1331 << Best->Function->isDeleted()
1332 << Name << Range;
John McCall5c32be02010-08-24 20:38:10 +00001333 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001334 return true;
Sebastian Redl33a31012008-12-04 22:20:51 +00001335 }
1336 assert(false && "Unreachable, bad result from BestViableFunction");
1337 return true;
1338}
1339
1340
Sebastian Redlfaf68082008-12-03 20:26:15 +00001341/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1342/// delete. These are:
1343/// @code
1344/// void* operator new(std::size_t) throw(std::bad_alloc);
1345/// void* operator new[](std::size_t) throw(std::bad_alloc);
1346/// void operator delete(void *) throw();
1347/// void operator delete[](void *) throw();
1348/// @endcode
1349/// Note that the placement and nothrow forms of new are *not* implicitly
1350/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00001351void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001352 if (GlobalNewDeleteDeclared)
1353 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001354
Douglas Gregor87f54062009-09-15 22:30:29 +00001355 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001356 // [...] The following allocation and deallocation functions (18.4) are
1357 // implicitly declared in global scope in each translation unit of a
Douglas Gregor87f54062009-09-15 22:30:29 +00001358 // program
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001359 //
Douglas Gregor87f54062009-09-15 22:30:29 +00001360 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001361 // void* operator new[](std::size_t) throw(std::bad_alloc);
1362 // void operator delete(void*) throw();
Douglas Gregor87f54062009-09-15 22:30:29 +00001363 // void operator delete[](void*) throw();
1364 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001365 // These implicit declarations introduce only the function names operator
Douglas Gregor87f54062009-09-15 22:30:29 +00001366 // new, operator new[], operator delete, operator delete[].
1367 //
1368 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1369 // "std" or "bad_alloc" as necessary to form the exception specification.
1370 // However, we do not make these implicit declarations visible to name
1371 // lookup.
Douglas Gregor87f54062009-09-15 22:30:29 +00001372 if (!StdBadAlloc) {
1373 // The "std::bad_alloc" class has not yet been declared, so build it
1374 // implicitly.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001375 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1376 getOrCreateStdNamespace(),
1377 SourceLocation(),
1378 &PP.getIdentifierTable().get("bad_alloc"),
Douglas Gregor87f54062009-09-15 22:30:29 +00001379 SourceLocation(), 0);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00001380 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00001381 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001382
Sebastian Redlfaf68082008-12-03 20:26:15 +00001383 GlobalNewDeleteDeclared = true;
1384
1385 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1386 QualType SizeT = Context.getSizeType();
Nuno Lopes13c88c72009-12-16 16:59:22 +00001387 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001388
Sebastian Redlfaf68082008-12-03 20:26:15 +00001389 DeclareGlobalAllocationFunction(
1390 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001391 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001392 DeclareGlobalAllocationFunction(
1393 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001394 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001395 DeclareGlobalAllocationFunction(
1396 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1397 Context.VoidTy, VoidPtr);
1398 DeclareGlobalAllocationFunction(
1399 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1400 Context.VoidTy, VoidPtr);
1401}
1402
1403/// DeclareGlobalAllocationFunction - Declares a single implicit global
1404/// allocation function if it doesn't already exist.
1405void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopes13c88c72009-12-16 16:59:22 +00001406 QualType Return, QualType Argument,
1407 bool AddMallocAttr) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001408 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1409
1410 // Check if this function is already declared.
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001411 {
Douglas Gregor17eb26b2008-12-23 22:05:29 +00001412 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001413 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001414 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth93538422010-02-03 11:02:14 +00001415 // Only look at non-template functions, as it is the predefined,
1416 // non-templated allocation function we are trying to declare here.
1417 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1418 QualType InitialParamType =
Douglas Gregor684d7bd2009-12-22 23:42:49 +00001419 Context.getCanonicalType(
Chandler Carruth93538422010-02-03 11:02:14 +00001420 Func->getParamDecl(0)->getType().getUnqualifiedType());
1421 // FIXME: Do we need to check for default arguments here?
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00001422 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1423 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001424 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth93538422010-02-03 11:02:14 +00001425 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00001426 }
Chandler Carruth93538422010-02-03 11:02:14 +00001427 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00001428 }
1429 }
1430
Douglas Gregor87f54062009-09-15 22:30:29 +00001431 QualType BadAllocType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001432 bool HasBadAllocExceptionSpec
Douglas Gregor87f54062009-09-15 22:30:29 +00001433 = (Name.getCXXOverloadedOperator() == OO_New ||
1434 Name.getCXXOverloadedOperator() == OO_Array_New);
1435 if (HasBadAllocExceptionSpec) {
1436 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00001437 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor87f54062009-09-15 22:30:29 +00001438 }
John McCalldb40c7f2010-12-14 08:05:40 +00001439
1440 FunctionProtoType::ExtProtoInfo EPI;
1441 EPI.HasExceptionSpec = true;
1442 if (HasBadAllocExceptionSpec) {
1443 EPI.NumExceptions = 1;
1444 EPI.Exceptions = &BadAllocType;
1445 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001446
John McCalldb40c7f2010-12-14 08:05:40 +00001447 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001448 FunctionDecl *Alloc =
1449 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCall8e7d6562010-08-26 03:08:43 +00001450 FnType, /*TInfo=*/0, SC_None,
1451 SC_None, false, true);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001452 Alloc->setImplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001453
Nuno Lopes13c88c72009-12-16 16:59:22 +00001454 if (AddMallocAttr)
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001455 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001456
Sebastian Redlfaf68082008-12-03 20:26:15 +00001457 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCallbcd03502009-12-07 02:54:59 +00001458 0, Argument, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00001459 SC_None,
1460 SC_None, 0);
Douglas Gregord5058122010-02-11 01:19:42 +00001461 Alloc->setParams(&Param, 1);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001462
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001463 // FIXME: Also add this declaration to the IdentifierResolver, but
1464 // make sure it is at the end of the chain to coincide with the
1465 // global scope.
John McCallcc14d1f2010-08-24 08:50:51 +00001466 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001467}
1468
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001469bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1470 DeclarationName Name,
Anders Carlssonf98849e2009-12-02 17:15:43 +00001471 FunctionDecl* &Operator) {
John McCall27b18f82009-11-17 02:14:36 +00001472 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001473 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00001474 LookupQualifiedName(Found, RD);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001475
John McCall27b18f82009-11-17 02:14:36 +00001476 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001477 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001478
Chandler Carruthb6f99172010-06-28 00:30:51 +00001479 Found.suppressDiagnostics();
1480
John McCall66a87592010-08-04 00:31:26 +00001481 llvm::SmallVector<DeclAccessPair,4> Matches;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001482 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1483 F != FEnd; ++F) {
Chandler Carruth9b418232010-08-08 07:04:00 +00001484 NamedDecl *ND = (*F)->getUnderlyingDecl();
1485
1486 // Ignore template operator delete members from the check for a usual
1487 // deallocation function.
1488 if (isa<FunctionTemplateDecl>(ND))
1489 continue;
1490
1491 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall66a87592010-08-04 00:31:26 +00001492 Matches.push_back(F.getPair());
1493 }
1494
1495 // There's exactly one suitable operator; pick it.
1496 if (Matches.size() == 1) {
1497 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
1498 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1499 Matches[0]);
1500 return false;
1501
1502 // We found multiple suitable operators; complain about the ambiguity.
1503 } else if (!Matches.empty()) {
1504 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1505 << Name << RD;
1506
1507 for (llvm::SmallVectorImpl<DeclAccessPair>::iterator
1508 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1509 Diag((*F)->getUnderlyingDecl()->getLocation(),
1510 diag::note_member_declared_here) << Name;
1511 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001512 }
1513
1514 // We did find operator delete/operator delete[] declarations, but
1515 // none of them were suitable.
1516 if (!Found.empty()) {
1517 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1518 << Name << RD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001519
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001520 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
John McCall66a87592010-08-04 00:31:26 +00001521 F != FEnd; ++F)
1522 Diag((*F)->getUnderlyingDecl()->getLocation(),
1523 diag::note_member_declared_here) << Name;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001524
1525 return true;
1526 }
1527
1528 // Look for a global declaration.
1529 DeclareGlobalNewDelete();
1530 DeclContext *TUDecl = Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001531
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001532 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1533 Expr* DeallocArgs[1];
1534 DeallocArgs[0] = &Null;
1535 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1536 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1537 Operator))
1538 return true;
1539
1540 assert(Operator && "Did not find a deallocation function!");
1541 return false;
1542}
1543
Sebastian Redlbd150f42008-11-21 19:14:01 +00001544/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1545/// @code ::delete ptr; @endcode
1546/// or
1547/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00001548ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001549Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John McCallb268a282010-08-23 23:25:46 +00001550 bool ArrayForm, Expr *Ex) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001551 // C++ [expr.delete]p1:
1552 // The operand shall have a pointer type, or a class type having a single
1553 // conversion function to a pointer type. The result has type void.
1554 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00001555 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1556
Anders Carlssona471db02009-08-16 20:29:29 +00001557 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00001558 bool ArrayFormAsWritten = ArrayForm;
John McCall284c48f2011-01-27 09:37:56 +00001559 bool UsualArrayDeleteWantsSize = false;
Mike Stump11289f42009-09-09 15:08:12 +00001560
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001561 if (!Ex->isTypeDependent()) {
1562 QualType Type = Ex->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00001563
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001564 if (const RecordType *Record = Type->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001565 if (RequireCompleteType(StartLoc, Type,
Douglas Gregorf65f4902010-07-29 14:44:35 +00001566 PDiag(diag::err_delete_incomplete_class_type)))
1567 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001568
John McCallda4458e2010-03-31 01:36:47 +00001569 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1570
Fariborz Jahanianb54ccb22009-09-11 21:44:33 +00001571 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001572 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001573 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001574 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00001575 NamedDecl *D = I.getDecl();
1576 if (isa<UsingShadowDecl>(D))
1577 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1578
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001579 // Skip over templated conversion functions; they aren't considered.
John McCallda4458e2010-03-31 01:36:47 +00001580 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001581 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001582
John McCallda4458e2010-03-31 01:36:47 +00001583 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001584
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001585 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1586 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00001587 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001588 ObjectPtrConversions.push_back(Conv);
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001589 }
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001590 if (ObjectPtrConversions.size() == 1) {
1591 // We have a single conversion to a pointer-to-object type. Perform
1592 // that conversion.
John McCallda4458e2010-03-31 01:36:47 +00001593 // TODO: don't redo the conversion calculation.
John McCallda4458e2010-03-31 01:36:47 +00001594 if (!PerformImplicitConversion(Ex,
1595 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001596 AA_Converting)) {
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001597 Type = Ex->getType();
1598 }
1599 }
1600 else if (ObjectPtrConversions.size() > 1) {
1601 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1602 << Type << Ex->getSourceRange();
John McCallda4458e2010-03-31 01:36:47 +00001603 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1604 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001605 return ExprError();
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001606 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001607 }
1608
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001609 if (!Type->isPointerType())
1610 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1611 << Type << Ex->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001612
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001613 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregorbb3348e2010-05-24 17:01:56 +00001614 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001615 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregorbb3348e2010-05-24 17:01:56 +00001616 // effectively bans deletion of "void*". However, most compilers support
1617 // this, so we treat it as a warning unless we're in a SFINAE context.
1618 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1619 << Type << Ex->getSourceRange();
1620 } else if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001621 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1622 << Type << Ex->getSourceRange());
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001623 else if (!Pointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00001624 RequireCompleteType(StartLoc, Pointee,
Anders Carlssond624e162009-08-26 23:45:07 +00001625 PDiag(diag::warn_delete_incomplete)
1626 << Ex->getSourceRange()))
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001627 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001628
Douglas Gregor98496dc2009-09-29 21:38:53 +00001629 // C++ [expr.delete]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001630 // [Note: a pointer to a const type can be the operand of a
1631 // delete-expression; it is not necessary to cast away the constness
1632 // (5.2.11) of the pointer expression before it is used as the operand
Douglas Gregor98496dc2009-09-29 21:38:53 +00001633 // of the delete-expression. ]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001634 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
John McCalle3027922010-08-25 11:45:40 +00001635 CK_NoOp);
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00001636
1637 if (Pointee->isArrayType() && !ArrayForm) {
1638 Diag(StartLoc, diag::warn_delete_array_type)
1639 << Type << Ex->getSourceRange()
1640 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1641 ArrayForm = true;
1642 }
1643
Anders Carlssona471db02009-08-16 20:29:29 +00001644 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1645 ArrayForm ? OO_Array_Delete : OO_Delete);
1646
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001647 QualType PointeeElem = Context.getBaseElementType(Pointee);
1648 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001649 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1650
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001651 if (!UseGlobal &&
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001652 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00001653 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001654
John McCall284c48f2011-01-27 09:37:56 +00001655 // If we're allocating an array of records, check whether the
1656 // usual operator delete[] has a size_t parameter.
1657 if (ArrayForm) {
1658 // If the user specifically asked to use the global allocator,
1659 // we'll need to do the lookup into the class.
1660 if (UseGlobal)
1661 UsualArrayDeleteWantsSize =
1662 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
1663
1664 // Otherwise, the usual operator delete[] should be the
1665 // function we just found.
1666 else if (isa<CXXMethodDecl>(OperatorDelete))
1667 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
1668 }
1669
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001670 if (!RD->hasTrivialDestructor())
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001671 if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
Mike Stump11289f42009-09-09 15:08:12 +00001672 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001673 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001674 DiagnoseUseOfDecl(Dtor, StartLoc);
1675 }
Anders Carlssona471db02009-08-16 20:29:29 +00001676 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001677
Anders Carlssona471db02009-08-16 20:29:29 +00001678 if (!OperatorDelete) {
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001679 // Look for a global declaration.
Anders Carlssona471db02009-08-16 20:29:29 +00001680 DeclareGlobalNewDelete();
1681 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001682 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001683 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssona471db02009-08-16 20:29:29 +00001684 OperatorDelete))
1685 return ExprError();
1686 }
Mike Stump11289f42009-09-09 15:08:12 +00001687
John McCall0f55a032010-04-20 02:18:25 +00001688 MarkDeclarationReferenced(StartLoc, OperatorDelete);
John McCall284c48f2011-01-27 09:37:56 +00001689
Douglas Gregorfa778132011-02-01 15:50:11 +00001690 // Check access and ambiguity of operator delete and destructor.
1691 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
1692 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1693 if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
1694 CheckDestructorAccess(Ex->getExprLoc(), Dtor,
1695 PDiag(diag::err_access_dtor) << PointeeElem);
1696 }
1697 }
1698
Sebastian Redlbd150f42008-11-21 19:14:01 +00001699 }
1700
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001701 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
John McCall284c48f2011-01-27 09:37:56 +00001702 ArrayFormAsWritten,
1703 UsualArrayDeleteWantsSize,
1704 OperatorDelete, Ex, StartLoc));
Sebastian Redlbd150f42008-11-21 19:14:01 +00001705}
1706
Douglas Gregor633caca2009-11-23 23:44:04 +00001707/// \brief Check the use of the given variable as a C++ condition in an if,
1708/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00001709ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00001710 SourceLocation StmtLoc,
1711 bool ConvertToBoolean) {
Douglas Gregor633caca2009-11-23 23:44:04 +00001712 QualType T = ConditionVar->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001713
Douglas Gregor633caca2009-11-23 23:44:04 +00001714 // C++ [stmt.select]p2:
1715 // The declarator shall not specify a function or an array.
1716 if (T->isFunctionType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001717 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00001718 diag::err_invalid_use_of_function_type)
1719 << ConditionVar->getSourceRange());
1720 else if (T->isArrayType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001721 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00001722 diag::err_invalid_use_of_array_type)
1723 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00001724
Douglas Gregore60e41a2010-05-06 17:25:47 +00001725 Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001726 ConditionVar->getLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00001727 ConditionVar->getType().getNonReferenceType(),
John McCall4bc41ae2010-11-18 19:01:18 +00001728 VK_LValue);
Douglas Gregorb412e172010-07-25 18:17:45 +00001729 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc))
Douglas Gregore60e41a2010-05-06 17:25:47 +00001730 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001731
Douglas Gregore60e41a2010-05-06 17:25:47 +00001732 return Owned(Condition);
Douglas Gregor633caca2009-11-23 23:44:04 +00001733}
1734
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001735/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1736bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1737 // C++ 6.4p4:
1738 // The value of a condition that is an initialized declaration in a statement
1739 // other than a switch statement is the value of the declared variable
1740 // implicitly converted to type bool. If that conversion is ill-formed, the
1741 // program is ill-formed.
1742 // The value of a condition that is an expression is the value of the
1743 // expression, implicitly converted to bool.
1744 //
Douglas Gregor5fb53972009-01-14 15:45:31 +00001745 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001746}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001747
1748/// Helper function to determine whether this is the (deprecated) C++
1749/// conversion from a string literal to a pointer to non-const char or
1750/// non-const wchar_t (for narrow and wide string literals,
1751/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00001752bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001753Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1754 // Look inside the implicit cast, if it exists.
1755 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1756 From = Cast->getSubExpr();
1757
1758 // A string literal (2.13.4) that is not a wide string literal can
1759 // be converted to an rvalue of type "pointer to char"; a wide
1760 // string literal can be converted to an rvalue of type "pointer
1761 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00001762 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001763 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001764 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00001765 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001766 // This conversion is considered only when there is an
1767 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall8ccfcb52009-09-24 19:53:00 +00001768 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001769 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1770 (!StrLit->isWide() &&
1771 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1772 ToPointeeType->getKind() == BuiltinType::Char_S))))
1773 return true;
1774 }
1775
1776 return false;
1777}
Douglas Gregor39c16d42008-10-24 04:54:22 +00001778
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001779static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00001780 SourceLocation CastLoc,
1781 QualType Ty,
1782 CastKind Kind,
1783 CXXMethodDecl *Method,
Douglas Gregor2bbfba02011-01-20 01:32:05 +00001784 NamedDecl *FoundDecl,
John McCalle3027922010-08-25 11:45:40 +00001785 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00001786 switch (Kind) {
1787 default: assert(0 && "Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00001788 case CK_ConstructorConversion: {
John McCall37ad5512010-08-23 06:44:23 +00001789 ASTOwningVector<Expr*> ConstructorArgs(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001790
Douglas Gregora4253922010-04-16 22:17:36 +00001791 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
John McCallfaf5fb42010-08-26 23:41:50 +00001792 MultiExprArg(&From, 1),
Douglas Gregora4253922010-04-16 22:17:36 +00001793 CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00001794 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001795
1796 ExprResult Result =
1797 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
John McCallbfd822c2010-08-24 07:32:53 +00001798 move_arg(ConstructorArgs),
Chandler Carruth01718152010-10-25 08:47:36 +00001799 /*ZeroInit*/ false, CXXConstructExpr::CK_Complete,
1800 SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00001801 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00001802 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001803
Douglas Gregora4253922010-04-16 22:17:36 +00001804 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1805 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001806
John McCalle3027922010-08-25 11:45:40 +00001807 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00001808 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001809
Douglas Gregora4253922010-04-16 22:17:36 +00001810 // Create an implicit call expr that calls it.
Douglas Gregor2bbfba02011-01-20 01:32:05 +00001811 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method);
Douglas Gregor668443e2011-01-20 00:18:04 +00001812 if (Result.isInvalid())
1813 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001814
Douglas Gregor668443e2011-01-20 00:18:04 +00001815 return S.MaybeBindToTemporary(Result.get());
Douglas Gregora4253922010-04-16 22:17:36 +00001816 }
1817 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001818}
Douglas Gregora4253922010-04-16 22:17:36 +00001819
Douglas Gregor5fb53972009-01-14 15:45:31 +00001820/// PerformImplicitConversion - Perform an implicit conversion of the
1821/// expression From to the type ToType using the pre-computed implicit
1822/// conversion sequence ICS. Returns true if there was an error, false
1823/// otherwise. The expression From is replaced with the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001824/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001825/// used in the error message.
1826bool
1827Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1828 const ImplicitConversionSequence &ICS,
Douglas Gregor58281352011-01-27 00:58:17 +00001829 AssignmentAction Action, bool CStyle) {
John McCall0d1da222010-01-12 00:44:57 +00001830 switch (ICS.getKind()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001831 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001832 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Douglas Gregor58281352011-01-27 00:58:17 +00001833 CStyle))
Douglas Gregor39c16d42008-10-24 04:54:22 +00001834 return true;
1835 break;
1836
Anders Carlsson110b07b2009-09-15 06:28:28 +00001837 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001838
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00001839 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00001840 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00001841 QualType BeforeToType;
1842 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00001843 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001844
Anders Carlsson110b07b2009-09-15 06:28:28 +00001845 // If the user-defined conversion is specified by a conversion function,
1846 // the initial standard conversion sequence converts the source type to
1847 // the implicit object parameter of the conversion function.
1848 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00001849 } else {
1850 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00001851 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001852 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00001853 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001854 // If the user-defined conversion is specified by a constructor, the
Fariborz Jahanian55824512009-11-06 00:23:08 +00001855 // initial standard conversion sequence converts the source type to the
1856 // type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00001857 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1858 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001859 }
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00001860 // Watch out for elipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00001861 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001862 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001863 ICS.UserDefined.Before, AA_Converting,
Douglas Gregor58281352011-01-27 00:58:17 +00001864 CStyle))
Fariborz Jahanian55824512009-11-06 00:23:08 +00001865 return true;
1866 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001867
1868 ExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00001869 = BuildCXXCastArgument(*this,
1870 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00001871 ToType.getNonReferenceType(),
Douglas Gregor2bbfba02011-01-20 01:32:05 +00001872 CastKind, cast<CXXMethodDecl>(FD),
1873 ICS.UserDefined.FoundConversionFunction,
John McCallb268a282010-08-23 23:25:46 +00001874 From);
Anders Carlssone9766d52009-09-09 21:33:21 +00001875
1876 if (CastArg.isInvalid())
1877 return true;
Eli Friedmane96f1d32009-11-27 04:41:50 +00001878
1879 From = CastArg.takeAs<Expr>();
1880
Eli Friedmane96f1d32009-11-27 04:41:50 +00001881 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor58281352011-01-27 00:58:17 +00001882 AA_Converting, CStyle);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00001883 }
John McCall0d1da222010-01-12 00:44:57 +00001884
1885 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00001886 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00001887 PDiag(diag::err_typecheck_ambiguous_condition)
1888 << From->getSourceRange());
1889 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001890
Douglas Gregor39c16d42008-10-24 04:54:22 +00001891 case ImplicitConversionSequence::EllipsisConversion:
1892 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001893 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001894
1895 case ImplicitConversionSequence::BadConversion:
1896 return true;
1897 }
1898
1899 // Everything went well.
1900 return false;
1901}
1902
1903/// PerformImplicitConversion - Perform an implicit conversion of the
1904/// expression From to the type ToType by following the standard
1905/// conversion sequence SCS. Returns true if there was an error, false
1906/// otherwise. The expression From is replaced with the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00001907/// expression. Flavor is the context in which we're performing this
1908/// conversion, for use in error messages.
Mike Stump11289f42009-09-09 15:08:12 +00001909bool
Douglas Gregor39c16d42008-10-24 04:54:22 +00001910Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001911 const StandardConversionSequence& SCS,
Douglas Gregor58281352011-01-27 00:58:17 +00001912 AssignmentAction Action, bool CStyle) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001913 // Overall FIXME: we are recomputing too many types here and doing far too
1914 // much extra work. What this means is that we need to keep track of more
1915 // information that is computed when we try the implicit conversion initially,
1916 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00001917 QualType FromType = From->getType();
1918
Douglas Gregor2fe98832008-11-03 19:09:14 +00001919 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00001920 // FIXME: When can ToType be a reference type?
1921 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00001922 if (SCS.Second == ICK_Derived_To_Base) {
John McCall37ad5512010-08-23 06:44:23 +00001923 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanian49850df2009-09-25 18:59:21 +00001924 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCall37ad5512010-08-23 06:44:23 +00001925 MultiExprArg(*this, &From, 1),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001926 /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00001927 ConstructorArgs))
1928 return true;
John McCalldadc5752010-08-24 06:29:42 +00001929 ExprResult FromResult =
Fariborz Jahanian49850df2009-09-25 18:59:21 +00001930 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1931 ToType, SCS.CopyConstructor,
John McCallbfd822c2010-08-24 07:32:53 +00001932 move_arg(ConstructorArgs),
1933 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00001934 CXXConstructExpr::CK_Complete,
1935 SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00001936 if (FromResult.isInvalid())
1937 return true;
1938 From = FromResult.takeAs<Expr>();
1939 return false;
1940 }
John McCalldadc5752010-08-24 06:29:42 +00001941 ExprResult FromResult =
Mike Stump11289f42009-09-09 15:08:12 +00001942 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1943 ToType, SCS.CopyConstructor,
John McCallbfd822c2010-08-24 07:32:53 +00001944 MultiExprArg(*this, &From, 1),
1945 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00001946 CXXConstructExpr::CK_Complete,
1947 SourceRange());
Mike Stump11289f42009-09-09 15:08:12 +00001948
Anders Carlsson6eb55572009-08-25 05:12:04 +00001949 if (FromResult.isInvalid())
1950 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001951
Anders Carlsson6eb55572009-08-25 05:12:04 +00001952 From = FromResult.takeAs<Expr>();
Douglas Gregor2fe98832008-11-03 19:09:14 +00001953 return false;
1954 }
1955
Douglas Gregor980fb162010-04-29 18:24:40 +00001956 // Resolve overloaded function references.
1957 if (Context.hasSameType(FromType, Context.OverloadTy)) {
1958 DeclAccessPair Found;
1959 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1960 true, Found);
1961 if (!Fn)
1962 return true;
1963
1964 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1965 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001966
Douglas Gregor980fb162010-04-29 18:24:40 +00001967 From = FixOverloadedFunctionReference(From, Found, Fn);
1968 FromType = From->getType();
1969 }
1970
Douglas Gregor39c16d42008-10-24 04:54:22 +00001971 // Perform the first implicit conversion.
1972 switch (SCS.First) {
1973 case ICK_Identity:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001974 // Nothing to do.
1975 break;
1976
John McCall34376a62010-12-04 03:47:34 +00001977 case ICK_Lvalue_To_Rvalue:
1978 // Should this get its own ICK?
1979 if (From->getObjectKind() == OK_ObjCProperty) {
1980 ConvertPropertyForRValue(From);
John McCalled75c092010-12-07 22:54:16 +00001981 if (!From->isGLValue()) break;
John McCall34376a62010-12-04 03:47:34 +00001982 }
1983
1984 FromType = FromType.getUnqualifiedType();
1985 From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
1986 From, 0, VK_RValue);
1987 break;
1988
Douglas Gregor39c16d42008-10-24 04:54:22 +00001989 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00001990 FromType = Context.getArrayDecayedType(FromType);
John McCalle3027922010-08-25 11:45:40 +00001991 ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001992 break;
1993
1994 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001995 FromType = Context.getPointerType(FromType);
John McCalle3027922010-08-25 11:45:40 +00001996 ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001997 break;
1998
1999 default:
2000 assert(false && "Improper first standard conversion");
2001 break;
2002 }
2003
2004 // Perform the second implicit conversion
2005 switch (SCS.Second) {
2006 case ICK_Identity:
Sebastian Redl5d431642009-10-10 12:04:10 +00002007 // If both sides are functions (or pointers/references to them), there could
2008 // be incompatible exception declarations.
2009 if (CheckExceptionSpecCompatibility(From, ToType))
2010 return true;
2011 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00002012 break;
2013
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00002014 case ICK_NoReturn_Adjustment:
2015 // If both sides are functions (or pointers/references to them), there could
2016 // be incompatible exception declarations.
2017 if (CheckExceptionSpecCompatibility(From, ToType))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002018 return true;
2019
John McCall4f5019e2010-12-19 02:44:49 +00002020 ImpCastExprToType(From, ToType, CK_NoOp);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00002021 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002022
Douglas Gregor39c16d42008-10-24 04:54:22 +00002023 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002024 case ICK_Integral_Conversion:
John McCalle3027922010-08-25 11:45:40 +00002025 ImpCastExprToType(From, ToType, CK_IntegralCast);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002026 break;
2027
2028 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002029 case ICK_Floating_Conversion:
John McCalle3027922010-08-25 11:45:40 +00002030 ImpCastExprToType(From, ToType, CK_FloatingCast);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002031 break;
2032
2033 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00002034 case ICK_Complex_Conversion: {
2035 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2036 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2037 CastKind CK;
2038 if (FromEl->isRealFloatingType()) {
2039 if (ToEl->isRealFloatingType())
2040 CK = CK_FloatingComplexCast;
2041 else
2042 CK = CK_FloatingComplexToIntegralComplex;
2043 } else if (ToEl->isRealFloatingType()) {
2044 CK = CK_IntegralComplexToFloatingComplex;
2045 } else {
2046 CK = CK_IntegralComplexCast;
2047 }
2048 ImpCastExprToType(From, ToType, CK);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002049 break;
John McCall8cb679e2010-11-15 09:13:47 +00002050 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00002051
Douglas Gregor39c16d42008-10-24 04:54:22 +00002052 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00002053 if (ToType->isRealFloatingType())
John McCalle3027922010-08-25 11:45:40 +00002054 ImpCastExprToType(From, ToType, CK_IntegralToFloating);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002055 else
John McCalle3027922010-08-25 11:45:40 +00002056 ImpCastExprToType(From, ToType, CK_FloatingToIntegral);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002057 break;
2058
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002059 case ICK_Compatible_Conversion:
John McCalle3027922010-08-25 11:45:40 +00002060 ImpCastExprToType(From, ToType, CK_NoOp);
Douglas Gregor39c16d42008-10-24 04:54:22 +00002061 break;
2062
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002063 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00002064 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002065 // Diagnose incompatible Objective-C conversions
Mike Stump11289f42009-09-09 15:08:12 +00002066 Diag(From->getSourceRange().getBegin(),
Douglas Gregor47d3f272008-12-19 17:40:08 +00002067 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002068 << From->getType() << ToType << Action
Douglas Gregor47d3f272008-12-19 17:40:08 +00002069 << From->getSourceRange();
2070 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002071
John McCall8cb679e2010-11-15 09:13:47 +00002072 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00002073 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00002074 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
Douglas Gregor39c16d42008-10-24 04:54:22 +00002075 return true;
John McCall2536c6d2010-08-25 10:28:54 +00002076 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
Douglas Gregor39c16d42008-10-24 04:54:22 +00002077 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002078 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002079
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002080 case ICK_Pointer_Member: {
John McCall8cb679e2010-11-15 09:13:47 +00002081 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00002082 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00002083 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002084 return true;
Sebastian Redl5d431642009-10-10 12:04:10 +00002085 if (CheckExceptionSpecCompatibility(From, ToType))
2086 return true;
John McCall2536c6d2010-08-25 10:28:54 +00002087 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002088 break;
2089 }
Anders Carlsson7fa434c2009-11-23 20:04:44 +00002090 case ICK_Boolean_Conversion: {
John McCall8cb679e2010-11-15 09:13:47 +00002091 CastKind Kind = CK_Invalid;
2092 switch (FromType->getScalarTypeKind()) {
2093 case Type::STK_Pointer: Kind = CK_PointerToBoolean; break;
2094 case Type::STK_MemberPointer: Kind = CK_MemberPointerToBoolean; break;
2095 case Type::STK_Bool: llvm_unreachable("bool -> bool conversion?");
2096 case Type::STK_Integral: Kind = CK_IntegralToBoolean; break;
2097 case Type::STK_Floating: Kind = CK_FloatingToBoolean; break;
2098 case Type::STK_IntegralComplex: Kind = CK_IntegralComplexToBoolean; break;
2099 case Type::STK_FloatingComplex: Kind = CK_FloatingComplexToBoolean; break;
2100 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002101
Anders Carlsson7fa434c2009-11-23 20:04:44 +00002102 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor39c16d42008-10-24 04:54:22 +00002103 break;
Anders Carlsson7fa434c2009-11-23 20:04:44 +00002104 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00002105
Douglas Gregor88d292c2010-05-13 16:44:06 +00002106 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00002107 CXXCastPath BasePath;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002108 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00002109 ToType.getNonReferenceType(),
2110 From->getLocStart(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002111 From->getSourceRange(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00002112 &BasePath,
Douglas Gregor58281352011-01-27 00:58:17 +00002113 CStyle))
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00002114 return true;
Douglas Gregor88d292c2010-05-13 16:44:06 +00002115
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002116 ImpCastExprToType(From, ToType.getNonReferenceType(),
John McCalle3027922010-08-25 11:45:40 +00002117 CK_DerivedToBase, CastCategory(From),
John McCallcf142162010-08-07 06:22:56 +00002118 &BasePath);
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00002119 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00002120 }
2121
Douglas Gregor46188682010-05-18 22:42:18 +00002122 case ICK_Vector_Conversion:
John McCalle3027922010-08-25 11:45:40 +00002123 ImpCastExprToType(From, ToType, CK_BitCast);
Douglas Gregor46188682010-05-18 22:42:18 +00002124 break;
2125
2126 case ICK_Vector_Splat:
John McCalle3027922010-08-25 11:45:40 +00002127 ImpCastExprToType(From, ToType, CK_VectorSplat);
Douglas Gregor46188682010-05-18 22:42:18 +00002128 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002129
Douglas Gregor46188682010-05-18 22:42:18 +00002130 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00002131 // Case 1. x -> _Complex y
2132 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2133 QualType ElType = ToComplex->getElementType();
2134 bool isFloatingComplex = ElType->isRealFloatingType();
2135
2136 // x -> y
2137 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2138 // do nothing
2139 } else if (From->getType()->isRealFloatingType()) {
2140 ImpCastExprToType(From, ElType,
2141 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral);
2142 } else {
2143 assert(From->getType()->isIntegerType());
2144 ImpCastExprToType(From, ElType,
2145 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast);
2146 }
2147 // y -> _Complex y
2148 ImpCastExprToType(From, ToType,
2149 isFloatingComplex ? CK_FloatingRealToComplex
2150 : CK_IntegralRealToComplex);
2151
2152 // Case 2. _Complex x -> y
2153 } else {
2154 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2155 assert(FromComplex);
2156
2157 QualType ElType = FromComplex->getElementType();
2158 bool isFloatingComplex = ElType->isRealFloatingType();
2159
2160 // _Complex x -> x
2161 ImpCastExprToType(From, ElType,
2162 isFloatingComplex ? CK_FloatingComplexToReal
2163 : CK_IntegralComplexToReal);
2164
2165 // x -> y
2166 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2167 // do nothing
2168 } else if (ToType->isRealFloatingType()) {
2169 ImpCastExprToType(From, ToType,
2170 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating);
2171 } else {
2172 assert(ToType->isIntegerType());
2173 ImpCastExprToType(From, ToType,
2174 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast);
2175 }
2176 }
Douglas Gregor46188682010-05-18 22:42:18 +00002177 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002178
Douglas Gregor46188682010-05-18 22:42:18 +00002179 case ICK_Lvalue_To_Rvalue:
2180 case ICK_Array_To_Pointer:
2181 case ICK_Function_To_Pointer:
2182 case ICK_Qualification:
2183 case ICK_Num_Conversion_Kinds:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002184 assert(false && "Improper second standard conversion");
2185 break;
2186 }
2187
2188 switch (SCS.Third) {
2189 case ICK_Identity:
2190 // Nothing to do.
2191 break;
2192
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002193 case ICK_Qualification: {
2194 // The qualification keeps the category of the inner expression, unless the
2195 // target type isn't a reference.
John McCall2536c6d2010-08-25 10:28:54 +00002196 ExprValueKind VK = ToType->isReferenceType() ?
2197 CastCategory(From) : VK_RValue;
Douglas Gregora8a089b2010-07-13 18:40:04 +00002198 ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
John McCalle3027922010-08-25 11:45:40 +00002199 CK_NoOp, VK);
Douglas Gregore489a7d2010-02-28 18:30:25 +00002200
2201 if (SCS.DeprecatedStringLiteralToCharPtr)
2202 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2203 << ToType.getNonReferenceType();
2204
Douglas Gregor39c16d42008-10-24 04:54:22 +00002205 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002206 }
2207
Douglas Gregor39c16d42008-10-24 04:54:22 +00002208 default:
Douglas Gregor46188682010-05-18 22:42:18 +00002209 assert(false && "Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00002210 break;
2211 }
2212
2213 return false;
2214}
2215
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002216ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor54e5b132010-09-09 16:14:44 +00002217 SourceLocation KWLoc,
2218 ParsedType Ty,
2219 SourceLocation RParen) {
2220 TypeSourceInfo *TSInfo;
2221 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump11289f42009-09-09 15:08:12 +00002222
Douglas Gregor54e5b132010-09-09 16:14:44 +00002223 if (!TSInfo)
2224 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002225 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor54e5b132010-09-09 16:14:44 +00002226}
2227
Sebastian Redl058fc822010-09-14 23:40:14 +00002228static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT, QualType T,
2229 SourceLocation KeyLoc) {
Douglas Gregore5bef032011-01-27 20:35:44 +00002230 // FIXME: For many of these traits, we need a complete type before we can
2231 // check these properties.
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002232 assert(!T->isDependentType() &&
2233 "Cannot evaluate traits for dependent types.");
2234 ASTContext &C = Self.Context;
2235 switch(UTT) {
2236 default: assert(false && "Unknown type trait or not implemented");
2237 case UTT_IsPOD: return T->isPODType();
2238 case UTT_IsLiteral: return T->isLiteralType();
2239 case UTT_IsClass: // Fallthrough
2240 case UTT_IsUnion:
2241 if (const RecordType *Record = T->getAs<RecordType>()) {
2242 bool Union = Record->getDecl()->isUnion();
2243 return UTT == UTT_IsUnion ? Union : !Union;
2244 }
2245 return false;
2246 case UTT_IsEnum: return T->isEnumeralType();
2247 case UTT_IsPolymorphic:
2248 if (const RecordType *Record = T->getAs<RecordType>()) {
2249 // Type traits are only parsed in C++, so we've got CXXRecords.
2250 return cast<CXXRecordDecl>(Record->getDecl())->isPolymorphic();
2251 }
2252 return false;
2253 case UTT_IsAbstract:
2254 if (const RecordType *RT = T->getAs<RecordType>())
2255 return cast<CXXRecordDecl>(RT->getDecl())->isAbstract();
2256 return false;
2257 case UTT_IsEmpty:
2258 if (const RecordType *Record = T->getAs<RecordType>()) {
2259 return !Record->getDecl()->isUnion()
2260 && cast<CXXRecordDecl>(Record->getDecl())->isEmpty();
2261 }
2262 return false;
2263 case UTT_HasTrivialConstructor:
2264 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2265 // If __is_pod (type) is true then the trait is true, else if type is
2266 // a cv class or union type (or array thereof) with a trivial default
2267 // constructor ([class.ctor]) then the trait is true, else it is false.
2268 if (T->isPODType())
2269 return true;
2270 if (const RecordType *RT =
2271 C.getBaseElementType(T)->getAs<RecordType>())
2272 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialConstructor();
2273 return false;
2274 case UTT_HasTrivialCopy:
2275 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2276 // If __is_pod (type) is true or type is a reference type then
2277 // the trait is true, else if type is a cv class or union type
2278 // with a trivial copy constructor ([class.copy]) then the trait
2279 // is true, else it is false.
2280 if (T->isPODType() || T->isReferenceType())
2281 return true;
2282 if (const RecordType *RT = T->getAs<RecordType>())
2283 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2284 return false;
2285 case UTT_HasTrivialAssign:
2286 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2287 // If type is const qualified or is a reference type then the
2288 // trait is false. Otherwise if __is_pod (type) is true then the
2289 // trait is true, else if type is a cv class or union type with
2290 // a trivial copy assignment ([class.copy]) then the trait is
2291 // true, else it is false.
2292 // Note: the const and reference restrictions are interesting,
2293 // given that const and reference members don't prevent a class
2294 // from having a trivial copy assignment operator (but do cause
2295 // errors if the copy assignment operator is actually used, q.v.
2296 // [class.copy]p12).
2297
2298 if (C.getBaseElementType(T).isConstQualified())
2299 return false;
2300 if (T->isPODType())
2301 return true;
2302 if (const RecordType *RT = T->getAs<RecordType>())
2303 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2304 return false;
2305 case UTT_HasTrivialDestructor:
2306 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2307 // If __is_pod (type) is true or type is a reference type
2308 // then the trait is true, else if type is a cv class or union
2309 // type (or array thereof) with a trivial destructor
2310 // ([class.dtor]) then the trait is true, else it is
2311 // false.
2312 if (T->isPODType() || T->isReferenceType())
2313 return true;
2314 if (const RecordType *RT =
2315 C.getBaseElementType(T)->getAs<RecordType>())
2316 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2317 return false;
2318 // TODO: Propagate nothrowness for implicitly declared special members.
2319 case UTT_HasNothrowAssign:
2320 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2321 // If type is const qualified or is a reference type then the
2322 // trait is false. Otherwise if __has_trivial_assign (type)
2323 // is true then the trait is true, else if type is a cv class
2324 // or union type with copy assignment operators that are known
2325 // not to throw an exception then the trait is true, else it is
2326 // false.
2327 if (C.getBaseElementType(T).isConstQualified())
2328 return false;
2329 if (T->isReferenceType())
2330 return false;
2331 if (T->isPODType())
2332 return true;
2333 if (const RecordType *RT = T->getAs<RecordType>()) {
2334 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2335 if (RD->hasTrivialCopyAssignment())
2336 return true;
2337
2338 bool FoundAssign = false;
2339 bool AllNoThrow = true;
2340 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redl058fc822010-09-14 23:40:14 +00002341 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2342 Sema::LookupOrdinaryName);
2343 if (Self.LookupQualifiedName(Res, RD)) {
2344 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2345 Op != OpEnd; ++Op) {
2346 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2347 if (Operator->isCopyAssignmentOperator()) {
2348 FoundAssign = true;
2349 const FunctionProtoType *CPT
2350 = Operator->getType()->getAs<FunctionProtoType>();
2351 if (!CPT->hasEmptyExceptionSpec()) {
2352 AllNoThrow = false;
2353 break;
2354 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002355 }
2356 }
2357 }
2358
2359 return FoundAssign && AllNoThrow;
2360 }
2361 return false;
2362 case UTT_HasNothrowCopy:
2363 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2364 // If __has_trivial_copy (type) is true then the trait is true, else
2365 // if type is a cv class or union type with copy constructors that are
2366 // known not to throw an exception then the trait is true, else it is
2367 // false.
2368 if (T->isPODType() || T->isReferenceType())
2369 return true;
2370 if (const RecordType *RT = T->getAs<RecordType>()) {
2371 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2372 if (RD->hasTrivialCopyConstructor())
2373 return true;
2374
2375 bool FoundConstructor = false;
2376 bool AllNoThrow = true;
2377 unsigned FoundTQs;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002378 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl951006f2010-09-13 21:10:20 +00002379 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002380 Con != ConEnd; ++Con) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00002381 // A template constructor is never a copy constructor.
2382 // FIXME: However, it may actually be selected at the actual overload
2383 // resolution point.
2384 if (isa<FunctionTemplateDecl>(*Con))
2385 continue;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002386 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2387 if (Constructor->isCopyConstructor(FoundTQs)) {
2388 FoundConstructor = true;
2389 const FunctionProtoType *CPT
2390 = Constructor->getType()->getAs<FunctionProtoType>();
Sebastian Redlc15c3262010-09-13 22:02:47 +00002391 // TODO: check whether evaluating default arguments can throw.
2392 // For now, we'll be conservative and assume that they can throw.
2393 if (!CPT->hasEmptyExceptionSpec() || CPT->getNumArgs() > 1) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002394 AllNoThrow = false;
2395 break;
2396 }
2397 }
2398 }
2399
2400 return FoundConstructor && AllNoThrow;
2401 }
2402 return false;
2403 case UTT_HasNothrowConstructor:
2404 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2405 // If __has_trivial_constructor (type) is true then the trait is
2406 // true, else if type is a cv class or union type (or array
2407 // thereof) with a default constructor that is known not to
2408 // throw an exception then the trait is true, else it is false.
2409 if (T->isPODType())
2410 return true;
2411 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
2412 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2413 if (RD->hasTrivialConstructor())
2414 return true;
2415
Sebastian Redlc15c3262010-09-13 22:02:47 +00002416 DeclContext::lookup_const_iterator Con, ConEnd;
2417 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2418 Con != ConEnd; ++Con) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00002419 // FIXME: In C++0x, a constructor template can be a default constructor.
2420 if (isa<FunctionTemplateDecl>(*Con))
2421 continue;
Sebastian Redlc15c3262010-09-13 22:02:47 +00002422 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2423 if (Constructor->isDefaultConstructor()) {
2424 const FunctionProtoType *CPT
2425 = Constructor->getType()->getAs<FunctionProtoType>();
2426 // TODO: check whether evaluating default arguments can throw.
2427 // For now, we'll be conservative and assume that they can throw.
2428 return CPT->hasEmptyExceptionSpec() && CPT->getNumArgs() == 0;
2429 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002430 }
2431 }
2432 return false;
2433 case UTT_HasVirtualDestructor:
2434 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2435 // If type is a class type with a virtual destructor ([class.dtor])
2436 // then the trait is true, else it is false.
2437 if (const RecordType *Record = T->getAs<RecordType>()) {
2438 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redl058fc822010-09-14 23:40:14 +00002439 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002440 return Destructor->isVirtual();
2441 }
2442 return false;
2443 }
2444}
2445
2446ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor54e5b132010-09-09 16:14:44 +00002447 SourceLocation KWLoc,
2448 TypeSourceInfo *TSInfo,
2449 SourceLocation RParen) {
2450 QualType T = TSInfo->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002451
Anders Carlsson1f9648d2009-07-07 19:06:02 +00002452 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
2453 // all traits except __is_class, __is_enum and __is_union require a the type
Sebastian Redla190d362010-09-08 00:48:43 +00002454 // to be complete, an array of unknown bound, or void.
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002455 if (UTT != UTT_IsClass && UTT != UTT_IsEnum && UTT != UTT_IsUnion) {
Sebastian Redla190d362010-09-08 00:48:43 +00002456 QualType E = T;
2457 if (T->isIncompleteArrayType())
2458 E = Context.getAsArrayType(T)->getElementType();
2459 if (!T->isVoidType() &&
2460 RequireCompleteType(KWLoc, E,
Anders Carlsson029fc692009-08-26 22:59:12 +00002461 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson1f9648d2009-07-07 19:06:02 +00002462 return ExprError();
2463 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002464
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002465 bool Value = false;
2466 if (!T->isDependentType())
Sebastian Redl058fc822010-09-14 23:40:14 +00002467 Value = EvaluateUnaryTypeTrait(*this, UTT, T, KWLoc);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002468
2469 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson1f9648d2009-07-07 19:06:02 +00002470 RParen, Context.BoolTy));
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002471}
Sebastian Redl5822f082009-02-07 20:10:22 +00002472
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002473ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
2474 SourceLocation KWLoc,
2475 ParsedType LhsTy,
2476 ParsedType RhsTy,
2477 SourceLocation RParen) {
2478 TypeSourceInfo *LhsTSInfo;
2479 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
2480 if (!LhsTSInfo)
2481 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
2482
2483 TypeSourceInfo *RhsTSInfo;
2484 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
2485 if (!RhsTSInfo)
2486 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
2487
2488 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
2489}
2490
2491static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
2492 QualType LhsT, QualType RhsT,
2493 SourceLocation KeyLoc) {
2494 assert((!LhsT->isDependentType() || RhsT->isDependentType()) &&
2495 "Cannot evaluate traits for dependent types.");
2496
2497 switch(BTT) {
John McCall388ef532011-01-28 22:02:36 +00002498 case BTT_IsBaseOf: {
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002499 // C++0x [meta.rel]p2
John McCall388ef532011-01-28 22:02:36 +00002500 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002501 // Base and Derived are not unions and name the same class type without
2502 // regard to cv-qualifiers.
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002503
John McCall388ef532011-01-28 22:02:36 +00002504 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
2505 if (!lhsRecord) return false;
2506
2507 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
2508 if (!rhsRecord) return false;
2509
2510 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
2511 == (lhsRecord == rhsRecord));
2512
2513 if (lhsRecord == rhsRecord)
2514 return !lhsRecord->getDecl()->isUnion();
2515
2516 // C++0x [meta.rel]p2:
2517 // If Base and Derived are class types and are different types
2518 // (ignoring possible cv-qualifiers) then Derived shall be a
2519 // complete type.
2520 if (Self.RequireCompleteType(KeyLoc, RhsT,
2521 diag::err_incomplete_type_used_in_type_trait_expr))
2522 return false;
2523
2524 return cast<CXXRecordDecl>(rhsRecord->getDecl())
2525 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
2526 }
2527
Francois Pichet34b21132010-12-08 22:35:30 +00002528 case BTT_TypeCompatible:
2529 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
2530 RhsT.getUnqualifiedType());
Douglas Gregor8006e762011-01-27 20:28:01 +00002531
2532 case BTT_IsConvertibleTo: {
2533 // C++0x [meta.rel]p4:
2534 // Given the following function prototype:
2535 //
2536 // template <class T>
2537 // typename add_rvalue_reference<T>::type create();
2538 //
2539 // the predicate condition for a template specialization
2540 // is_convertible<From, To> shall be satisfied if and only if
2541 // the return expression in the following code would be
2542 // well-formed, including any implicit conversions to the return
2543 // type of the function:
2544 //
2545 // To test() {
2546 // return create<From>();
2547 // }
2548 //
2549 // Access checking is performed as if in a context unrelated to To and
2550 // From. Only the validity of the immediate context of the expression
2551 // of the return-statement (including conversions to the return type)
2552 // is considered.
2553 //
2554 // We model the initialization as a copy-initialization of a temporary
2555 // of the appropriate type, which for this expression is identical to the
2556 // return statement (since NRVO doesn't apply).
2557 if (LhsT->isObjectType() || LhsT->isFunctionType())
2558 LhsT = Self.Context.getRValueReferenceType(LhsT);
2559
2560 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorc03a1082011-01-28 02:26:04 +00002561 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor8006e762011-01-27 20:28:01 +00002562 Expr::getValueKindForType(LhsT));
2563 Expr *FromPtr = &From;
2564 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
2565 SourceLocation()));
2566
Douglas Gregoredb76852011-01-27 22:31:44 +00002567 // Perform the initialization within a SFINAE trap at translation unit
2568 // scope.
2569 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
2570 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Douglas Gregor8006e762011-01-27 20:28:01 +00002571 InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
2572 if (Init.getKind() == InitializationSequence::FailedSequence)
2573 return false;
Douglas Gregoredb76852011-01-27 22:31:44 +00002574
Douglas Gregor8006e762011-01-27 20:28:01 +00002575 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
2576 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
2577 }
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002578 }
2579 llvm_unreachable("Unknown type trait or not implemented");
2580}
2581
2582ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
2583 SourceLocation KWLoc,
2584 TypeSourceInfo *LhsTSInfo,
2585 TypeSourceInfo *RhsTSInfo,
2586 SourceLocation RParen) {
2587 QualType LhsT = LhsTSInfo->getType();
2588 QualType RhsT = RhsTSInfo->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002589
John McCall388ef532011-01-28 22:02:36 +00002590 if (BTT == BTT_TypeCompatible) {
Francois Pichet34b21132010-12-08 22:35:30 +00002591 if (getLangOptions().CPlusPlus) {
2592 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
2593 << SourceRange(KWLoc, RParen);
2594 return ExprError();
2595 }
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002596 }
2597
2598 bool Value = false;
2599 if (!LhsT->isDependentType() && !RhsT->isDependentType())
2600 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
2601
Francois Pichet34b21132010-12-08 22:35:30 +00002602 // Select trait result type.
2603 QualType ResultType;
2604 switch (BTT) {
Francois Pichet34b21132010-12-08 22:35:30 +00002605 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
2606 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
Douglas Gregor8006e762011-01-27 20:28:01 +00002607 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
Francois Pichet34b21132010-12-08 22:35:30 +00002608 }
2609
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002610 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
2611 RhsTSInfo, Value, RParen,
Francois Pichet34b21132010-12-08 22:35:30 +00002612 ResultType));
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002613}
2614
John McCall7decc9e2010-11-18 06:31:45 +00002615QualType Sema::CheckPointerToMemberOperands(Expr *&lex, Expr *&rex,
2616 ExprValueKind &VK,
2617 SourceLocation Loc,
2618 bool isIndirect) {
Sebastian Redl5822f082009-02-07 20:10:22 +00002619 const char *OpSpelling = isIndirect ? "->*" : ".*";
2620 // C++ 5.5p2
2621 // The binary operator .* [p3: ->*] binds its second operand, which shall
2622 // be of type "pointer to member of T" (where T is a completely-defined
2623 // class type) [...]
2624 QualType RType = rex->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002625 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00002626 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00002627 Diag(Loc, diag::err_bad_memptr_rhs)
2628 << OpSpelling << RType << rex->getSourceRange();
2629 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00002630 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00002631
Sebastian Redl5822f082009-02-07 20:10:22 +00002632 QualType Class(MemPtr->getClass(), 0);
2633
Douglas Gregord07ba342010-10-13 20:41:14 +00002634 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
2635 // member pointer points must be completely-defined. However, there is no
2636 // reason for this semantic distinction, and the rule is not enforced by
2637 // other compilers. Therefore, we do not check this property, as it is
2638 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00002639
Sebastian Redl5822f082009-02-07 20:10:22 +00002640 // C++ 5.5p2
2641 // [...] to its first operand, which shall be of class T or of a class of
2642 // which T is an unambiguous and accessible base class. [p3: a pointer to
2643 // such a class]
2644 QualType LType = lex->getType();
2645 if (isIndirect) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002646 if (const PointerType *Ptr = LType->getAs<PointerType>())
John McCall7decc9e2010-11-18 06:31:45 +00002647 LType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00002648 else {
2649 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanian59f64202009-10-26 20:45:27 +00002650 << OpSpelling << 1 << LType
Douglas Gregora771f462010-03-31 17:46:05 +00002651 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00002652 return QualType();
2653 }
2654 }
2655
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002656 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00002657 // If we want to check the hierarchy, we need a complete type.
2658 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
2659 << OpSpelling << (int)isIndirect)) {
2660 return QualType();
2661 }
Anders Carlssona70cff62010-04-24 19:06:50 +00002662 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002663 /*DetectVirtual=*/false);
Mike Stump87c57ac2009-05-16 07:39:55 +00002664 // FIXME: Would it be useful to print full ambiguity paths, or is that
2665 // overkill?
Sebastian Redl5822f082009-02-07 20:10:22 +00002666 if (!IsDerivedFrom(LType, Class, Paths) ||
2667 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
2668 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman1fcf66b2010-01-16 00:00:48 +00002669 << (int)isIndirect << lex->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00002670 return QualType();
2671 }
Eli Friedman1fcf66b2010-01-16 00:00:48 +00002672 // Cast LHS to type of use.
2673 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
John McCall2536c6d2010-08-25 10:28:54 +00002674 ExprValueKind VK =
2675 isIndirect ? VK_RValue : CastCategory(lex);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002676
John McCallcf142162010-08-07 06:22:56 +00002677 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00002678 BuildBasePathArray(Paths, BasePath);
John McCall2536c6d2010-08-25 10:28:54 +00002679 ImpCastExprToType(lex, UseType, CK_DerivedToBase, VK, &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00002680 }
2681
Douglas Gregor747eb782010-07-08 06:14:04 +00002682 if (isa<CXXScalarValueInitExpr>(rex->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00002683 // Diagnose use of pointer-to-member type which when used as
2684 // the functional cast in a pointer-to-member expression.
2685 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
2686 return QualType();
2687 }
John McCall7decc9e2010-11-18 06:31:45 +00002688
Sebastian Redl5822f082009-02-07 20:10:22 +00002689 // C++ 5.5p2
2690 // The result is an object or a function of the type specified by the
2691 // second operand.
2692 // The cv qualifiers are the union of those in the pointer and the left side,
2693 // in accordance with 5.5p5 and 5.2.5.
2694 // FIXME: This returns a dereferenced member function pointer as a normal
2695 // function type. However, the only operation valid on such functions is
Mike Stump87c57ac2009-05-16 07:39:55 +00002696 // calling them. There's also a GCC extension to get a function pointer to the
2697 // thing, which is another complication, because this type - unlike the type
2698 // that is the result of this expression - takes the class as the first
Sebastian Redl5822f082009-02-07 20:10:22 +00002699 // argument.
2700 // We probably need a "MemberFunctionClosureType" or something like that.
2701 QualType Result = MemPtr->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00002702 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00002703
Douglas Gregor1d042092011-01-26 16:40:18 +00002704 // C++0x [expr.mptr.oper]p6:
2705 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002706 // ill-formed if the second operand is a pointer to member function with
2707 // ref-qualifier &. In a ->* expression or in a .* expression whose object
2708 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor1d042092011-01-26 16:40:18 +00002709 // is a pointer to member function with ref-qualifier &&.
2710 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
2711 switch (Proto->getRefQualifier()) {
2712 case RQ_None:
2713 // Do nothing
2714 break;
2715
2716 case RQ_LValue:
2717 if (!isIndirect && !lex->Classify(Context).isLValue())
2718 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
2719 << RType << 1 << lex->getSourceRange();
2720 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002721
Douglas Gregor1d042092011-01-26 16:40:18 +00002722 case RQ_RValue:
2723 if (isIndirect || !lex->Classify(Context).isRValue())
2724 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
2725 << RType << 0 << lex->getSourceRange();
2726 break;
2727 }
2728 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002729
John McCall7decc9e2010-11-18 06:31:45 +00002730 // C++ [expr.mptr.oper]p6:
2731 // The result of a .* expression whose second operand is a pointer
2732 // to a data member is of the same value category as its
2733 // first operand. The result of a .* expression whose second
2734 // operand is a pointer to a member function is a prvalue. The
2735 // result of an ->* expression is an lvalue if its second operand
2736 // is a pointer to data member and a prvalue otherwise.
2737 if (Result->isFunctionType())
2738 VK = VK_RValue;
2739 else if (isIndirect)
2740 VK = VK_LValue;
2741 else
2742 VK = lex->getValueKind();
2743
Sebastian Redl5822f082009-02-07 20:10:22 +00002744 return Result;
2745}
Sebastian Redl1a99f442009-04-16 17:51:27 +00002746
Sebastian Redl1a99f442009-04-16 17:51:27 +00002747/// \brief Try to convert a type to another according to C++0x 5.16p3.
2748///
2749/// This is part of the parameter validation for the ? operator. If either
2750/// value operand is a class type, the two operands are attempted to be
2751/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002752/// It returns true if the program is ill-formed and has already been diagnosed
2753/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00002754static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
2755 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00002756 bool &HaveConversion,
2757 QualType &ToType) {
2758 HaveConversion = false;
2759 ToType = To->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002760
2761 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00002762 SourceLocation());
Sebastian Redl1a99f442009-04-16 17:51:27 +00002763 // C++0x 5.16p3
2764 // The process for determining whether an operand expression E1 of type T1
2765 // can be converted to match an operand expression E2 of type T2 is defined
2766 // as follows:
2767 // -- If E2 is an lvalue:
John McCall086a4642010-11-24 05:12:34 +00002768 bool ToIsLvalue = To->isLValue();
Douglas Gregorf9edf802010-03-26 20:59:55 +00002769 if (ToIsLvalue) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002770 // E1 can be converted to match E2 if E1 can be implicitly converted to
2771 // type "lvalue reference to T2", subject to the constraint that in the
2772 // conversion the reference must bind directly to E1.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002773 QualType T = Self.Context.getLValueReferenceType(ToType);
2774 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002775
Douglas Gregor838fcc32010-03-26 20:14:36 +00002776 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2777 if (InitSeq.isDirectReferenceBinding()) {
2778 ToType = T;
2779 HaveConversion = true;
2780 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00002781 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002782
Douglas Gregor838fcc32010-03-26 20:14:36 +00002783 if (InitSeq.isAmbiguous())
2784 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002785 }
John McCall65eb8792010-02-25 01:37:24 +00002786
Sebastian Redl1a99f442009-04-16 17:51:27 +00002787 // -- If E2 is an rvalue, or if the conversion above cannot be done:
2788 // -- if E1 and E2 have class type, and the underlying class types are
2789 // the same or one is a base class of the other:
2790 QualType FTy = From->getType();
2791 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002792 const RecordType *FRec = FTy->getAs<RecordType>();
2793 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002794 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Douglas Gregor838fcc32010-03-26 20:14:36 +00002795 Self.IsDerivedFrom(FTy, TTy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002796 if (FRec && TRec &&
Douglas Gregor838fcc32010-03-26 20:14:36 +00002797 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002798 // E1 can be converted to match E2 if the class of T2 is the
2799 // same type as, or a base class of, the class of T1, and
2800 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00002801 if (FRec == TRec || FDerivedFromT) {
2802 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00002803 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2804 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2805 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2806 HaveConversion = true;
2807 return false;
2808 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002809
Douglas Gregor838fcc32010-03-26 20:14:36 +00002810 if (InitSeq.isAmbiguous())
2811 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002812 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00002813 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002814
Douglas Gregor838fcc32010-03-26 20:14:36 +00002815 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00002816 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002817
Douglas Gregor838fcc32010-03-26 20:14:36 +00002818 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2819 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002820 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregorf9edf802010-03-26 20:59:55 +00002821 // an rvalue).
2822 //
2823 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2824 // to the array-to-pointer or function-to-pointer conversions.
2825 if (!TTy->getAs<TagType>())
2826 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002827
Douglas Gregor838fcc32010-03-26 20:14:36 +00002828 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2829 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002830 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002831 ToType = TTy;
2832 if (InitSeq.isAmbiguous())
2833 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2834
Sebastian Redl1a99f442009-04-16 17:51:27 +00002835 return false;
2836}
2837
2838/// \brief Try to find a common type for two according to C++0x 5.16p5.
2839///
2840/// This is part of the parameter validation for the ? operator. If either
2841/// value operand is a class type, overload resolution is used to find a
2842/// conversion to a common type.
2843static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2844 SourceLocation Loc) {
2845 Expr *Args[2] = { LHS, RHS };
John McCallbc077cf2010-02-08 23:07:23 +00002846 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002847 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002848
2849 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00002850 switch (CandidateSet.BestViableFunction(Self, Loc, Best)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002851 case OR_Success:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002852 // We found a match. Perform the conversions on the arguments and move on.
2853 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002854 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00002855 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002856 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002857 break;
2858 return false;
2859
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002860 case OR_No_Viable_Function:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002861 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2862 << LHS->getType() << RHS->getType()
2863 << LHS->getSourceRange() << RHS->getSourceRange();
2864 return true;
2865
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002866 case OR_Ambiguous:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002867 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2868 << LHS->getType() << RHS->getType()
2869 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00002870 // FIXME: Print the possible common types by printing the return types of
2871 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00002872 break;
2873
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002874 case OR_Deleted:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002875 assert(false && "Conditional operator has only built-in overloads");
2876 break;
2877 }
2878 return true;
2879}
2880
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002881/// \brief Perform an "extended" implicit conversion as returned by
2882/// TryClassUnification.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002883static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2884 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2885 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2886 SourceLocation());
2887 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
John McCallfaf5fb42010-08-26 23:41:50 +00002888 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&E, 1));
Douglas Gregor838fcc32010-03-26 20:14:36 +00002889 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002890 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002891
Douglas Gregor838fcc32010-03-26 20:14:36 +00002892 E = Result.takeAs<Expr>();
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002893 return false;
2894}
2895
Sebastian Redl1a99f442009-04-16 17:51:27 +00002896/// \brief Check the operands of ?: under C++ semantics.
2897///
2898/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2899/// extension. In this case, LHS == Cond. (But they're not aliases.)
2900QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
John McCall7decc9e2010-11-18 06:31:45 +00002901 Expr *&SAVE, ExprValueKind &VK,
John McCall4bc41ae2010-11-18 19:01:18 +00002902 ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00002903 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00002904 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2905 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00002906
2907 // C++0x 5.16p1
2908 // The first expression is contextually converted to bool.
2909 if (!Cond->isTypeDependent()) {
Fariborz Jahanian2b1d88a2010-09-18 19:38:38 +00002910 if (SAVE && Cond->getType()->isArrayType()) {
2911 QualType CondTy = Cond->getType();
2912 CondTy = Context.getArrayDecayedType(CondTy);
2913 ImpCastExprToType(Cond, CondTy, CK_ArrayToPointerDecay);
2914 SAVE = LHS = Cond;
2915 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00002916 if (CheckCXXBooleanCondition(Cond))
2917 return QualType();
2918 }
2919
John McCall7decc9e2010-11-18 06:31:45 +00002920 // Assume r-value.
2921 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00002922 OK = OK_Ordinary;
John McCall7decc9e2010-11-18 06:31:45 +00002923
Sebastian Redl1a99f442009-04-16 17:51:27 +00002924 // Either of the arguments dependent?
2925 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2926 return Context.DependentTy;
2927
2928 // C++0x 5.16p2
2929 // If either the second or the third operand has type (cv) void, ...
2930 QualType LTy = LHS->getType();
2931 QualType RTy = RHS->getType();
2932 bool LVoid = LTy->isVoidType();
2933 bool RVoid = RTy->isVoidType();
2934 if (LVoid || RVoid) {
2935 // ... then the [l2r] conversions are performed on the second and third
2936 // operands ...
Douglas Gregorb92a1562010-02-03 00:27:59 +00002937 DefaultFunctionArrayLvalueConversion(LHS);
2938 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002939 LTy = LHS->getType();
2940 RTy = RHS->getType();
2941
2942 // ... and one of the following shall hold:
2943 // -- The second or the third operand (but not both) is a throw-
2944 // expression; the result is of the type of the other and is an rvalue.
2945 bool LThrow = isa<CXXThrowExpr>(LHS);
2946 bool RThrow = isa<CXXThrowExpr>(RHS);
2947 if (LThrow && !RThrow)
2948 return RTy;
2949 if (RThrow && !LThrow)
2950 return LTy;
2951
2952 // -- Both the second and third operands have type void; the result is of
2953 // type void and is an rvalue.
2954 if (LVoid && RVoid)
2955 return Context.VoidTy;
2956
2957 // Neither holds, error.
2958 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2959 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2960 << LHS->getSourceRange() << RHS->getSourceRange();
2961 return QualType();
2962 }
2963
2964 // Neither is void.
2965
2966 // C++0x 5.16p3
2967 // Otherwise, if the second and third operand have different types, and
2968 // either has (cv) class type, and attempt is made to convert each of those
2969 // operands to the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002970 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00002971 (LTy->isRecordType() || RTy->isRecordType())) {
2972 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2973 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002974 QualType L2RType, R2LType;
2975 bool HaveL2R, HaveR2L;
2976 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002977 return QualType();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002978 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002979 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002980
Sebastian Redl1a99f442009-04-16 17:51:27 +00002981 // If both can be converted, [...] the program is ill-formed.
2982 if (HaveL2R && HaveR2L) {
2983 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2984 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2985 return QualType();
2986 }
2987
2988 // If exactly one conversion is possible, that conversion is applied to
2989 // the chosen operand and the converted operands are used in place of the
2990 // original operands for the remainder of this section.
2991 if (HaveL2R) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00002992 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002993 return QualType();
2994 LTy = LHS->getType();
2995 } else if (HaveR2L) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00002996 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002997 return QualType();
2998 RTy = RHS->getType();
2999 }
3000 }
3001
3002 // C++0x 5.16p4
John McCall7decc9e2010-11-18 06:31:45 +00003003 // If the second and third operands are glvalues of the same value
3004 // category and have the same type, the result is of that type and
3005 // value category and it is a bit-field if the second or the third
3006 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00003007 // We only extend this to bitfields, not to the crazy other kinds of
3008 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00003009 bool Same = Context.hasSameType(LTy, RTy);
John McCall7decc9e2010-11-18 06:31:45 +00003010 if (Same &&
3011 LHS->getValueKind() != VK_RValue &&
3012 LHS->getValueKind() == RHS->getValueKind() &&
John McCall4bc41ae2010-11-18 19:01:18 +00003013 (LHS->getObjectKind() == OK_Ordinary ||
3014 LHS->getObjectKind() == OK_BitField) &&
3015 (RHS->getObjectKind() == OK_Ordinary ||
3016 RHS->getObjectKind() == OK_BitField)) {
John McCall7decc9e2010-11-18 06:31:45 +00003017 VK = LHS->getValueKind();
John McCall4bc41ae2010-11-18 19:01:18 +00003018 if (LHS->getObjectKind() == OK_BitField ||
3019 RHS->getObjectKind() == OK_BitField)
3020 OK = OK_BitField;
John McCall7decc9e2010-11-18 06:31:45 +00003021 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00003022 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003023
3024 // C++0x 5.16p5
3025 // Otherwise, the result is an rvalue. If the second and third operands
3026 // do not have the same type, and either has (cv) class type, ...
3027 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
3028 // ... overload resolution is used to determine the conversions (if any)
3029 // to be applied to the operands. If the overload resolution fails, the
3030 // program is ill-formed.
3031 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
3032 return QualType();
3033 }
3034
3035 // C++0x 5.16p6
3036 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
3037 // conversions are performed on the second and third operands.
Douglas Gregorb92a1562010-02-03 00:27:59 +00003038 DefaultFunctionArrayLvalueConversion(LHS);
3039 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003040 LTy = LHS->getType();
3041 RTy = RHS->getType();
3042
3043 // After those conversions, one of the following shall hold:
3044 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00003045 // is of that type. If the operands have class type, the result
3046 // is a prvalue temporary of the result type, which is
3047 // copy-initialized from either the second operand or the third
3048 // operand depending on the value of the first operand.
3049 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
3050 if (LTy->isRecordType()) {
3051 // The operands have class type. Make a temporary copy.
3052 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003053 ExprResult LHSCopy = PerformCopyInitialization(Entity,
3054 SourceLocation(),
John McCall34376a62010-12-04 03:47:34 +00003055 Owned(LHS));
Douglas Gregorfa6010b2010-05-19 23:40:50 +00003056 if (LHSCopy.isInvalid())
3057 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003058
3059 ExprResult RHSCopy = PerformCopyInitialization(Entity,
3060 SourceLocation(),
John McCall34376a62010-12-04 03:47:34 +00003061 Owned(RHS));
Douglas Gregorfa6010b2010-05-19 23:40:50 +00003062 if (RHSCopy.isInvalid())
3063 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003064
Douglas Gregorfa6010b2010-05-19 23:40:50 +00003065 LHS = LHSCopy.takeAs<Expr>();
3066 RHS = RHSCopy.takeAs<Expr>();
3067 }
3068
Sebastian Redl1a99f442009-04-16 17:51:27 +00003069 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00003070 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003071
Douglas Gregor46188682010-05-18 22:42:18 +00003072 // Extension: conditional operator involving vector types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003073 if (LTy->isVectorType() || RTy->isVectorType())
Douglas Gregor46188682010-05-18 22:42:18 +00003074 return CheckVectorOperands(QuestionLoc, LHS, RHS);
3075
Sebastian Redl1a99f442009-04-16 17:51:27 +00003076 // -- The second and third operands have arithmetic or enumeration type;
3077 // the usual arithmetic conversions are performed to bring them to a
3078 // common type, and the result is of that type.
3079 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
3080 UsualArithmeticConversions(LHS, RHS);
3081 return LHS->getType();
3082 }
3083
3084 // -- The second and third operands have pointer type, or one has pointer
3085 // type and the other is a null pointer constant; pointer conversions
3086 // and qualification conversions are performed to bring them to their
3087 // composite pointer type. The result is of the composite pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00003088 // -- The second and third operands have pointer to member type, or one has
3089 // pointer to member type and the other is a null pointer constant;
3090 // pointer to member conversions and qualification conversions are
3091 // performed to bring them to a common type, whose cv-qualification
3092 // shall match the cv-qualification of either the second or the third
3093 // operand. The result is of the common type.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003094 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00003095 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003096 isSFINAEContext()? 0 : &NonStandardCompositeType);
3097 if (!Composite.isNull()) {
3098 if (NonStandardCompositeType)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003099 Diag(QuestionLoc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003100 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
3101 << LTy << RTy << Composite
3102 << LHS->getSourceRange() << RHS->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003103
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003104 return Composite;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003105 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003106
Douglas Gregor697a3912010-04-01 22:47:07 +00003107 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00003108 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
3109 if (!Composite.isNull())
3110 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003111
Sebastian Redl1a99f442009-04-16 17:51:27 +00003112 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3113 << LHS->getType() << RHS->getType()
3114 << LHS->getSourceRange() << RHS->getSourceRange();
3115 return QualType();
3116}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003117
3118/// \brief Find a merged pointer type and convert the two expressions to it.
3119///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003120/// This finds the composite pointer type (or member pointer type) for @p E1
3121/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
3122/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003123/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003124///
Douglas Gregor19175ff2010-04-16 23:20:25 +00003125/// \param Loc The location of the operator requiring these two expressions to
3126/// be converted to the composite pointer type.
3127///
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003128/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
3129/// a non-standard (but still sane) composite type to which both expressions
3130/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
3131/// will be set true.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003132QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor19175ff2010-04-16 23:20:25 +00003133 Expr *&E1, Expr *&E2,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003134 bool *NonStandardCompositeType) {
3135 if (NonStandardCompositeType)
3136 *NonStandardCompositeType = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003137
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003138 assert(getLangOptions().CPlusPlus && "This function assumes C++");
3139 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003140
Fariborz Jahanian33e148f2009-12-08 20:04:24 +00003141 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
3142 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003143 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003144
3145 // C++0x 5.9p2
3146 // Pointer conversions and qualification conversions are performed on
3147 // pointer operands to bring them to their composite pointer type. If
3148 // one operand is a null pointer constant, the composite pointer type is
3149 // the type of the other operand.
Douglas Gregor56751b52009-09-25 04:25:58 +00003150 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003151 if (T2->isMemberPointerType())
John McCalle3027922010-08-25 11:45:40 +00003152 ImpCastExprToType(E1, T2, CK_NullToMemberPointer);
Eli Friedman06ed2a52009-10-20 08:27:19 +00003153 else
John McCalle84af4e2010-11-13 01:35:44 +00003154 ImpCastExprToType(E1, T2, CK_NullToPointer);
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003155 return T2;
3156 }
Douglas Gregor56751b52009-09-25 04:25:58 +00003157 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003158 if (T1->isMemberPointerType())
John McCalle3027922010-08-25 11:45:40 +00003159 ImpCastExprToType(E2, T1, CK_NullToMemberPointer);
Eli Friedman06ed2a52009-10-20 08:27:19 +00003160 else
John McCalle84af4e2010-11-13 01:35:44 +00003161 ImpCastExprToType(E2, T1, CK_NullToPointer);
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003162 return T1;
3163 }
Mike Stump11289f42009-09-09 15:08:12 +00003164
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003165 // Now both have to be pointers or member pointers.
Sebastian Redl658262f2009-11-16 21:03:45 +00003166 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
3167 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003168 return QualType();
3169
3170 // Otherwise, of one of the operands has type "pointer to cv1 void," then
3171 // the other has type "pointer to cv2 T" and the composite pointer type is
3172 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
3173 // Otherwise, the composite pointer type is a pointer type similar to the
3174 // type of one of the operands, with a cv-qualification signature that is
3175 // the union of the cv-qualification signatures of the operand types.
3176 // In practice, the first part here is redundant; it's subsumed by the second.
3177 // What we do here is, we build the two possible composite types, and try the
3178 // conversions in both directions. If only one works, or if the two composite
3179 // types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00003180 // FIXME: extended qualifiers?
Sebastian Redl658262f2009-11-16 21:03:45 +00003181 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
3182 QualifierVector QualifierUnion;
3183 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
3184 ContainingClassVector;
3185 ContainingClassVector MemberOfClass;
3186 QualType Composite1 = Context.getCanonicalType(T1),
3187 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003188 unsigned NeedConstBefore = 0;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003189 do {
3190 const PointerType *Ptr1, *Ptr2;
3191 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3192 (Ptr2 = Composite2->getAs<PointerType>())) {
3193 Composite1 = Ptr1->getPointeeType();
3194 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003195
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003196 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003197 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003198 if (NonStandardCompositeType &&
3199 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3200 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003201
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003202 QualifierUnion.push_back(
3203 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3204 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3205 continue;
3206 }
Mike Stump11289f42009-09-09 15:08:12 +00003207
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003208 const MemberPointerType *MemPtr1, *MemPtr2;
3209 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3210 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3211 Composite1 = MemPtr1->getPointeeType();
3212 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003213
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003214 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003215 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003216 if (NonStandardCompositeType &&
3217 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3218 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003219
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003220 QualifierUnion.push_back(
3221 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3222 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
3223 MemPtr2->getClass()));
3224 continue;
3225 }
Mike Stump11289f42009-09-09 15:08:12 +00003226
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003227 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00003228
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003229 // Cannot unwrap any more types.
3230 break;
3231 } while (true);
Mike Stump11289f42009-09-09 15:08:12 +00003232
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003233 if (NeedConstBefore && NonStandardCompositeType) {
3234 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003235 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003236 // requirements of C++ [conv.qual]p4 bullet 3.
3237 for (unsigned I = 0; I != NeedConstBefore; ++I) {
3238 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
3239 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
3240 *NonStandardCompositeType = true;
3241 }
3242 }
3243 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003244
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003245 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redl658262f2009-11-16 21:03:45 +00003246 ContainingClassVector::reverse_iterator MOC
3247 = MemberOfClass.rbegin();
3248 for (QualifierVector::reverse_iterator
3249 I = QualifierUnion.rbegin(),
3250 E = QualifierUnion.rend();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003251 I != E; (void)++I, ++MOC) {
John McCall8ccfcb52009-09-24 19:53:00 +00003252 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003253 if (MOC->first && MOC->second) {
3254 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00003255 Composite1 = Context.getMemberPointerType(
3256 Context.getQualifiedType(Composite1, Quals),
3257 MOC->first);
3258 Composite2 = Context.getMemberPointerType(
3259 Context.getQualifiedType(Composite2, Quals),
3260 MOC->second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003261 } else {
3262 // Rebuild pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00003263 Composite1
3264 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
3265 Composite2
3266 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003267 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003268 }
3269
Douglas Gregor19175ff2010-04-16 23:20:25 +00003270 // Try to convert to the first composite pointer type.
3271 InitializedEntity Entity1
3272 = InitializedEntity::InitializeTemporary(Composite1);
3273 InitializationKind Kind
3274 = InitializationKind::CreateCopy(Loc, SourceLocation());
3275 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
3276 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump11289f42009-09-09 15:08:12 +00003277
Douglas Gregor19175ff2010-04-16 23:20:25 +00003278 if (E1ToC1 && E2ToC1) {
3279 // Conversion to Composite1 is viable.
3280 if (!Context.hasSameType(Composite1, Composite2)) {
3281 // Composite2 is a different type from Composite1. Check whether
3282 // Composite2 is also viable.
3283 InitializedEntity Entity2
3284 = InitializedEntity::InitializeTemporary(Composite2);
3285 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3286 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3287 if (E1ToC2 && E2ToC2) {
3288 // Both Composite1 and Composite2 are viable and are different;
3289 // this is an ambiguity.
3290 return QualType();
3291 }
3292 }
3293
3294 // Convert E1 to Composite1
John McCalldadc5752010-08-24 06:29:42 +00003295 ExprResult E1Result
John McCall37ad5512010-08-23 06:44:23 +00003296 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00003297 if (E1Result.isInvalid())
3298 return QualType();
3299 E1 = E1Result.takeAs<Expr>();
3300
3301 // Convert E2 to Composite1
John McCalldadc5752010-08-24 06:29:42 +00003302 ExprResult E2Result
John McCall37ad5512010-08-23 06:44:23 +00003303 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00003304 if (E2Result.isInvalid())
3305 return QualType();
3306 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003307
Douglas Gregor19175ff2010-04-16 23:20:25 +00003308 return Composite1;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003309 }
3310
Douglas Gregor19175ff2010-04-16 23:20:25 +00003311 // Check whether Composite2 is viable.
3312 InitializedEntity Entity2
3313 = InitializedEntity::InitializeTemporary(Composite2);
3314 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3315 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3316 if (!E1ToC2 || !E2ToC2)
3317 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003318
Douglas Gregor19175ff2010-04-16 23:20:25 +00003319 // Convert E1 to Composite2
John McCalldadc5752010-08-24 06:29:42 +00003320 ExprResult E1Result
John McCall37ad5512010-08-23 06:44:23 +00003321 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00003322 if (E1Result.isInvalid())
3323 return QualType();
3324 E1 = E1Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003325
Douglas Gregor19175ff2010-04-16 23:20:25 +00003326 // Convert E2 to Composite2
John McCalldadc5752010-08-24 06:29:42 +00003327 ExprResult E2Result
John McCall37ad5512010-08-23 06:44:23 +00003328 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00003329 if (E2Result.isInvalid())
3330 return QualType();
3331 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003332
Douglas Gregor19175ff2010-04-16 23:20:25 +00003333 return Composite2;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003334}
Anders Carlsson85a307d2009-05-17 18:41:29 +00003335
John McCalldadc5752010-08-24 06:29:42 +00003336ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00003337 if (!E)
3338 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003339
Anders Carlssonf86a8d12009-08-15 23:41:35 +00003340 if (!Context.getLangOptions().CPlusPlus)
3341 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00003342
Douglas Gregor363b1512009-12-24 18:51:59 +00003343 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
3344
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003345 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlsson2d4cada2009-05-30 20:36:53 +00003346 if (!RT)
3347 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00003348
Anders Carlssonbb4cfdf2010-07-16 21:18:37 +00003349 // If this is the result of a call or an Objective-C message send expression,
3350 // our source might actually be a reference, in which case we shouldn't bind.
Anders Carlssonaedb46f2009-09-14 01:30:44 +00003351 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
Anders Carlssonbb4cfdf2010-07-16 21:18:37 +00003352 if (CE->getCallReturnType()->isReferenceType())
Anders Carlssonaedb46f2009-09-14 01:30:44 +00003353 return Owned(E);
Anders Carlssonbb4cfdf2010-07-16 21:18:37 +00003354 } else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
3355 if (const ObjCMethodDecl *MD = ME->getMethodDecl()) {
3356 if (MD->getResultType()->isReferenceType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003357 return Owned(E);
Anders Carlssonbb4cfdf2010-07-16 21:18:37 +00003358 }
Anders Carlssonaedb46f2009-09-14 01:30:44 +00003359 }
John McCall67da35c2010-02-04 22:26:26 +00003360
3361 // That should be enough to guarantee that this type is complete.
3362 // If it has a trivial destructor, we can avoid the extra copy.
Jeffrey Yasskinbbc4eea2011-01-27 19:17:54 +00003363 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCallbdb989e2010-08-12 02:40:37 +00003364 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall67da35c2010-02-04 22:26:26 +00003365 return Owned(E);
3366
Douglas Gregore71edda2010-07-01 22:47:18 +00003367 CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD));
Anders Carlssonc78576e2009-05-30 21:21:49 +00003368 ExprTemporaries.push_back(Temp);
Douglas Gregore71edda2010-07-01 22:47:18 +00003369 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Fariborz Jahanian67828442009-08-03 19:13:25 +00003370 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00003371 CheckDestructorAccess(E->getExprLoc(), Destructor,
3372 PDiag(diag::err_access_dtor_temp)
3373 << E->getType());
3374 }
Anders Carlsson2d4cada2009-05-30 20:36:53 +00003375 // FIXME: Add the temporary to the temporaries vector.
3376 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
3377}
3378
John McCall5d413782010-12-06 08:20:24 +00003379Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Anders Carlssonb3d05d62009-06-05 15:38:08 +00003380 assert(SubExpr && "sub expression can't be null!");
Mike Stump11289f42009-09-09 15:08:12 +00003381
Douglas Gregor580cd4a2009-12-03 17:10:37 +00003382 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3383 assert(ExprTemporaries.size() >= FirstTemporary);
3384 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlssonb3d05d62009-06-05 15:38:08 +00003385 return SubExpr;
Mike Stump11289f42009-09-09 15:08:12 +00003386
John McCall5d413782010-12-06 08:20:24 +00003387 Expr *E = ExprWithCleanups::Create(Context, SubExpr,
3388 &ExprTemporaries[FirstTemporary],
3389 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor580cd4a2009-12-03 17:10:37 +00003390 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
3391 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00003392
Anders Carlssonb3d05d62009-06-05 15:38:08 +00003393 return E;
3394}
3395
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003396ExprResult
John McCall5d413782010-12-06 08:20:24 +00003397Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00003398 if (SubExpr.isInvalid())
3399 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003400
John McCall5d413782010-12-06 08:20:24 +00003401 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00003402}
3403
John McCall5d413782010-12-06 08:20:24 +00003404Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00003405 assert(SubStmt && "sub statement can't be null!");
3406
3407 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3408 assert(ExprTemporaries.size() >= FirstTemporary);
3409 if (ExprTemporaries.size() == FirstTemporary)
3410 return SubStmt;
3411
3412 // FIXME: In order to attach the temporaries, wrap the statement into
3413 // a StmtExpr; currently this is only used for asm statements.
3414 // This is hacky, either create a new CXXStmtWithTemporaries statement or
3415 // a new AsmStmtWithTemporaries.
3416 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
3417 SourceLocation(),
3418 SourceLocation());
3419 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
3420 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00003421 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00003422}
3423
John McCalldadc5752010-08-24 06:29:42 +00003424ExprResult
John McCallb268a282010-08-23 23:25:46 +00003425Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallba7bf592010-08-24 05:47:05 +00003426 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregore610ada2010-02-24 18:44:31 +00003427 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003428 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003429 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003430 if (Result.isInvalid()) return ExprError();
3431 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00003432
John McCallb268a282010-08-23 23:25:46 +00003433 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00003434 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003435 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00003436 // If we have a pointer to a dependent type and are using the -> operator,
3437 // the object type is the type that the pointer points to. We might still
3438 // have enough information about that type to do something useful.
3439 if (OpKind == tok::arrow)
3440 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3441 BaseType = Ptr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003442
John McCallba7bf592010-08-24 05:47:05 +00003443 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00003444 MayBePseudoDestructor = true;
John McCallb268a282010-08-23 23:25:46 +00003445 return Owned(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003446 }
Mike Stump11289f42009-09-09 15:08:12 +00003447
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003448 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00003449 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003450 // returned, with the original second operand.
3451 if (OpKind == tok::arrow) {
John McCallc1538c02009-09-30 01:01:30 +00003452 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00003453 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00003454 llvm::SmallVector<SourceLocation, 8> Locations;
John McCallbd0465b2009-09-30 01:30:54 +00003455 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003456
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003457 while (BaseType->isRecordType()) {
John McCallb268a282010-08-23 23:25:46 +00003458 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
3459 if (Result.isInvalid())
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003460 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00003461 Base = Result.get();
3462 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonfbd2d492009-10-13 22:55:59 +00003463 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallb268a282010-08-23 23:25:46 +00003464 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00003465 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCallbd0465b2009-09-30 01:30:54 +00003466 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00003467 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00003468 for (unsigned i = 0; i < Locations.size(); i++)
3469 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00003470 return ExprError();
3471 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003472 }
Mike Stump11289f42009-09-09 15:08:12 +00003473
Douglas Gregore4f764f2009-11-20 19:58:21 +00003474 if (BaseType->isPointerType())
3475 BaseType = BaseType->getPointeeType();
3476 }
Mike Stump11289f42009-09-09 15:08:12 +00003477
3478 // We could end up with various non-record types here, such as extended
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003479 // vector types or Objective-C interfaces. Just return early and let
3480 // ActOnMemberReferenceExpr do the work.
Douglas Gregor2b6ca462009-09-03 21:38:09 +00003481 if (!BaseType->isRecordType()) {
3482 // C++ [basic.lookup.classref]p2:
3483 // [...] If the type of the object expression is of pointer to scalar
3484 // type, the unqualified-id is looked up in the context of the complete
3485 // postfix-expression.
Douglas Gregore610ada2010-02-24 18:44:31 +00003486 //
3487 // This also indicates that we should be parsing a
3488 // pseudo-destructor-name.
John McCallba7bf592010-08-24 05:47:05 +00003489 ObjectType = ParsedType();
Douglas Gregore610ada2010-02-24 18:44:31 +00003490 MayBePseudoDestructor = true;
John McCallb268a282010-08-23 23:25:46 +00003491 return Owned(Base);
Douglas Gregor2b6ca462009-09-03 21:38:09 +00003492 }
Mike Stump11289f42009-09-09 15:08:12 +00003493
Douglas Gregor3fad6172009-11-17 05:17:33 +00003494 // The object type must be complete (or dependent).
3495 if (!BaseType->isDependentType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003496 RequireCompleteType(OpLoc, BaseType,
Douglas Gregor3fad6172009-11-17 05:17:33 +00003497 PDiag(diag::err_incomplete_member_access)))
3498 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003499
Douglas Gregor2b6ca462009-09-03 21:38:09 +00003500 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00003501 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00003502 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00003503 // type C (or of pointer to a class type C), the unqualified-id is looked
3504 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00003505 ObjectType = ParsedType::make(BaseType);
Mike Stump11289f42009-09-09 15:08:12 +00003506 return move(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003507}
3508
John McCalldadc5752010-08-24 06:29:42 +00003509ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCallb268a282010-08-23 23:25:46 +00003510 Expr *MemExpr) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003511 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCallb268a282010-08-23 23:25:46 +00003512 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
3513 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregora771f462010-03-31 17:46:05 +00003514 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003515
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003516 return ActOnCallExpr(/*Scope*/ 0,
John McCallb268a282010-08-23 23:25:46 +00003517 MemExpr,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003518 /*LPLoc*/ ExpectedLParenLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00003519 MultiExprArg(),
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003520 /*RPLoc*/ ExpectedLParenLoc);
3521}
Douglas Gregore610ada2010-02-24 18:44:31 +00003522
John McCalldadc5752010-08-24 06:29:42 +00003523ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003524 SourceLocation OpLoc,
3525 tok::TokenKind OpKind,
3526 const CXXScopeSpec &SS,
Douglas Gregor651fe5e2010-02-24 23:40:28 +00003527 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003528 SourceLocation CCLoc,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00003529 SourceLocation TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00003530 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003531 bool HasTrailingLParen) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00003532 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003533
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003534 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003535 // The left-hand side of the dot operator shall be of scalar type. The
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003536 // left-hand side of the arrow operator shall be of pointer to scalar type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003537 // This scalar type is the object type.
John McCallb268a282010-08-23 23:25:46 +00003538 QualType ObjectType = Base->getType();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003539 if (OpKind == tok::arrow) {
3540 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3541 ObjectType = Ptr->getPointeeType();
John McCallb268a282010-08-23 23:25:46 +00003542 } else if (!Base->isTypeDependent()) {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003543 // The user wrote "p->" when she probably meant "p."; fix it.
3544 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3545 << ObjectType << true
Douglas Gregora771f462010-03-31 17:46:05 +00003546 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003547 if (isSFINAEContext())
3548 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003549
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003550 OpKind = tok::period;
3551 }
3552 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003553
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003554 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
3555 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
John McCallb268a282010-08-23 23:25:46 +00003556 << ObjectType << Base->getSourceRange();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003557 return ExprError();
3558 }
3559
3560 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003561 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003562 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00003563 if (DestructedTypeInfo) {
3564 QualType DestructedType = DestructedTypeInfo->getType();
3565 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00003566 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
Douglas Gregor678f90d2010-02-25 01:56:36 +00003567 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
3568 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
3569 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00003570 << ObjectType << DestructedType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00003571 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003572
Douglas Gregor678f90d2010-02-25 01:56:36 +00003573 // Recover by setting the destructed type to the object type.
3574 DestructedType = ObjectType;
3575 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
3576 DestructedTypeStart);
3577 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3578 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003579 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003580
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003581 // C++ [expr.pseudo]p2:
3582 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
3583 // form
3584 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003585 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003586 //
3587 // shall designate the same scalar type.
3588 if (ScopeTypeInfo) {
3589 QualType ScopeType = ScopeTypeInfo->getType();
3590 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00003591 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003592
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00003593 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003594 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00003595 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00003596 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003597
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003598 ScopeType = QualType();
3599 ScopeTypeInfo = 0;
3600 }
3601 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003602
John McCallb268a282010-08-23 23:25:46 +00003603 Expr *Result
3604 = new (Context) CXXPseudoDestructorExpr(Context, Base,
3605 OpKind == tok::arrow, OpLoc,
3606 SS.getScopeRep(), SS.getRange(),
3607 ScopeTypeInfo,
3608 CCLoc,
3609 TildeLoc,
3610 Destructed);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003611
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003612 if (HasTrailingLParen)
John McCallb268a282010-08-23 23:25:46 +00003613 return Owned(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003614
John McCallb268a282010-08-23 23:25:46 +00003615 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003616}
3617
John McCalldadc5752010-08-24 06:29:42 +00003618ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003619 SourceLocation OpLoc,
3620 tok::TokenKind OpKind,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003621 CXXScopeSpec &SS,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003622 UnqualifiedId &FirstTypeName,
3623 SourceLocation CCLoc,
3624 SourceLocation TildeLoc,
3625 UnqualifiedId &SecondTypeName,
3626 bool HasTrailingLParen) {
3627 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3628 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3629 "Invalid first type name in pseudo-destructor");
3630 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3631 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3632 "Invalid second type name in pseudo-destructor");
3633
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003634 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003635 // The left-hand side of the dot operator shall be of scalar type. The
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003636 // left-hand side of the arrow operator shall be of pointer to scalar type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003637 // This scalar type is the object type.
John McCallb268a282010-08-23 23:25:46 +00003638 QualType ObjectType = Base->getType();
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003639 if (OpKind == tok::arrow) {
3640 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3641 ObjectType = Ptr->getPointeeType();
Douglas Gregor678f90d2010-02-25 01:56:36 +00003642 } else if (!ObjectType->isDependentType()) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003643 // The user wrote "p->" when she probably meant "p."; fix it.
3644 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregor678f90d2010-02-25 01:56:36 +00003645 << ObjectType << true
Douglas Gregora771f462010-03-31 17:46:05 +00003646 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003647 if (isSFINAEContext())
3648 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003649
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003650 OpKind = tok::period;
3651 }
3652 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00003653
3654 // Compute the object type that we should use for name lookup purposes. Only
3655 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00003656 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00003657 if (!SS.isSet()) {
John McCallba7bf592010-08-24 05:47:05 +00003658 if (const Type *T = ObjectType->getAs<RecordType>())
3659 ObjectTypePtrForLookup = ParsedType::make(QualType(T, 0));
3660 else if (ObjectType->isDependentType())
3661 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00003662 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003663
3664 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003665 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003666 QualType DestructedType;
3667 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregor678f90d2010-02-25 01:56:36 +00003668 PseudoDestructorTypeStorage Destructed;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003669 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003670 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00003671 SecondTypeName.StartLocation,
3672 S, &SS, true, ObjectTypePtrForLookup);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003673 if (!T &&
Douglas Gregor678f90d2010-02-25 01:56:36 +00003674 ((SS.isSet() && !computeDeclContext(SS, false)) ||
3675 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003676 // The name of the type being destroyed is a dependent name, and we
Douglas Gregor678f90d2010-02-25 01:56:36 +00003677 // couldn't find anything useful in scope. Just store the identifier and
3678 // it's location, and we'll perform (qualified) name lookup again at
3679 // template instantiation time.
3680 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
3681 SecondTypeName.StartLocation);
3682 } else if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003683 Diag(SecondTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003684 diag::err_pseudo_dtor_destructor_non_type)
3685 << SecondTypeName.Identifier << ObjectType;
3686 if (isSFINAEContext())
3687 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003688
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003689 // Recover by assuming we had the right type all along.
3690 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003691 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003692 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003693 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003694 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003695 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003696 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3697 TemplateId->getTemplateArgs(),
3698 TemplateId->NumArgs);
John McCall3e56fd42010-08-23 07:28:44 +00003699 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003700 TemplateId->TemplateNameLoc,
3701 TemplateId->LAngleLoc,
3702 TemplateArgsPtr,
3703 TemplateId->RAngleLoc);
3704 if (T.isInvalid() || !T.get()) {
3705 // Recover by assuming we had the right type all along.
3706 DestructedType = ObjectType;
3707 } else
3708 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003709 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003710
3711 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003712 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00003713 if (!DestructedType.isNull()) {
3714 if (!DestructedTypeInfo)
3715 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003716 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00003717 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3718 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003719
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003720 // Convert the name of the scope type (the type prior to '::') into a type.
3721 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003722 QualType ScopeType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003723 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003724 FirstTypeName.Identifier) {
3725 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003726 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00003727 FirstTypeName.StartLocation,
3728 S, &SS, false, ObjectTypePtrForLookup);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003729 if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003730 Diag(FirstTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003731 diag::err_pseudo_dtor_destructor_non_type)
3732 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003733
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003734 if (isSFINAEContext())
3735 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003736
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003737 // Just drop this type. It's unnecessary anyway.
3738 ScopeType = QualType();
3739 } else
3740 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003741 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003742 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003743 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003744 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3745 TemplateId->getTemplateArgs(),
3746 TemplateId->NumArgs);
John McCall3e56fd42010-08-23 07:28:44 +00003747 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003748 TemplateId->TemplateNameLoc,
3749 TemplateId->LAngleLoc,
3750 TemplateArgsPtr,
3751 TemplateId->RAngleLoc);
3752 if (T.isInvalid() || !T.get()) {
3753 // Recover by dropping this type.
3754 ScopeType = QualType();
3755 } else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003756 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003757 }
3758 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003759
Douglas Gregor90ad9222010-02-24 23:02:30 +00003760 if (!ScopeType.isNull() && !ScopeTypeInfo)
3761 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
3762 FirstTypeName.StartLocation);
3763
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003764
John McCallb268a282010-08-23 23:25:46 +00003765 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00003766 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00003767 Destructed, HasTrailingLParen);
Douglas Gregore610ada2010-02-24 18:44:31 +00003768}
3769
Douglas Gregor668443e2011-01-20 00:18:04 +00003770ExprResult Sema::BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
3771 CXXMethodDecl *Method) {
John McCall16df1e52010-03-30 21:47:33 +00003772 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
3773 FoundDecl, Method))
Douglas Gregor668443e2011-01-20 00:18:04 +00003774 return true;
Eli Friedmanf7195532009-12-09 04:53:56 +00003775
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003776 MemberExpr *ME =
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003777 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
John McCall7decc9e2010-11-18 06:31:45 +00003778 SourceLocation(), Method->getType(),
3779 VK_RValue, OK_Ordinary);
3780 QualType ResultType = Method->getResultType();
3781 ExprValueKind VK = Expr::getValueKindForType(ResultType);
3782 ResultType = ResultType.getNonLValueExprType(Context);
3783
Douglas Gregor27381f32009-11-23 12:27:39 +00003784 MarkDeclarationReferenced(Exp->getLocStart(), Method);
3785 CXXMemberCallExpr *CE =
John McCall7decc9e2010-11-18 06:31:45 +00003786 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
Douglas Gregor27381f32009-11-23 12:27:39 +00003787 Exp->getLocEnd());
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00003788 return CE;
3789}
3790
Sebastian Redl4202c0f2010-09-10 20:55:43 +00003791ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
3792 SourceLocation RParen) {
Sebastian Redl4202c0f2010-09-10 20:55:43 +00003793 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
3794 Operand->CanThrow(Context),
3795 KeyLoc, RParen));
3796}
3797
3798ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
3799 Expr *Operand, SourceLocation RParen) {
3800 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00003801}
3802
John McCall34376a62010-12-04 03:47:34 +00003803/// Perform the conversions required for an expression used in a
3804/// context that ignores the result.
3805void Sema::IgnoredValueConversions(Expr *&E) {
John McCallfee942d2010-12-02 02:07:15 +00003806 // C99 6.3.2.1:
3807 // [Except in specific positions,] an lvalue that does not have
3808 // array type is converted to the value stored in the
3809 // designated object (and is no longer an lvalue).
John McCall34376a62010-12-04 03:47:34 +00003810 if (E->isRValue()) return;
John McCallfee942d2010-12-02 02:07:15 +00003811
John McCall34376a62010-12-04 03:47:34 +00003812 // We always want to do this on ObjC property references.
3813 if (E->getObjectKind() == OK_ObjCProperty) {
3814 ConvertPropertyForRValue(E);
3815 if (E->isRValue()) return;
3816 }
3817
3818 // Otherwise, this rule does not apply in C++, at least not for the moment.
3819 if (getLangOptions().CPlusPlus) return;
3820
3821 // GCC seems to also exclude expressions of incomplete enum type.
3822 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
3823 if (!T->getDecl()->isComplete()) {
3824 // FIXME: stupid workaround for a codegen bug!
3825 ImpCastExprToType(E, Context.VoidTy, CK_ToVoid);
3826 return;
3827 }
3828 }
3829
3830 DefaultFunctionArrayLvalueConversion(E);
John McCallca61b652010-12-04 12:29:11 +00003831 if (!E->getType()->isVoidType())
3832 RequireCompleteType(E->getExprLoc(), E->getType(),
3833 diag::err_incomplete_type);
John McCall34376a62010-12-04 03:47:34 +00003834}
3835
3836ExprResult Sema::ActOnFinishFullExpr(Expr *FullExpr) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003837 if (!FullExpr)
Douglas Gregora6e053e2010-12-15 01:34:56 +00003838 return ExprError();
John McCall34376a62010-12-04 03:47:34 +00003839
Douglas Gregor506bd562010-12-13 22:49:22 +00003840 if (DiagnoseUnexpandedParameterPack(FullExpr))
3841 return ExprError();
3842
John McCall34376a62010-12-04 03:47:34 +00003843 IgnoredValueConversions(FullExpr);
John McCallacf0ee52010-10-08 02:01:28 +00003844 CheckImplicitConversions(FullExpr);
John McCall5d413782010-12-06 08:20:24 +00003845 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00003846}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00003847
3848StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
3849 if (!FullStmt) return StmtError();
3850
John McCall5d413782010-12-06 08:20:24 +00003851 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00003852}