blob: 4ac162a9f9d05c922d836c807d2e256946821ac3 [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,
34 IdentifierInfo &II,
35 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();
74
75 bool AlreadySearched = false;
76 bool LookAtPrefix = true;
Sebastian Redla771d222010-07-07 23:17:38 +000077 // C++ [basic.lookup.qual]p6:
78 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
79 // the type-names are looked up as types in the scope designated by the
80 // nested-name-specifier. In a qualified-id of the form:
81 //
82 // ::[opt] nested-name-specifier ̃ class-name
83 //
84 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth8f254812010-02-21 10:19:54 +000085 // a qualified-id of the form:
Douglas Gregorfe17d252010-02-16 19:09:40 +000086 //
Sebastian Redla771d222010-07-07 23:17:38 +000087 // ::opt nested-name-specifier class-name :: ̃ class-name
Douglas Gregorfe17d252010-02-16 19:09:40 +000088 //
Sebastian Redla771d222010-07-07 23:17:38 +000089 // the class-names are looked up as types in the scope designated by
90 // the nested-name-specifier.
Douglas 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
93 // code below is permitted to look at the prefix of the
94 // nested-name-specifier.
95 DeclContext *DC = computeDeclContext(SS, EnteringContext);
96 if (DC && DC->isFileContext()) {
97 AlreadySearched = true;
98 LookupCtx = DC;
99 isDependent = false;
100 } else if (DC && isa<CXXRecordDecl>(DC))
101 LookAtPrefix = false;
102
103 // The second case from the C++03 rules quoted further above.
Douglas 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 }
Douglas Gregor46841e12010-02-23 00:15:22 +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();
131 assert((isDependent || !SearchType->isIncompleteType()) &&
132 "Caller should have completed object type");
133
134 LookInScope = true;
135 } else {
136 // Perform lookup into the current scope (only).
137 LookInScope = true;
138 }
139
140 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
141 for (unsigned Step = 0; Step != 2; ++Step) {
142 // Look for the name first in the computed lookup context (if we
143 // have one) and, if that fails to find a match, in the sope (if
144 // we're allowed to look there).
145 Found.clear();
146 if (Step == 0 && LookupCtx)
147 LookupQualifiedName(Found, LookupCtx);
Douglas 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
173 // issue 399, for which there isn't even an obvious direction.
174 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
175 QualType MemberOfType;
176 if (SS.isSet()) {
177 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
178 // Figure out the type of the context, if it has one.
John 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;
185
186 if (MemberOfType.isNull())
187 continue;
188
189 // We're referring into a class template specialization. If the
190 // class template we found is the same as the template being
191 // specialized, we found what we are looking for.
192 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
193 if (ClassTemplateSpecializationDecl *Spec
194 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
195 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
196 Template->getCanonicalDecl())
John McCallba7bf592010-08-24 05:47:05 +0000197 return ParsedType::make(MemberOfType);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000198 }
199
200 continue;
201 }
202
203 // We're referring to an unresolved class template
204 // specialization. Determine whether we class template we found
205 // is the same as the template being specialized or, if we don't
206 // know which template is being specialized, that it at least
207 // has the same name.
208 if (const TemplateSpecializationType *SpecType
209 = MemberOfType->getAs<TemplateSpecializationType>()) {
210 TemplateName SpecName = SpecType->getTemplateName();
211
212 // The class template we found is the same template being
213 // specialized.
214 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
215 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
John 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.
223 if (DependentTemplateName *DepTemplate
224 = 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)
256 << &II;
257 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:
269 // The top-level cv-qualifiers of the lvalue expression or the type-id
270 // that is the operand of typeid are always ignored.
271 // If the type of the type-id is a class type or a reference to a class
272 // type, the class shall be completely-defined.
Douglas 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();
Daniel Dunbar0547ad32010-05-11 21:32:35 +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();
301
302 // 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 }
313
314 // C++ [expr.typeid]p4:
315 // [...] If the type of the type-id is a reference to a possibly
316 // cv-qualified type, the result of the typeid expression refers to a
317 // std::type_info object representing the cv-unqualified referenced
318 // type.
Douglas 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 }
326
327 // If this is an unevaluated operand, clear out the set of
328 // declaration references we have been computing and eliminate any
329 // temporaries introduced in its computation.
330 if (isUnevaluatedOperand)
331 ExprEvalContexts.back().Context = Unevaluated;
332
333 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCallb268a282010-08-23 23:25:46 +0000334 E,
Douglas Gregor9da64192010-04-26 22:37:10 +0000335 SourceRange(TypeidLoc, RParenLoc)));
336}
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 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000354
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000355 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
Douglas Gregor9da64192010-04-26 22:37:10 +0000356
357 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();
364
365 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
Douglas Gregor9da64192010-04-26 22:37:10 +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 Pichet9dddd402010-12-20 03:51:03 +0000375// Get the CXXRecordDecl associated with QT bypassing 1 level of pointer,
376// reference or array type.
Francois Pichetbea85d82010-12-20 05:44:28 +0000377static CXXRecordDecl *GetCXXRecordOfUuidArg(QualType QT) {
Francois Pichet9dddd402010-12-20 03:51:03 +0000378 Type* Ty = QT.getTypePtr();;
379 if (QT->isPointerType() || QT->isReferenceType())
380 Ty = QT->getPointeeType().getTypePtr();
381 else if (QT->isArrayType())
382 Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
383
384 return Ty->getAsCXXRecordDecl();
385}
386
Francois Pichet9f4f2072010-09-08 12:20:18 +0000387/// \brief Build a Microsoft __uuidof expression with a type operand.
388ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
389 SourceLocation TypeidLoc,
390 TypeSourceInfo *Operand,
391 SourceLocation RParenLoc) {
Francois Pichet9dddd402010-12-20 03:51:03 +0000392 // Make sure Operand has an associated GUID.
393 CXXRecordDecl* RD = GetCXXRecordOfUuidArg(Operand->getType());
394 if (!RD || !RD->getAttr<UuidAttr>())
395 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
396
Francois Pichet9f4f2072010-09-08 12:20:18 +0000397 // FIXME: add __uuidof semantic analysis for type operand.
398 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
399 Operand,
400 SourceRange(TypeidLoc, RParenLoc)));
401}
402
403/// \brief Build a Microsoft __uuidof expression with an expression operand.
404ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
405 SourceLocation TypeidLoc,
406 Expr *E,
407 SourceLocation RParenLoc) {
Francois Pichet9dddd402010-12-20 03:51:03 +0000408 // Make sure E has an associated GUID.
409 // 0 is fine also.
410 CXXRecordDecl* RD = GetCXXRecordOfUuidArg(E->getType());
411 if ((!RD || !RD->getAttr<UuidAttr>()) &&
412 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
413 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
414
Francois Pichet9f4f2072010-09-08 12:20:18 +0000415 // FIXME: add __uuidof semantic analysis for expr operand.
416 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
417 E,
418 SourceRange(TypeidLoc, RParenLoc)));
419}
420
421/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
422ExprResult
423Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
424 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
425 // If MSVCGuidDecl has not been cached, do the lookup.
426 if (!MSVCGuidDecl) {
427 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
428 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
429 LookupQualifiedName(R, Context.getTranslationUnitDecl());
430 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
431 if (!MSVCGuidDecl)
432 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
433 }
434
435 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
436
437 if (isType) {
438 // The operand is a type; handle it as such.
439 TypeSourceInfo *TInfo = 0;
440 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
441 &TInfo);
442 if (T.isNull())
443 return ExprError();
444
445 if (!TInfo)
446 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
447
448 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
449 }
450
451 // The operand is an expression.
452 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
453}
454
Steve Naroff66356bd2007-09-16 14:56:35 +0000455/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCalldadc5752010-08-24 06:29:42 +0000456ExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000457Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000458 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000459 "Unknown C++ Boolean value!");
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000460 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
461 Context.BoolTy, OpLoc));
Bill Wendling4073ed52007-02-13 01:51:42 +0000462}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000463
Sebastian Redl576fd422009-05-10 18:38:11 +0000464/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCalldadc5752010-08-24 06:29:42 +0000465ExprResult
Sebastian Redl576fd422009-05-10 18:38:11 +0000466Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
467 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
468}
469
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000470/// ActOnCXXThrow - Parse throw expressions.
John McCalldadc5752010-08-24 06:29:42 +0000471ExprResult
John McCallb268a282010-08-23 23:25:46 +0000472Sema::ActOnCXXThrow(SourceLocation OpLoc, Expr *Ex) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000473 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
474 return ExprError();
475 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
476}
477
478/// CheckCXXThrowOperand - Validate the operand of a throw.
479bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
480 // C++ [except.throw]p3:
Douglas Gregor247894b2009-12-23 22:04:40 +0000481 // A throw-expression initializes a temporary object, called the exception
482 // object, the type of which is determined by removing any top-level
483 // cv-qualifiers from the static type of the operand of throw and adjusting
484 // the type from "array of T" or "function returning T" to "pointer to T"
485 // or "pointer to function returning T", [...]
486 if (E->getType().hasQualifiers())
John McCalle3027922010-08-25 11:45:40 +0000487 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000488 CastCategory(E));
Douglas Gregor247894b2009-12-23 22:04:40 +0000489
Sebastian Redl4de47b42009-04-27 20:27:31 +0000490 DefaultFunctionArrayConversion(E);
491
492 // If the type of the exception would be an incomplete type or a pointer
493 // to an incomplete type other than (cv) void the program is ill-formed.
494 QualType Ty = E->getType();
John McCall2e6567a2010-04-22 01:10:34 +0000495 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000496 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000497 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000498 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000499 }
500 if (!isPointer || !Ty->isVoidType()) {
501 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlsson029fc692009-08-26 22:59:12 +0000502 PDiag(isPointer ? diag::err_throw_incomplete_ptr
503 : diag::err_throw_incomplete)
504 << E->getSourceRange()))
Sebastian Redl4de47b42009-04-27 20:27:31 +0000505 return true;
Rafael Espindola70e040d2010-03-02 21:28:26 +0000506
Douglas Gregore8154332010-04-15 18:05:39 +0000507 if (RequireNonAbstractType(ThrowLoc, E->getType(),
508 PDiag(diag::err_throw_abstract_type)
509 << E->getSourceRange()))
510 return true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000511 }
512
John McCall2e6567a2010-04-22 01:10:34 +0000513 // Initialize the exception result. This implicitly weeds out
514 // abstract types or types with inaccessible copy constructors.
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000515 // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p34.
John McCall2e6567a2010-04-22 01:10:34 +0000516 InitializedEntity Entity =
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000517 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
518 /*NRVO=*/false);
John McCalldadc5752010-08-24 06:29:42 +0000519 ExprResult Res = PerformCopyInitialization(Entity,
John McCall2e6567a2010-04-22 01:10:34 +0000520 SourceLocation(),
521 Owned(E));
522 if (Res.isInvalid())
523 return true;
524 E = Res.takeAs<Expr>();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000525
Eli Friedman91a3d272010-06-03 20:39:03 +0000526 // If the exception has class type, we need additional handling.
527 const RecordType *RecordTy = Ty->getAs<RecordType>();
528 if (!RecordTy)
529 return false;
530 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
531
Douglas Gregor88d292c2010-05-13 16:44:06 +0000532 // If we are throwing a polymorphic class type or pointer thereof,
533 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000534 MarkVTableUsed(ThrowLoc, RD);
535
Eli Friedman36ebbec2010-10-12 20:32:36 +0000536 // If a pointer is thrown, the referenced object will not be destroyed.
537 if (isPointer)
538 return false;
539
Eli Friedman91a3d272010-06-03 20:39:03 +0000540 // If the class has a non-trivial destructor, we must be able to call it.
541 if (RD->hasTrivialDestructor())
542 return false;
543
Douglas Gregorbac74902010-07-01 14:13:13 +0000544 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +0000545 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman91a3d272010-06-03 20:39:03 +0000546 if (!Destructor)
547 return false;
548
549 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
550 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregor747eb782010-07-08 06:14:04 +0000551 PDiag(diag::err_access_dtor_exception) << Ty);
Sebastian Redl4de47b42009-04-27 20:27:31 +0000552 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000553}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000554
John McCalldadc5752010-08-24 06:29:42 +0000555ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000556 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
557 /// is a non-lvalue expression whose value is the address of the object for
558 /// which the function is called.
559
John McCall87fe5d52010-05-20 01:18:31 +0000560 DeclContext *DC = getFunctionLevelDeclContext();
561 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000562 if (MD->isInstance())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000563 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregorb15af892010-01-07 23:12:05 +0000564 MD->getThisType(Context),
565 /*isImplicit=*/false));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000566
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000567 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000568}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000569
John McCalldadc5752010-08-24 06:29:42 +0000570ExprResult
Douglas Gregor2b88c112010-09-08 00:15:04 +0000571Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000572 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000573 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000574 SourceLocation RParenLoc) {
Douglas Gregor7df89f52010-02-05 19:11:37 +0000575 if (!TypeRep)
576 return ExprError();
Douglas Gregor2b88c112010-09-08 00:15:04 +0000577
John McCall97513962010-01-15 18:39:57 +0000578 TypeSourceInfo *TInfo;
579 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
580 if (!TInfo)
581 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregor2b88c112010-09-08 00:15:04 +0000582
583 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
584}
585
586/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
587/// Can be interpreted either as function-style casting ("int(x)")
588/// or class type construction ("ClassType(x,y,z)")
589/// or creation of a value-initialized type ("int()").
590ExprResult
591Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
592 SourceLocation LParenLoc,
593 MultiExprArg exprs,
594 SourceLocation RParenLoc) {
595 QualType Ty = TInfo->getType();
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000596 unsigned NumExprs = exprs.size();
597 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregor2b88c112010-09-08 00:15:04 +0000598 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000599 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
600
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000601 if (Ty->isDependentType() ||
Douglas Gregor0950e412009-03-13 21:01:28 +0000602 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000603 exprs.release();
Mike Stump11289f42009-09-09 15:08:12 +0000604
Douglas Gregor2b88c112010-09-08 00:15:04 +0000605 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregorce934142009-05-20 18:46:25 +0000606 LParenLoc,
607 Exprs, NumExprs,
608 RParenLoc));
Douglas Gregor0950e412009-03-13 21:01:28 +0000609 }
610
Anders Carlsson55243162009-08-27 03:53:50 +0000611 if (Ty->isArrayType())
612 return ExprError(Diag(TyBeginLoc,
613 diag::err_value_init_for_array_type) << FullRange);
614 if (!Ty->isVoidType() &&
615 RequireCompleteType(TyBeginLoc, Ty,
616 PDiag(diag::err_invalid_incomplete_type_use)
617 << FullRange))
618 return ExprError();
Fariborz Jahanian9a14b842009-10-23 21:01:39 +0000619
Anders Carlsson55243162009-08-27 03:53:50 +0000620 if (RequireNonAbstractType(TyBeginLoc, Ty,
621 diag::err_allocation_of_abstract_type))
622 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000623
624
Douglas Gregordd04d332009-01-16 18:33:17 +0000625 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000626 // If the expression list is a single expression, the type conversion
627 // expression is equivalent (in definedness, and if defined in meaning) to the
628 // corresponding cast expression.
629 //
630 if (NumExprs == 1) {
John McCall8cb679e2010-11-15 09:13:47 +0000631 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +0000632 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +0000633 CXXCastPath BasePath;
Douglas Gregor2b88c112010-09-08 00:15:04 +0000634 if (CheckCastTypes(TInfo->getTypeLoc().getSourceRange(), Ty, Exprs[0],
John McCall7decc9e2010-11-18 06:31:45 +0000635 Kind, VK, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +0000636 /*FunctionalStyle=*/true))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000637 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +0000638
639 exprs.release();
Anders Carlssone9766d52009-09-09 21:33:21 +0000640
John McCallcf142162010-08-07 06:22:56 +0000641 return Owned(CXXFunctionalCastExpr::Create(Context,
Douglas Gregor2b88c112010-09-08 00:15:04 +0000642 Ty.getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +0000643 VK, TInfo, TyBeginLoc, Kind,
John McCallcf142162010-08-07 06:22:56 +0000644 Exprs[0], &BasePath,
645 RParenLoc));
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000646 }
647
Douglas Gregor8ec51732010-09-08 21:40:08 +0000648 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
649 InitializationKind Kind
650 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
651 LParenLoc, RParenLoc)
652 : InitializationKind::CreateValue(TyBeginLoc,
653 LParenLoc, RParenLoc);
654 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
655 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000656
Douglas Gregor8ec51732010-09-08 21:40:08 +0000657 // FIXME: Improve AST representation?
658 return move(Result);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000659}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000660
661
Sebastian Redlbd150f42008-11-21 19:14:01 +0000662/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
663/// @code new (memory) int[size][4] @endcode
664/// or
665/// @code ::new Foo(23, "hello") @endcode
666/// For the interpretation of this heap of arguments, consult the base version.
John McCalldadc5752010-08-24 06:29:42 +0000667ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +0000668Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000669 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Douglas Gregorf2753b32010-07-13 15:54:32 +0000670 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl351bb782008-12-02 14:43:59 +0000671 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000672 MultiExprArg ConstructorArgs,
Mike Stump11289f42009-09-09 15:08:12 +0000673 SourceLocation ConstructorRParen) {
Sebastian Redl351bb782008-12-02 14:43:59 +0000674 Expr *ArraySize = 0;
Sebastian Redl351bb782008-12-02 14:43:59 +0000675 // If the specified type is an array, unwrap it and save the expression.
676 if (D.getNumTypeObjects() > 0 &&
677 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
678 DeclaratorChunk &Chunk = D.getTypeObject(0);
679 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000680 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
681 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000682 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000683 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
684 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000685
Sebastian Redl351bb782008-12-02 14:43:59 +0000686 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000687 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +0000688 }
689
Douglas Gregor73341c42009-09-11 00:18:58 +0000690 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000691 if (ArraySize) {
692 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +0000693 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
694 break;
695
696 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
697 if (Expr *NumElts = (Expr *)Array.NumElts) {
698 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
699 !NumElts->isIntegerConstantExpr(Context)) {
700 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
701 << NumElts->getSourceRange();
702 return ExprError();
703 }
704 }
705 }
706 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000707
John McCall8cb7bdf2010-06-04 23:28:52 +0000708 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
709 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000710 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000711 return ExprError();
Ted Kremenekabb1f912010-06-25 22:48:49 +0000712
Douglas Gregor0744ef62010-09-07 21:49:58 +0000713 if (!TInfo)
714 TInfo = Context.getTrivialTypeSourceInfo(AllocType);
715
Ted Kremenekabb1f912010-06-25 22:48:49 +0000716 SourceRange R = TInfo->getTypeLoc().getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +0000717 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000718 PlacementLParen,
Mike Stump11289f42009-09-09 15:08:12 +0000719 move(PlacementArgs),
Douglas Gregord0fefba2009-05-21 00:00:09 +0000720 PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +0000721 TypeIdParens,
Mike Stump11289f42009-09-09 15:08:12 +0000722 AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +0000723 TInfo,
John McCallb268a282010-08-23 23:25:46 +0000724 ArraySize,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000725 ConstructorLParen,
726 move(ConstructorArgs),
727 ConstructorRParen);
728}
729
John McCalldadc5752010-08-24 06:29:42 +0000730ExprResult
Douglas Gregord0fefba2009-05-21 00:00:09 +0000731Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
732 SourceLocation PlacementLParen,
733 MultiExprArg PlacementArgs,
734 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +0000735 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000736 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +0000737 TypeSourceInfo *AllocTypeInfo,
John McCallb268a282010-08-23 23:25:46 +0000738 Expr *ArraySize,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000739 SourceLocation ConstructorLParen,
740 MultiExprArg ConstructorArgs,
741 SourceLocation ConstructorRParen) {
Douglas Gregor0744ef62010-09-07 21:49:58 +0000742 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
Sebastian Redl351bb782008-12-02 14:43:59 +0000743
Douglas Gregorcda95f42010-05-16 16:01:03 +0000744 // Per C++0x [expr.new]p5, the type being constructed may be a
745 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +0000746 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +0000747 if (const ConstantArrayType *Array
748 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000749 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
750 Context.getSizeType(),
751 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +0000752 AllocType = Array->getElementType();
753 }
754 }
Sebastian Redlbd150f42008-11-21 19:14:01 +0000755
Douglas Gregor3999e152010-10-06 16:00:31 +0000756 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
757 return ExprError();
758
Douglas Gregorcda95f42010-05-16 16:01:03 +0000759 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl351bb782008-12-02 14:43:59 +0000760
Sebastian Redlbd150f42008-11-21 19:14:01 +0000761 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
762 // or enumeration type with a non-negative value."
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000763 if (ArraySize && !ArraySize->isTypeDependent()) {
Douglas Gregor4799d032010-06-30 00:20:43 +0000764
Sebastian Redl351bb782008-12-02 14:43:59 +0000765 QualType SizeType = ArraySize->getType();
Douglas Gregorf4ea7252010-06-29 23:17:37 +0000766
John McCalldadc5752010-08-24 06:29:42 +0000767 ExprResult ConvertedSize
John McCallb268a282010-08-23 23:25:46 +0000768 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
Douglas Gregor4799d032010-06-30 00:20:43 +0000769 PDiag(diag::err_array_size_not_integral),
770 PDiag(diag::err_array_size_incomplete_type)
771 << ArraySize->getSourceRange(),
772 PDiag(diag::err_array_size_explicit_conversion),
773 PDiag(diag::note_array_size_conversion),
774 PDiag(diag::err_array_size_ambiguous_conversion),
775 PDiag(diag::note_array_size_conversion),
776 PDiag(getLangOptions().CPlusPlus0x? 0
777 : diag::ext_array_size_conversion));
778 if (ConvertedSize.isInvalid())
779 return ExprError();
780
John McCallb268a282010-08-23 23:25:46 +0000781 ArraySize = ConvertedSize.take();
Douglas Gregor4799d032010-06-30 00:20:43 +0000782 SizeType = ArraySize->getType();
Douglas Gregor0bf31402010-10-08 23:50:27 +0000783 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +0000784 return ExprError();
785
Sebastian Redl351bb782008-12-02 14:43:59 +0000786 // Let's see if this is a constant < 0. If so, we reject it out of hand.
787 // We don't care about special rules, so we tell the machinery it's not
788 // evaluated - it gives us a result in more cases.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000789 if (!ArraySize->isValueDependent()) {
790 llvm::APSInt Value;
791 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
792 if (Value < llvm::APSInt(
Anders Carlsson8ab20bb2009-09-23 00:37:25 +0000793 llvm::APInt::getNullValue(Value.getBitWidth()),
794 Value.isUnsigned()))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000795 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregorcaa1bf42010-08-18 00:39:00 +0000796 diag::err_typecheck_negative_array_size)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000797 << ArraySize->getSourceRange());
Douglas Gregorcaa1bf42010-08-18 00:39:00 +0000798
799 if (!AllocType->isDependentType()) {
800 unsigned ActiveSizeBits
801 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
802 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
803 Diag(ArraySize->getSourceRange().getBegin(),
804 diag::err_array_too_large)
805 << Value.toString(10)
806 << ArraySize->getSourceRange();
807 return ExprError();
808 }
809 }
Douglas Gregorf2753b32010-07-13 15:54:32 +0000810 } else if (TypeIdParens.isValid()) {
811 // Can't have dynamic array size when the type-id is in parentheses.
812 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
813 << ArraySize->getSourceRange()
814 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
815 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
816
817 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000818 }
Sebastian Redl351bb782008-12-02 14:43:59 +0000819 }
Anders Carlsson8ab20bb2009-09-23 00:37:25 +0000820
Eli Friedman06ed2a52009-10-20 08:27:19 +0000821 ImpCastExprToType(ArraySize, Context.getSizeType(),
John McCalle3027922010-08-25 11:45:40 +0000822 CK_IntegralCast);
Sebastian Redl351bb782008-12-02 14:43:59 +0000823 }
Sebastian Redlbd150f42008-11-21 19:14:01 +0000824
Sebastian Redlbd150f42008-11-21 19:14:01 +0000825 FunctionDecl *OperatorNew = 0;
826 FunctionDecl *OperatorDelete = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000827 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
828 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000829
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000830 if (!AllocType->isDependentType() &&
831 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
832 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000833 SourceRange(PlacementLParen, PlacementRParen),
834 UseGlobal, AllocType, ArraySize, PlaceArgs,
835 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000836 return ExprError();
Fariborz Jahanian835026e2009-11-24 18:29:37 +0000837 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000838 if (OperatorNew) {
839 // Add default arguments, if any.
840 const FunctionProtoType *Proto =
841 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +0000842 VariadicCallType CallType =
843 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Anders Carlssonc144bc22010-05-03 02:07:56 +0000844
845 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
846 Proto, 1, PlaceArgs, NumPlaceArgs,
847 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +0000848 return ExprError();
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000849
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000850 NumPlaceArgs = AllPlaceArgs.size();
851 if (NumPlaceArgs > 0)
852 PlaceArgs = &AllPlaceArgs[0];
853 }
854
Sebastian Redlbd150f42008-11-21 19:14:01 +0000855 bool Init = ConstructorLParen.isValid();
856 // --- Choosing a constructor ---
Sebastian Redlbd150f42008-11-21 19:14:01 +0000857 CXXConstructorDecl *Constructor = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000858 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
859 unsigned NumConsArgs = ConstructorArgs.size();
John McCall37ad5512010-08-23 06:44:23 +0000860 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmanfd8d4e12009-11-08 22:15:39 +0000861
Anders Carlssonc6bb0e12010-05-03 15:45:23 +0000862 // Array 'new' can't have any initializers.
Anders Carlssone6ae81b2010-05-16 16:24:20 +0000863 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlssonc6bb0e12010-05-03 15:45:23 +0000864 SourceRange InitRange(ConsArgs[0]->getLocStart(),
865 ConsArgs[NumConsArgs - 1]->getLocEnd());
866
867 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
868 return ExprError();
869 }
870
Douglas Gregor85dabae2009-12-16 01:38:02 +0000871 if (!AllocType->isDependentType() &&
872 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
873 // C++0x [expr.new]p15:
874 // A new-expression that creates an object of type T initializes that
875 // object as follows:
876 InitializationKind Kind
877 // - If the new-initializer is omitted, the object is default-
878 // initialized (8.5); if no initialization is performed,
879 // the object has indeterminate value
Douglas Gregor0744ef62010-09-07 21:49:58 +0000880 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
Douglas Gregor85dabae2009-12-16 01:38:02 +0000881 // - Otherwise, the new-initializer is interpreted according to the
882 // initialization rules of 8.5 for direct-initialization.
Douglas Gregor0744ef62010-09-07 21:49:58 +0000883 : InitializationKind::CreateDirect(TypeRange.getBegin(),
Douglas Gregor85dabae2009-12-16 01:38:02 +0000884 ConstructorLParen,
885 ConstructorRParen);
886
Douglas Gregor85dabae2009-12-16 01:38:02 +0000887 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +0000888 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000889 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
John McCalldadc5752010-08-24 06:29:42 +0000890 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor85dabae2009-12-16 01:38:02 +0000891 move(ConstructorArgs));
892 if (FullInit.isInvalid())
893 return ExprError();
894
895 // FullInit is our initializer; walk through it to determine if it's a
896 // constructor call, which CXXNewExpr handles directly.
897 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
898 if (CXXBindTemporaryExpr *Binder
899 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
900 FullInitExpr = Binder->getSubExpr();
901 if (CXXConstructExpr *Construct
902 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
903 Constructor = Construct->getConstructor();
904 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
905 AEnd = Construct->arg_end();
906 A != AEnd; ++A)
John McCallc3007a22010-10-26 07:05:15 +0000907 ConvertedConstructorArgs.push_back(*A);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000908 } else {
909 // Take the converted initializer.
910 ConvertedConstructorArgs.push_back(FullInit.release());
911 }
912 } else {
913 // No initialization required.
914 }
915
916 // Take the converted arguments and use them for the new expression.
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000917 NumConsArgs = ConvertedConstructorArgs.size();
918 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redlbd150f42008-11-21 19:14:01 +0000919 }
Douglas Gregor85dabae2009-12-16 01:38:02 +0000920
Douglas Gregor6642ca22010-02-26 05:06:18 +0000921 // Mark the new and delete operators as referenced.
922 if (OperatorNew)
923 MarkDeclarationReferenced(StartLoc, OperatorNew);
924 if (OperatorDelete)
925 MarkDeclarationReferenced(StartLoc, OperatorDelete);
926
Sebastian Redlbd150f42008-11-21 19:14:01 +0000927 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor4bbd1ac2009-10-17 21:40:42 +0000928
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000929 PlacementArgs.release();
930 ConstructorArgs.release();
Ted Kremenekabb1f912010-06-25 22:48:49 +0000931
Ted Kremenek9d6eb402010-02-11 22:51:03 +0000932 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregorf2753b32010-07-13 15:54:32 +0000933 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenek9d6eb402010-02-11 22:51:03 +0000934 ArraySize, Constructor, Init,
935 ConsArgs, NumConsArgs, OperatorDelete,
Douglas Gregor0744ef62010-09-07 21:49:58 +0000936 ResultType, AllocTypeInfo,
937 StartLoc,
Ted Kremenek9d6eb402010-02-11 22:51:03 +0000938 Init ? ConstructorRParen :
Chandler Carruth01718152010-10-25 08:47:36 +0000939 TypeRange.getEnd(),
940 ConstructorLParen, ConstructorRParen));
Sebastian Redlbd150f42008-11-21 19:14:01 +0000941}
942
943/// CheckAllocatedType - Checks that a type is suitable as the allocated type
944/// in a new-expression.
945/// dimension off and stores the size expression in ArraySize.
Douglas Gregord0fefba2009-05-21 00:00:09 +0000946bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000947 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +0000948 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
949 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +0000950 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +0000951 return Diag(Loc, diag::err_bad_new_type)
952 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +0000953 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +0000954 return Diag(Loc, diag::err_bad_new_type)
955 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +0000956 else if (!AllocType->isDependentType() &&
Douglas Gregord0fefba2009-05-21 00:00:09 +0000957 RequireCompleteType(Loc, AllocType,
Anders Carlssond624e162009-08-26 23:45:07 +0000958 PDiag(diag::err_new_incomplete_type)
959 << R))
Sebastian Redlbd150f42008-11-21 19:14:01 +0000960 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +0000961 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +0000962 diag::err_allocation_of_abstract_type))
963 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +0000964 else if (AllocType->isVariablyModifiedType())
965 return Diag(Loc, diag::err_variably_modified_new_type)
966 << AllocType;
967
Sebastian Redlbd150f42008-11-21 19:14:01 +0000968 return false;
969}
970
Douglas Gregor6642ca22010-02-26 05:06:18 +0000971/// \brief Determine whether the given function is a non-placement
972/// deallocation function.
973static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
974 if (FD->isInvalidDecl())
975 return false;
976
977 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
978 return Method->isUsualDeallocationFunction();
979
980 return ((FD->getOverloadedOperator() == OO_Delete ||
981 FD->getOverloadedOperator() == OO_Array_Delete) &&
982 FD->getNumParams() == 1);
983}
984
Sebastian Redlfaf68082008-12-03 20:26:15 +0000985/// FindAllocationFunctions - Finds the overloads of operator new and delete
986/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000987bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
988 bool UseGlobal, QualType AllocType,
989 bool IsArray, Expr **PlaceArgs,
990 unsigned NumPlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +0000991 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +0000992 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-12-03 20:26:15 +0000993 // --- Choosing an allocation function ---
994 // C++ 5.3.4p8 - 14 & 18
995 // 1) If UseGlobal is true, only look in the global scope. Else, also look
996 // in the scope of the allocated class.
997 // 2) If an array size is given, look for operator new[], else look for
998 // operator new.
999 // 3) The first argument is always size_t. Append the arguments from the
1000 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +00001001
1002 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
1003 // We don't care about the actual value of this argument.
1004 // FIXME: Should the Sema create the expression and embed it in the syntax
1005 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001006 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Anders Carlssona471db02009-08-16 20:29:29 +00001007 Context.Target.getPointerWidth(0)),
1008 Context.getSizeType(),
1009 SourceLocation());
1010 AllocArgs[0] = &Size;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001011 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1012
Douglas Gregor6642ca22010-02-26 05:06:18 +00001013 // C++ [expr.new]p8:
1014 // If the allocated type is a non-array type, the allocation
1015 // function’s name is operator new and the deallocation function’s
1016 // name is operator delete. If the allocated type is an array
1017 // type, the allocation function’s name is operator new[] and the
1018 // deallocation function’s name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +00001019 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1020 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001021 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1022 IsArray ? OO_Array_Delete : OO_Delete);
1023
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001024 QualType AllocElemType = Context.getBaseElementType(AllocType);
1025
1026 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump11289f42009-09-09 15:08:12 +00001027 CXXRecordDecl *Record
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001028 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001029 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +00001030 AllocArgs.size(), Record, /*AllowMissing=*/true,
1031 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +00001032 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001033 }
1034 if (!OperatorNew) {
1035 // Didn't find a member overload. Look for a global one.
1036 DeclareGlobalNewDelete();
Sebastian Redl33a31012008-12-04 22:20:51 +00001037 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001038 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +00001039 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1040 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +00001041 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001042 }
1043
John McCall0f55a032010-04-20 02:18:25 +00001044 // We don't need an operator delete if we're running under
1045 // -fno-exceptions.
1046 if (!getLangOptions().Exceptions) {
1047 OperatorDelete = 0;
1048 return false;
1049 }
1050
Anders Carlsson6f9dabf2009-05-31 20:26:12 +00001051 // FindAllocationOverload can change the passed in arguments, so we need to
1052 // copy them back.
1053 if (NumPlaceArgs > 0)
1054 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001055
Douglas Gregor6642ca22010-02-26 05:06:18 +00001056 // C++ [expr.new]p19:
1057 //
1058 // If the new-expression begins with a unary :: operator, the
1059 // deallocation function’s name is looked up in the global
1060 // scope. Otherwise, if the allocated type is a class type T or an
1061 // array thereof, the deallocation function’s name is looked up in
1062 // the scope of T. If this lookup fails to find the name, or if
1063 // the allocated type is not a class type or array thereof, the
1064 // deallocation function’s name is looked up in the global scope.
1065 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001066 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00001067 CXXRecordDecl *RD
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001068 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00001069 LookupQualifiedName(FoundDelete, RD);
1070 }
John McCallfb6f5262010-03-18 08:19:33 +00001071 if (FoundDelete.isAmbiguous())
1072 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00001073
1074 if (FoundDelete.empty()) {
1075 DeclareGlobalNewDelete();
1076 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1077 }
1078
1079 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00001080
1081 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1082
John McCalld3be2c82010-09-14 21:34:24 +00001083 // Whether we're looking for a placement operator delete is dictated
1084 // by whether we selected a placement operator new, not by whether
1085 // we had explicit placement arguments. This matters for things like
1086 // struct A { void *operator new(size_t, int = 0); ... };
1087 // A *a = new A()
1088 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1089
1090 if (isPlacementNew) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00001091 // C++ [expr.new]p20:
1092 // A declaration of a placement deallocation function matches the
1093 // declaration of a placement allocation function if it has the
1094 // same number of parameters and, after parameter transformations
1095 // (8.3.5), all parameter types except the first are
1096 // identical. [...]
1097 //
1098 // To perform this comparison, we compute the function type that
1099 // the deallocation function should have, and use that type both
1100 // for template argument deduction and for comparison purposes.
John McCalldb40c7f2010-12-14 08:05:40 +00001101 //
1102 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6642ca22010-02-26 05:06:18 +00001103 QualType ExpectedFunctionType;
1104 {
1105 const FunctionProtoType *Proto
1106 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00001107
Douglas Gregor6642ca22010-02-26 05:06:18 +00001108 llvm::SmallVector<QualType, 4> ArgTypes;
1109 ArgTypes.push_back(Context.VoidPtrTy);
1110 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1111 ArgTypes.push_back(Proto->getArgType(I));
1112
John McCalldb40c7f2010-12-14 08:05:40 +00001113 FunctionProtoType::ExtProtoInfo EPI;
1114 EPI.Variadic = Proto->isVariadic();
1115
Douglas Gregor6642ca22010-02-26 05:06:18 +00001116 ExpectedFunctionType
1117 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
John McCalldb40c7f2010-12-14 08:05:40 +00001118 ArgTypes.size(), EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001119 }
1120
1121 for (LookupResult::iterator D = FoundDelete.begin(),
1122 DEnd = FoundDelete.end();
1123 D != DEnd; ++D) {
1124 FunctionDecl *Fn = 0;
1125 if (FunctionTemplateDecl *FnTmpl
1126 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1127 // Perform template argument deduction to try to match the
1128 // expected function type.
1129 TemplateDeductionInfo Info(Context, StartLoc);
1130 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1131 continue;
1132 } else
1133 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1134
1135 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00001136 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001137 }
1138 } else {
1139 // C++ [expr.new]p20:
1140 // [...] Any non-placement deallocation function matches a
1141 // non-placement allocation function. [...]
1142 for (LookupResult::iterator D = FoundDelete.begin(),
1143 DEnd = FoundDelete.end();
1144 D != DEnd; ++D) {
1145 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1146 if (isNonPlacementDeallocationFunction(Fn))
John McCalla0296f72010-03-19 07:35:19 +00001147 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001148 }
1149 }
1150
1151 // C++ [expr.new]p20:
1152 // [...] If the lookup finds a single matching deallocation
1153 // function, that function will be called; otherwise, no
1154 // deallocation function will be called.
1155 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00001156 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00001157
1158 // C++0x [expr.new]p20:
1159 // If the lookup finds the two-parameter form of a usual
1160 // deallocation function (3.7.4.2) and that function, considered
1161 // as a placement deallocation function, would have been
1162 // selected as a match for the allocation function, the program
1163 // is ill-formed.
1164 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1165 isNonPlacementDeallocationFunction(OperatorDelete)) {
1166 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1167 << SourceRange(PlaceArgs[0]->getLocStart(),
1168 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1169 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1170 << DeleteName;
John McCallfb6f5262010-03-18 08:19:33 +00001171 } else {
1172 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCalla0296f72010-03-19 07:35:19 +00001173 Matches[0].first);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001174 }
1175 }
1176
Sebastian Redlfaf68082008-12-03 20:26:15 +00001177 return false;
1178}
1179
Sebastian Redl33a31012008-12-04 22:20:51 +00001180/// FindAllocationOverload - Find an fitting overload for the allocation
1181/// function in the specified scope.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001182bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1183 DeclarationName Name, Expr** Args,
1184 unsigned NumArgs, DeclContext *Ctx,
Mike Stump11289f42009-09-09 15:08:12 +00001185 bool AllowMissing, FunctionDecl *&Operator) {
John McCall27b18f82009-11-17 02:14:36 +00001186 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1187 LookupQualifiedName(R, Ctx);
John McCall9f3059a2009-10-09 21:13:30 +00001188 if (R.empty()) {
Sebastian Redl33a31012008-12-04 22:20:51 +00001189 if (AllowMissing)
1190 return false;
Sebastian Redl33a31012008-12-04 22:20:51 +00001191 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00001192 << Name << Range;
Sebastian Redl33a31012008-12-04 22:20:51 +00001193 }
1194
John McCallfb6f5262010-03-18 08:19:33 +00001195 if (R.isAmbiguous())
1196 return true;
1197
1198 R.suppressDiagnostics();
John McCall9f3059a2009-10-09 21:13:30 +00001199
John McCallbc077cf2010-02-08 23:07:23 +00001200 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor80a6cc52009-09-30 00:03:47 +00001201 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1202 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor55297ac2008-12-23 00:26:44 +00001203 // Even member operator new/delete are implicitly treated as
1204 // static, so don't use AddMemberCandidate.
John McCalla0296f72010-03-19 07:35:19 +00001205 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth93538422010-02-03 11:02:14 +00001206
John McCalla0296f72010-03-19 07:35:19 +00001207 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1208 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth93538422010-02-03 11:02:14 +00001209 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1210 Candidates,
1211 /*SuppressUserConversions=*/false);
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001212 continue;
Chandler Carruth93538422010-02-03 11:02:14 +00001213 }
1214
John McCalla0296f72010-03-19 07:35:19 +00001215 FunctionDecl *Fn = cast<FunctionDecl>(D);
1216 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth93538422010-02-03 11:02:14 +00001217 /*SuppressUserConversions=*/false);
Sebastian Redl33a31012008-12-04 22:20:51 +00001218 }
1219
1220 // Do the resolution.
1221 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00001222 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl33a31012008-12-04 22:20:51 +00001223 case OR_Success: {
1224 // Got one!
1225 FunctionDecl *FnDecl = Best->Function;
1226 // The first argument is size_t, and the first parameter must be size_t,
1227 // too. This is checked on declaration and can be assumed. (It can't be
1228 // asserted on, though, since invalid decls are left in there.)
John McCallfb6f5262010-03-18 08:19:33 +00001229 // Watch out for variadic allocator function.
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001230 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1231 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
John McCalldadc5752010-08-24 06:29:42 +00001232 ExprResult Result
Douglas Gregor34147272010-03-26 20:35:59 +00001233 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001234 Context,
Douglas Gregor34147272010-03-26 20:35:59 +00001235 FnDecl->getParamDecl(i)),
1236 SourceLocation(),
John McCallc3007a22010-10-26 07:05:15 +00001237 Owned(Args[i]));
Douglas Gregor34147272010-03-26 20:35:59 +00001238 if (Result.isInvalid())
Sebastian Redl33a31012008-12-04 22:20:51 +00001239 return true;
Douglas Gregor34147272010-03-26 20:35:59 +00001240
1241 Args[i] = Result.takeAs<Expr>();
Sebastian Redl33a31012008-12-04 22:20:51 +00001242 }
1243 Operator = FnDecl;
John McCalla0296f72010-03-19 07:35:19 +00001244 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl33a31012008-12-04 22:20:51 +00001245 return false;
1246 }
1247
1248 case OR_No_Viable_Function:
Sebastian Redl33a31012008-12-04 22:20:51 +00001249 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00001250 << Name << Range;
John McCall5c32be02010-08-24 20:38:10 +00001251 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl33a31012008-12-04 22:20:51 +00001252 return true;
1253
1254 case OR_Ambiguous:
Sebastian Redl33a31012008-12-04 22:20:51 +00001255 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001256 << Name << Range;
John McCall5c32be02010-08-24 20:38:10 +00001257 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl33a31012008-12-04 22:20:51 +00001258 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001259
1260 case OR_Deleted:
1261 Diag(StartLoc, diag::err_ovl_deleted_call)
1262 << Best->Function->isDeleted()
1263 << Name << Range;
John McCall5c32be02010-08-24 20:38:10 +00001264 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001265 return true;
Sebastian Redl33a31012008-12-04 22:20:51 +00001266 }
1267 assert(false && "Unreachable, bad result from BestViableFunction");
1268 return true;
1269}
1270
1271
Sebastian Redlfaf68082008-12-03 20:26:15 +00001272/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1273/// delete. These are:
1274/// @code
1275/// void* operator new(std::size_t) throw(std::bad_alloc);
1276/// void* operator new[](std::size_t) throw(std::bad_alloc);
1277/// void operator delete(void *) throw();
1278/// void operator delete[](void *) throw();
1279/// @endcode
1280/// Note that the placement and nothrow forms of new are *not* implicitly
1281/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00001282void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001283 if (GlobalNewDeleteDeclared)
1284 return;
Douglas Gregor87f54062009-09-15 22:30:29 +00001285
1286 // C++ [basic.std.dynamic]p2:
1287 // [...] The following allocation and deallocation functions (18.4) are
1288 // implicitly declared in global scope in each translation unit of a
1289 // program
1290 //
1291 // void* operator new(std::size_t) throw(std::bad_alloc);
1292 // void* operator new[](std::size_t) throw(std::bad_alloc);
1293 // void operator delete(void*) throw();
1294 // void operator delete[](void*) throw();
1295 //
1296 // These implicit declarations introduce only the function names operator
1297 // new, operator new[], operator delete, operator delete[].
1298 //
1299 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1300 // "std" or "bad_alloc" as necessary to form the exception specification.
1301 // However, we do not make these implicit declarations visible to name
1302 // lookup.
Douglas Gregor87f54062009-09-15 22:30:29 +00001303 if (!StdBadAlloc) {
1304 // The "std::bad_alloc" class has not yet been declared, so build it
1305 // implicitly.
Abramo Bagnara6150c882010-05-11 21:36:43 +00001306 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00001307 getOrCreateStdNamespace(),
Douglas Gregor87f54062009-09-15 22:30:29 +00001308 SourceLocation(),
1309 &PP.getIdentifierTable().get("bad_alloc"),
1310 SourceLocation(), 0);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00001311 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00001312 }
1313
Sebastian Redlfaf68082008-12-03 20:26:15 +00001314 GlobalNewDeleteDeclared = true;
1315
1316 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1317 QualType SizeT = Context.getSizeType();
Nuno Lopes13c88c72009-12-16 16:59:22 +00001318 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001319
Sebastian Redlfaf68082008-12-03 20:26:15 +00001320 DeclareGlobalAllocationFunction(
1321 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001322 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001323 DeclareGlobalAllocationFunction(
1324 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001325 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001326 DeclareGlobalAllocationFunction(
1327 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1328 Context.VoidTy, VoidPtr);
1329 DeclareGlobalAllocationFunction(
1330 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1331 Context.VoidTy, VoidPtr);
1332}
1333
1334/// DeclareGlobalAllocationFunction - Declares a single implicit global
1335/// allocation function if it doesn't already exist.
1336void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopes13c88c72009-12-16 16:59:22 +00001337 QualType Return, QualType Argument,
1338 bool AddMallocAttr) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001339 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1340
1341 // Check if this function is already declared.
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001342 {
Douglas Gregor17eb26b2008-12-23 22:05:29 +00001343 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001344 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001345 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth93538422010-02-03 11:02:14 +00001346 // Only look at non-template functions, as it is the predefined,
1347 // non-templated allocation function we are trying to declare here.
1348 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1349 QualType InitialParamType =
Douglas Gregor684d7bd2009-12-22 23:42:49 +00001350 Context.getCanonicalType(
Chandler Carruth93538422010-02-03 11:02:14 +00001351 Func->getParamDecl(0)->getType().getUnqualifiedType());
1352 // FIXME: Do we need to check for default arguments here?
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00001353 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1354 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001355 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth93538422010-02-03 11:02:14 +00001356 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00001357 }
Chandler Carruth93538422010-02-03 11:02:14 +00001358 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00001359 }
1360 }
1361
Douglas Gregor87f54062009-09-15 22:30:29 +00001362 QualType BadAllocType;
1363 bool HasBadAllocExceptionSpec
1364 = (Name.getCXXOverloadedOperator() == OO_New ||
1365 Name.getCXXOverloadedOperator() == OO_Array_New);
1366 if (HasBadAllocExceptionSpec) {
1367 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00001368 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor87f54062009-09-15 22:30:29 +00001369 }
John McCalldb40c7f2010-12-14 08:05:40 +00001370
1371 FunctionProtoType::ExtProtoInfo EPI;
1372 EPI.HasExceptionSpec = true;
1373 if (HasBadAllocExceptionSpec) {
1374 EPI.NumExceptions = 1;
1375 EPI.Exceptions = &BadAllocType;
1376 }
Douglas Gregor87f54062009-09-15 22:30:29 +00001377
John McCalldb40c7f2010-12-14 08:05:40 +00001378 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001379 FunctionDecl *Alloc =
1380 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCall8e7d6562010-08-26 03:08:43 +00001381 FnType, /*TInfo=*/0, SC_None,
1382 SC_None, false, true);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001383 Alloc->setImplicit();
Nuno Lopes13c88c72009-12-16 16:59:22 +00001384
1385 if (AddMallocAttr)
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001386 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Nuno Lopes13c88c72009-12-16 16:59:22 +00001387
Sebastian Redlfaf68082008-12-03 20:26:15 +00001388 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCallbcd03502009-12-07 02:54:59 +00001389 0, Argument, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00001390 SC_None,
1391 SC_None, 0);
Douglas Gregord5058122010-02-11 01:19:42 +00001392 Alloc->setParams(&Param, 1);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001393
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001394 // FIXME: Also add this declaration to the IdentifierResolver, but
1395 // make sure it is at the end of the chain to coincide with the
1396 // global scope.
John McCallcc14d1f2010-08-24 08:50:51 +00001397 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001398}
1399
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001400bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1401 DeclarationName Name,
Anders Carlssonf98849e2009-12-02 17:15:43 +00001402 FunctionDecl* &Operator) {
John McCall27b18f82009-11-17 02:14:36 +00001403 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001404 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00001405 LookupQualifiedName(Found, RD);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001406
John McCall27b18f82009-11-17 02:14:36 +00001407 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001408 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001409
Chandler Carruthb6f99172010-06-28 00:30:51 +00001410 Found.suppressDiagnostics();
1411
John McCall66a87592010-08-04 00:31:26 +00001412 llvm::SmallVector<DeclAccessPair,4> Matches;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001413 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1414 F != FEnd; ++F) {
Chandler Carruth9b418232010-08-08 07:04:00 +00001415 NamedDecl *ND = (*F)->getUnderlyingDecl();
1416
1417 // Ignore template operator delete members from the check for a usual
1418 // deallocation function.
1419 if (isa<FunctionTemplateDecl>(ND))
1420 continue;
1421
1422 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall66a87592010-08-04 00:31:26 +00001423 Matches.push_back(F.getPair());
1424 }
1425
1426 // There's exactly one suitable operator; pick it.
1427 if (Matches.size() == 1) {
1428 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
1429 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1430 Matches[0]);
1431 return false;
1432
1433 // We found multiple suitable operators; complain about the ambiguity.
1434 } else if (!Matches.empty()) {
1435 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1436 << Name << RD;
1437
1438 for (llvm::SmallVectorImpl<DeclAccessPair>::iterator
1439 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1440 Diag((*F)->getUnderlyingDecl()->getLocation(),
1441 diag::note_member_declared_here) << Name;
1442 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001443 }
1444
1445 // We did find operator delete/operator delete[] declarations, but
1446 // none of them were suitable.
1447 if (!Found.empty()) {
1448 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1449 << Name << RD;
1450
1451 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
John McCall66a87592010-08-04 00:31:26 +00001452 F != FEnd; ++F)
1453 Diag((*F)->getUnderlyingDecl()->getLocation(),
1454 diag::note_member_declared_here) << Name;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001455
1456 return true;
1457 }
1458
1459 // Look for a global declaration.
1460 DeclareGlobalNewDelete();
1461 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1462
1463 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1464 Expr* DeallocArgs[1];
1465 DeallocArgs[0] = &Null;
1466 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1467 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1468 Operator))
1469 return true;
1470
1471 assert(Operator && "Did not find a deallocation function!");
1472 return false;
1473}
1474
Sebastian Redlbd150f42008-11-21 19:14:01 +00001475/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1476/// @code ::delete ptr; @endcode
1477/// or
1478/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00001479ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001480Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John McCallb268a282010-08-23 23:25:46 +00001481 bool ArrayForm, Expr *Ex) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001482 // C++ [expr.delete]p1:
1483 // The operand shall have a pointer type, or a class type having a single
1484 // conversion function to a pointer type. The result has type void.
1485 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00001486 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1487
Anders Carlssona471db02009-08-16 20:29:29 +00001488 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00001489 bool ArrayFormAsWritten = ArrayForm;
Mike Stump11289f42009-09-09 15:08:12 +00001490
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001491 if (!Ex->isTypeDependent()) {
1492 QualType Type = Ex->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00001493
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001494 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregorf65f4902010-07-29 14:44:35 +00001495 if (RequireCompleteType(StartLoc, Type,
1496 PDiag(diag::err_delete_incomplete_class_type)))
1497 return ExprError();
1498
John McCallda4458e2010-03-31 01:36:47 +00001499 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1500
Fariborz Jahanianb54ccb22009-09-11 21:44:33 +00001501 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCallda4458e2010-03-31 01:36:47 +00001502 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001503 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001504 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00001505 NamedDecl *D = I.getDecl();
1506 if (isa<UsingShadowDecl>(D))
1507 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1508
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001509 // Skip over templated conversion functions; they aren't considered.
John McCallda4458e2010-03-31 01:36:47 +00001510 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001511 continue;
1512
John McCallda4458e2010-03-31 01:36:47 +00001513 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001514
1515 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1516 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00001517 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001518 ObjectPtrConversions.push_back(Conv);
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001519 }
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001520 if (ObjectPtrConversions.size() == 1) {
1521 // We have a single conversion to a pointer-to-object type. Perform
1522 // that conversion.
John McCallda4458e2010-03-31 01:36:47 +00001523 // TODO: don't redo the conversion calculation.
John McCallda4458e2010-03-31 01:36:47 +00001524 if (!PerformImplicitConversion(Ex,
1525 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001526 AA_Converting)) {
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001527 Type = Ex->getType();
1528 }
1529 }
1530 else if (ObjectPtrConversions.size() > 1) {
1531 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1532 << Type << Ex->getSourceRange();
John McCallda4458e2010-03-31 01:36:47 +00001533 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1534 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001535 return ExprError();
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001536 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001537 }
1538
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001539 if (!Type->isPointerType())
1540 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1541 << Type << Ex->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001542
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001543 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregorbb3348e2010-05-24 17:01:56 +00001544 if (Pointee->isVoidType() && !isSFINAEContext()) {
1545 // The C++ standard bans deleting a pointer to a non-object type, which
1546 // effectively bans deletion of "void*". However, most compilers support
1547 // this, so we treat it as a warning unless we're in a SFINAE context.
1548 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1549 << Type << Ex->getSourceRange();
1550 } else if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001551 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1552 << Type << Ex->getSourceRange());
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001553 else if (!Pointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00001554 RequireCompleteType(StartLoc, Pointee,
Anders Carlssond624e162009-08-26 23:45:07 +00001555 PDiag(diag::warn_delete_incomplete)
1556 << Ex->getSourceRange()))
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001557 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001558
Douglas Gregor98496dc2009-09-29 21:38:53 +00001559 // C++ [expr.delete]p2:
1560 // [Note: a pointer to a const type can be the operand of a
1561 // delete-expression; it is not necessary to cast away the constness
1562 // (5.2.11) of the pointer expression before it is used as the operand
1563 // of the delete-expression. ]
1564 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
John McCalle3027922010-08-25 11:45:40 +00001565 CK_NoOp);
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00001566
1567 if (Pointee->isArrayType() && !ArrayForm) {
1568 Diag(StartLoc, diag::warn_delete_array_type)
1569 << Type << Ex->getSourceRange()
1570 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1571 ArrayForm = true;
1572 }
1573
Anders Carlssona471db02009-08-16 20:29:29 +00001574 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1575 ArrayForm ? OO_Array_Delete : OO_Delete);
1576
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001577 QualType PointeeElem = Context.getBaseElementType(Pointee);
1578 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001579 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1580
1581 if (!UseGlobal &&
1582 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00001583 return ExprError();
Anders Carlsson654e5c72009-11-14 03:17:38 +00001584
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001585 if (!RD->hasTrivialDestructor())
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001586 if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
Mike Stump11289f42009-09-09 15:08:12 +00001587 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001588 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001589 DiagnoseUseOfDecl(Dtor, StartLoc);
1590 }
Anders Carlssona471db02009-08-16 20:29:29 +00001591 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001592
Anders Carlssona471db02009-08-16 20:29:29 +00001593 if (!OperatorDelete) {
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001594 // Look for a global declaration.
Anders Carlssona471db02009-08-16 20:29:29 +00001595 DeclareGlobalNewDelete();
1596 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001597 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001598 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssona471db02009-08-16 20:29:29 +00001599 OperatorDelete))
1600 return ExprError();
1601 }
Mike Stump11289f42009-09-09 15:08:12 +00001602
John McCall0f55a032010-04-20 02:18:25 +00001603 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1604
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001605 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redlbd150f42008-11-21 19:14:01 +00001606 }
1607
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001608 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00001609 ArrayFormAsWritten, OperatorDelete,
1610 Ex, StartLoc));
Sebastian Redlbd150f42008-11-21 19:14:01 +00001611}
1612
Douglas Gregor633caca2009-11-23 23:44:04 +00001613/// \brief Check the use of the given variable as a C++ condition in an if,
1614/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00001615ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00001616 SourceLocation StmtLoc,
1617 bool ConvertToBoolean) {
Douglas Gregor633caca2009-11-23 23:44:04 +00001618 QualType T = ConditionVar->getType();
1619
1620 // C++ [stmt.select]p2:
1621 // The declarator shall not specify a function or an array.
1622 if (T->isFunctionType())
1623 return ExprError(Diag(ConditionVar->getLocation(),
1624 diag::err_invalid_use_of_function_type)
1625 << ConditionVar->getSourceRange());
1626 else if (T->isArrayType())
1627 return ExprError(Diag(ConditionVar->getLocation(),
1628 diag::err_invalid_use_of_array_type)
1629 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00001630
Douglas Gregore60e41a2010-05-06 17:25:47 +00001631 Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1632 ConditionVar->getLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00001633 ConditionVar->getType().getNonReferenceType(),
John McCall4bc41ae2010-11-18 19:01:18 +00001634 VK_LValue);
Douglas Gregorb412e172010-07-25 18:17:45 +00001635 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc))
Douglas Gregore60e41a2010-05-06 17:25:47 +00001636 return ExprError();
Douglas Gregore60e41a2010-05-06 17:25:47 +00001637
1638 return Owned(Condition);
Douglas Gregor633caca2009-11-23 23:44:04 +00001639}
1640
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001641/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1642bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1643 // C++ 6.4p4:
1644 // The value of a condition that is an initialized declaration in a statement
1645 // other than a switch statement is the value of the declared variable
1646 // implicitly converted to type bool. If that conversion is ill-formed, the
1647 // program is ill-formed.
1648 // The value of a condition that is an expression is the value of the
1649 // expression, implicitly converted to bool.
1650 //
Douglas Gregor5fb53972009-01-14 15:45:31 +00001651 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001652}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001653
1654/// Helper function to determine whether this is the (deprecated) C++
1655/// conversion from a string literal to a pointer to non-const char or
1656/// non-const wchar_t (for narrow and wide string literals,
1657/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00001658bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001659Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1660 // Look inside the implicit cast, if it exists.
1661 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1662 From = Cast->getSubExpr();
1663
1664 // A string literal (2.13.4) that is not a wide string literal can
1665 // be converted to an rvalue of type "pointer to char"; a wide
1666 // string literal can be converted to an rvalue of type "pointer
1667 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00001668 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001669 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001670 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00001671 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001672 // This conversion is considered only when there is an
1673 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall8ccfcb52009-09-24 19:53:00 +00001674 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001675 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1676 (!StrLit->isWide() &&
1677 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1678 ToPointeeType->getKind() == BuiltinType::Char_S))))
1679 return true;
1680 }
1681
1682 return false;
1683}
Douglas Gregor39c16d42008-10-24 04:54:22 +00001684
John McCalldadc5752010-08-24 06:29:42 +00001685static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00001686 SourceLocation CastLoc,
1687 QualType Ty,
1688 CastKind Kind,
1689 CXXMethodDecl *Method,
1690 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00001691 switch (Kind) {
1692 default: assert(0 && "Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00001693 case CK_ConstructorConversion: {
John McCall37ad5512010-08-23 06:44:23 +00001694 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregora4253922010-04-16 22:17:36 +00001695
1696 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
John McCallfaf5fb42010-08-26 23:41:50 +00001697 MultiExprArg(&From, 1),
Douglas Gregora4253922010-04-16 22:17:36 +00001698 CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00001699 return ExprError();
Douglas Gregora4253922010-04-16 22:17:36 +00001700
John McCalldadc5752010-08-24 06:29:42 +00001701 ExprResult Result =
Douglas Gregora4253922010-04-16 22:17:36 +00001702 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
John McCallbfd822c2010-08-24 07:32:53 +00001703 move_arg(ConstructorArgs),
Chandler Carruth01718152010-10-25 08:47:36 +00001704 /*ZeroInit*/ false, CXXConstructExpr::CK_Complete,
1705 SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00001706 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00001707 return ExprError();
Douglas Gregora4253922010-04-16 22:17:36 +00001708
1709 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1710 }
1711
John McCalle3027922010-08-25 11:45:40 +00001712 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00001713 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1714
1715 // Create an implicit call expr that calls it.
1716 // FIXME: pass the FoundDecl for the user-defined conversion here
1717 CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method);
1718 return S.MaybeBindToTemporary(CE);
1719 }
1720 }
1721}
1722
Douglas Gregor5fb53972009-01-14 15:45:31 +00001723/// PerformImplicitConversion - Perform an implicit conversion of the
1724/// expression From to the type ToType using the pre-computed implicit
1725/// conversion sequence ICS. Returns true if there was an error, false
1726/// otherwise. The expression From is replaced with the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001727/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001728/// used in the error message.
1729bool
1730Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1731 const ImplicitConversionSequence &ICS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001732 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall0d1da222010-01-12 00:44:57 +00001733 switch (ICS.getKind()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001734 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001735 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redl7c353682009-11-14 21:15:49 +00001736 IgnoreBaseAccess))
Douglas Gregor39c16d42008-10-24 04:54:22 +00001737 return true;
1738 break;
1739
Anders Carlsson110b07b2009-09-15 06:28:28 +00001740 case ImplicitConversionSequence::UserDefinedConversion: {
1741
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00001742 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00001743 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00001744 QualType BeforeToType;
1745 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00001746 CastKind = CK_UserDefinedConversion;
Anders Carlsson110b07b2009-09-15 06:28:28 +00001747
1748 // If the user-defined conversion is specified by a conversion function,
1749 // the initial standard conversion sequence converts the source type to
1750 // the implicit object parameter of the conversion function.
1751 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00001752 } else {
1753 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00001754 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001755 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00001756 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian55824512009-11-06 00:23:08 +00001757 // If the user-defined conversion is specified by a constructor, the
1758 // initial standard conversion sequence converts the source type to the
1759 // type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00001760 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1761 }
Anders Carlsson110b07b2009-09-15 06:28:28 +00001762 }
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00001763 // Watch out for elipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00001764 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian55824512009-11-06 00:23:08 +00001765 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001766 ICS.UserDefined.Before, AA_Converting,
Sebastian Redl7c353682009-11-14 21:15:49 +00001767 IgnoreBaseAccess))
Fariborz Jahanian55824512009-11-06 00:23:08 +00001768 return true;
1769 }
Anders Carlsson110b07b2009-09-15 06:28:28 +00001770
John McCalldadc5752010-08-24 06:29:42 +00001771 ExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00001772 = BuildCXXCastArgument(*this,
1773 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00001774 ToType.getNonReferenceType(),
1775 CastKind, cast<CXXMethodDecl>(FD),
John McCallb268a282010-08-23 23:25:46 +00001776 From);
Anders Carlssone9766d52009-09-09 21:33:21 +00001777
1778 if (CastArg.isInvalid())
1779 return true;
Eli Friedmane96f1d32009-11-27 04:41:50 +00001780
1781 From = CastArg.takeAs<Expr>();
1782
Eli Friedmane96f1d32009-11-27 04:41:50 +00001783 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001784 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00001785 }
John McCall0d1da222010-01-12 00:44:57 +00001786
1787 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00001788 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00001789 PDiag(diag::err_typecheck_ambiguous_condition)
1790 << From->getSourceRange());
1791 return true;
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00001792
Douglas Gregor39c16d42008-10-24 04:54:22 +00001793 case ImplicitConversionSequence::EllipsisConversion:
1794 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001795 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001796
1797 case ImplicitConversionSequence::BadConversion:
1798 return true;
1799 }
1800
1801 // Everything went well.
1802 return false;
1803}
1804
1805/// PerformImplicitConversion - Perform an implicit conversion of the
1806/// expression From to the type ToType by following the standard
1807/// conversion sequence SCS. Returns true if there was an error, false
1808/// otherwise. The expression From is replaced with the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00001809/// expression. Flavor is the context in which we're performing this
1810/// conversion, for use in error messages.
Mike Stump11289f42009-09-09 15:08:12 +00001811bool
Douglas Gregor39c16d42008-10-24 04:54:22 +00001812Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001813 const StandardConversionSequence& SCS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001814 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001815 // Overall FIXME: we are recomputing too many types here and doing far too
1816 // much extra work. What this means is that we need to keep track of more
1817 // information that is computed when we try the implicit conversion initially,
1818 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00001819 QualType FromType = From->getType();
1820
Douglas Gregor2fe98832008-11-03 19:09:14 +00001821 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00001822 // FIXME: When can ToType be a reference type?
1823 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00001824 if (SCS.Second == ICK_Derived_To_Base) {
John McCall37ad5512010-08-23 06:44:23 +00001825 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanian49850df2009-09-25 18:59:21 +00001826 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCall37ad5512010-08-23 06:44:23 +00001827 MultiExprArg(*this, &From, 1),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00001828 /*FIXME:ConstructLoc*/SourceLocation(),
1829 ConstructorArgs))
1830 return true;
John McCalldadc5752010-08-24 06:29:42 +00001831 ExprResult FromResult =
Fariborz Jahanian49850df2009-09-25 18:59:21 +00001832 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1833 ToType, SCS.CopyConstructor,
John McCallbfd822c2010-08-24 07:32:53 +00001834 move_arg(ConstructorArgs),
1835 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00001836 CXXConstructExpr::CK_Complete,
1837 SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00001838 if (FromResult.isInvalid())
1839 return true;
1840 From = FromResult.takeAs<Expr>();
1841 return false;
1842 }
John McCalldadc5752010-08-24 06:29:42 +00001843 ExprResult FromResult =
Mike Stump11289f42009-09-09 15:08:12 +00001844 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1845 ToType, SCS.CopyConstructor,
John McCallbfd822c2010-08-24 07:32:53 +00001846 MultiExprArg(*this, &From, 1),
1847 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00001848 CXXConstructExpr::CK_Complete,
1849 SourceRange());
Mike Stump11289f42009-09-09 15:08:12 +00001850
Anders Carlsson6eb55572009-08-25 05:12:04 +00001851 if (FromResult.isInvalid())
1852 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001853
Anders Carlsson6eb55572009-08-25 05:12:04 +00001854 From = FromResult.takeAs<Expr>();
Douglas Gregor2fe98832008-11-03 19:09:14 +00001855 return false;
1856 }
1857
Douglas Gregor980fb162010-04-29 18:24:40 +00001858 // Resolve overloaded function references.
1859 if (Context.hasSameType(FromType, Context.OverloadTy)) {
1860 DeclAccessPair Found;
1861 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1862 true, Found);
1863 if (!Fn)
1864 return true;
1865
1866 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1867 return true;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001868
Douglas Gregor980fb162010-04-29 18:24:40 +00001869 From = FixOverloadedFunctionReference(From, Found, Fn);
1870 FromType = From->getType();
1871 }
1872
Douglas Gregor39c16d42008-10-24 04:54:22 +00001873 // Perform the first implicit conversion.
1874 switch (SCS.First) {
1875 case ICK_Identity:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001876 // Nothing to do.
1877 break;
1878
John McCall34376a62010-12-04 03:47:34 +00001879 case ICK_Lvalue_To_Rvalue:
1880 // Should this get its own ICK?
1881 if (From->getObjectKind() == OK_ObjCProperty) {
1882 ConvertPropertyForRValue(From);
John McCalled75c092010-12-07 22:54:16 +00001883 if (!From->isGLValue()) break;
John McCall34376a62010-12-04 03:47:34 +00001884 }
1885
1886 FromType = FromType.getUnqualifiedType();
1887 From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
1888 From, 0, VK_RValue);
1889 break;
1890
Douglas Gregor39c16d42008-10-24 04:54:22 +00001891 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00001892 FromType = Context.getArrayDecayedType(FromType);
John McCalle3027922010-08-25 11:45:40 +00001893 ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001894 break;
1895
1896 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001897 FromType = Context.getPointerType(FromType);
John McCalle3027922010-08-25 11:45:40 +00001898 ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001899 break;
1900
1901 default:
1902 assert(false && "Improper first standard conversion");
1903 break;
1904 }
1905
1906 // Perform the second implicit conversion
1907 switch (SCS.Second) {
1908 case ICK_Identity:
Sebastian Redl5d431642009-10-10 12:04:10 +00001909 // If both sides are functions (or pointers/references to them), there could
1910 // be incompatible exception declarations.
1911 if (CheckExceptionSpecCompatibility(From, ToType))
1912 return true;
1913 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00001914 break;
1915
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001916 case ICK_NoReturn_Adjustment:
1917 // If both sides are functions (or pointers/references to them), there could
1918 // be incompatible exception declarations.
1919 if (CheckExceptionSpecCompatibility(From, ToType))
1920 return true;
1921
John McCall4f5019e2010-12-19 02:44:49 +00001922 ImpCastExprToType(From, ToType, CK_NoOp);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001923 break;
1924
Douglas Gregor39c16d42008-10-24 04:54:22 +00001925 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001926 case ICK_Integral_Conversion:
John McCalle3027922010-08-25 11:45:40 +00001927 ImpCastExprToType(From, ToType, CK_IntegralCast);
Eli Friedman06ed2a52009-10-20 08:27:19 +00001928 break;
1929
1930 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001931 case ICK_Floating_Conversion:
John McCalle3027922010-08-25 11:45:40 +00001932 ImpCastExprToType(From, ToType, CK_FloatingCast);
Eli Friedman06ed2a52009-10-20 08:27:19 +00001933 break;
1934
1935 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00001936 case ICK_Complex_Conversion: {
1937 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
1938 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
1939 CastKind CK;
1940 if (FromEl->isRealFloatingType()) {
1941 if (ToEl->isRealFloatingType())
1942 CK = CK_FloatingComplexCast;
1943 else
1944 CK = CK_FloatingComplexToIntegralComplex;
1945 } else if (ToEl->isRealFloatingType()) {
1946 CK = CK_IntegralComplexToFloatingComplex;
1947 } else {
1948 CK = CK_IntegralComplexCast;
1949 }
1950 ImpCastExprToType(From, ToType, CK);
Eli Friedman06ed2a52009-10-20 08:27:19 +00001951 break;
John McCall8cb679e2010-11-15 09:13:47 +00001952 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00001953
Douglas Gregor39c16d42008-10-24 04:54:22 +00001954 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00001955 if (ToType->isRealFloatingType())
John McCalle3027922010-08-25 11:45:40 +00001956 ImpCastExprToType(From, ToType, CK_IntegralToFloating);
Eli Friedman06ed2a52009-10-20 08:27:19 +00001957 else
John McCalle3027922010-08-25 11:45:40 +00001958 ImpCastExprToType(From, ToType, CK_FloatingToIntegral);
Eli Friedman06ed2a52009-10-20 08:27:19 +00001959 break;
1960
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001961 case ICK_Compatible_Conversion:
John McCalle3027922010-08-25 11:45:40 +00001962 ImpCastExprToType(From, ToType, CK_NoOp);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001963 break;
1964
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001965 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00001966 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001967 // Diagnose incompatible Objective-C conversions
Mike Stump11289f42009-09-09 15:08:12 +00001968 Diag(From->getSourceRange().getBegin(),
Douglas Gregor47d3f272008-12-19 17:40:08 +00001969 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001970 << From->getType() << ToType << Action
Douglas Gregor47d3f272008-12-19 17:40:08 +00001971 << From->getSourceRange();
1972 }
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001973
John McCall8cb679e2010-11-15 09:13:47 +00001974 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00001975 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00001976 if (CheckPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess))
Douglas Gregor39c16d42008-10-24 04:54:22 +00001977 return true;
John McCall2536c6d2010-08-25 10:28:54 +00001978 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001979 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001980 }
1981
1982 case ICK_Pointer_Member: {
John McCall8cb679e2010-11-15 09:13:47 +00001983 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00001984 CXXCastPath BasePath;
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001985 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath,
1986 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001987 return true;
Sebastian Redl5d431642009-10-10 12:04:10 +00001988 if (CheckExceptionSpecCompatibility(From, ToType))
1989 return true;
John McCall2536c6d2010-08-25 10:28:54 +00001990 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001991 break;
1992 }
Anders Carlsson7fa434c2009-11-23 20:04:44 +00001993 case ICK_Boolean_Conversion: {
John McCall8cb679e2010-11-15 09:13:47 +00001994 CastKind Kind = CK_Invalid;
1995 switch (FromType->getScalarTypeKind()) {
1996 case Type::STK_Pointer: Kind = CK_PointerToBoolean; break;
1997 case Type::STK_MemberPointer: Kind = CK_MemberPointerToBoolean; break;
1998 case Type::STK_Bool: llvm_unreachable("bool -> bool conversion?");
1999 case Type::STK_Integral: Kind = CK_IntegralToBoolean; break;
2000 case Type::STK_Floating: Kind = CK_FloatingToBoolean; break;
2001 case Type::STK_IntegralComplex: Kind = CK_IntegralComplexToBoolean; break;
2002 case Type::STK_FloatingComplex: Kind = CK_FloatingComplexToBoolean; break;
2003 }
Anders Carlsson7fa434c2009-11-23 20:04:44 +00002004
2005 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor39c16d42008-10-24 04:54:22 +00002006 break;
Anders Carlsson7fa434c2009-11-23 20:04:44 +00002007 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00002008
Douglas Gregor88d292c2010-05-13 16:44:06 +00002009 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00002010 CXXCastPath BasePath;
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00002011 if (CheckDerivedToBaseConversion(From->getType(),
2012 ToType.getNonReferenceType(),
2013 From->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00002014 From->getSourceRange(),
2015 &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002016 IgnoreBaseAccess))
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00002017 return true;
Douglas Gregor88d292c2010-05-13 16:44:06 +00002018
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002019 ImpCastExprToType(From, ToType.getNonReferenceType(),
John McCalle3027922010-08-25 11:45:40 +00002020 CK_DerivedToBase, CastCategory(From),
John McCallcf142162010-08-07 06:22:56 +00002021 &BasePath);
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00002022 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00002023 }
2024
Douglas Gregor46188682010-05-18 22:42:18 +00002025 case ICK_Vector_Conversion:
John McCalle3027922010-08-25 11:45:40 +00002026 ImpCastExprToType(From, ToType, CK_BitCast);
Douglas Gregor46188682010-05-18 22:42:18 +00002027 break;
2028
2029 case ICK_Vector_Splat:
John McCalle3027922010-08-25 11:45:40 +00002030 ImpCastExprToType(From, ToType, CK_VectorSplat);
Douglas Gregor46188682010-05-18 22:42:18 +00002031 break;
2032
2033 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00002034 // Case 1. x -> _Complex y
2035 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2036 QualType ElType = ToComplex->getElementType();
2037 bool isFloatingComplex = ElType->isRealFloatingType();
2038
2039 // x -> y
2040 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2041 // do nothing
2042 } else if (From->getType()->isRealFloatingType()) {
2043 ImpCastExprToType(From, ElType,
2044 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral);
2045 } else {
2046 assert(From->getType()->isIntegerType());
2047 ImpCastExprToType(From, ElType,
2048 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast);
2049 }
2050 // y -> _Complex y
2051 ImpCastExprToType(From, ToType,
2052 isFloatingComplex ? CK_FloatingRealToComplex
2053 : CK_IntegralRealToComplex);
2054
2055 // Case 2. _Complex x -> y
2056 } else {
2057 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2058 assert(FromComplex);
2059
2060 QualType ElType = FromComplex->getElementType();
2061 bool isFloatingComplex = ElType->isRealFloatingType();
2062
2063 // _Complex x -> x
2064 ImpCastExprToType(From, ElType,
2065 isFloatingComplex ? CK_FloatingComplexToReal
2066 : CK_IntegralComplexToReal);
2067
2068 // x -> y
2069 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2070 // do nothing
2071 } else if (ToType->isRealFloatingType()) {
2072 ImpCastExprToType(From, ToType,
2073 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating);
2074 } else {
2075 assert(ToType->isIntegerType());
2076 ImpCastExprToType(From, ToType,
2077 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast);
2078 }
2079 }
Douglas Gregor46188682010-05-18 22:42:18 +00002080 break;
2081
2082 case ICK_Lvalue_To_Rvalue:
2083 case ICK_Array_To_Pointer:
2084 case ICK_Function_To_Pointer:
2085 case ICK_Qualification:
2086 case ICK_Num_Conversion_Kinds:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002087 assert(false && "Improper second standard conversion");
2088 break;
2089 }
2090
2091 switch (SCS.Third) {
2092 case ICK_Identity:
2093 // Nothing to do.
2094 break;
2095
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002096 case ICK_Qualification: {
2097 // The qualification keeps the category of the inner expression, unless the
2098 // target type isn't a reference.
John McCall2536c6d2010-08-25 10:28:54 +00002099 ExprValueKind VK = ToType->isReferenceType() ?
2100 CastCategory(From) : VK_RValue;
Douglas Gregora8a089b2010-07-13 18:40:04 +00002101 ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
John McCalle3027922010-08-25 11:45:40 +00002102 CK_NoOp, VK);
Douglas Gregore489a7d2010-02-28 18:30:25 +00002103
2104 if (SCS.DeprecatedStringLiteralToCharPtr)
2105 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2106 << ToType.getNonReferenceType();
2107
Douglas Gregor39c16d42008-10-24 04:54:22 +00002108 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002109 }
2110
Douglas Gregor39c16d42008-10-24 04:54:22 +00002111 default:
Douglas Gregor46188682010-05-18 22:42:18 +00002112 assert(false && "Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00002113 break;
2114 }
2115
2116 return false;
2117}
2118
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002119ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor54e5b132010-09-09 16:14:44 +00002120 SourceLocation KWLoc,
2121 ParsedType Ty,
2122 SourceLocation RParen) {
2123 TypeSourceInfo *TSInfo;
2124 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump11289f42009-09-09 15:08:12 +00002125
Douglas Gregor54e5b132010-09-09 16:14:44 +00002126 if (!TSInfo)
2127 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002128 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor54e5b132010-09-09 16:14:44 +00002129}
2130
Sebastian Redl058fc822010-09-14 23:40:14 +00002131static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT, QualType T,
2132 SourceLocation KeyLoc) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002133 assert(!T->isDependentType() &&
2134 "Cannot evaluate traits for dependent types.");
2135 ASTContext &C = Self.Context;
2136 switch(UTT) {
2137 default: assert(false && "Unknown type trait or not implemented");
2138 case UTT_IsPOD: return T->isPODType();
2139 case UTT_IsLiteral: return T->isLiteralType();
2140 case UTT_IsClass: // Fallthrough
2141 case UTT_IsUnion:
2142 if (const RecordType *Record = T->getAs<RecordType>()) {
2143 bool Union = Record->getDecl()->isUnion();
2144 return UTT == UTT_IsUnion ? Union : !Union;
2145 }
2146 return false;
2147 case UTT_IsEnum: return T->isEnumeralType();
2148 case UTT_IsPolymorphic:
2149 if (const RecordType *Record = T->getAs<RecordType>()) {
2150 // Type traits are only parsed in C++, so we've got CXXRecords.
2151 return cast<CXXRecordDecl>(Record->getDecl())->isPolymorphic();
2152 }
2153 return false;
2154 case UTT_IsAbstract:
2155 if (const RecordType *RT = T->getAs<RecordType>())
2156 return cast<CXXRecordDecl>(RT->getDecl())->isAbstract();
2157 return false;
2158 case UTT_IsEmpty:
2159 if (const RecordType *Record = T->getAs<RecordType>()) {
2160 return !Record->getDecl()->isUnion()
2161 && cast<CXXRecordDecl>(Record->getDecl())->isEmpty();
2162 }
2163 return false;
2164 case UTT_HasTrivialConstructor:
2165 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2166 // If __is_pod (type) is true then the trait is true, else if type is
2167 // a cv class or union type (or array thereof) with a trivial default
2168 // constructor ([class.ctor]) then the trait is true, else it is false.
2169 if (T->isPODType())
2170 return true;
2171 if (const RecordType *RT =
2172 C.getBaseElementType(T)->getAs<RecordType>())
2173 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialConstructor();
2174 return false;
2175 case UTT_HasTrivialCopy:
2176 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2177 // If __is_pod (type) is true or type is a reference type then
2178 // the trait is true, else if type is a cv class or union type
2179 // with a trivial copy constructor ([class.copy]) then the trait
2180 // is true, else it is false.
2181 if (T->isPODType() || T->isReferenceType())
2182 return true;
2183 if (const RecordType *RT = T->getAs<RecordType>())
2184 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2185 return false;
2186 case UTT_HasTrivialAssign:
2187 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2188 // If type is const qualified or is a reference type then the
2189 // trait is false. Otherwise if __is_pod (type) is true then the
2190 // trait is true, else if type is a cv class or union type with
2191 // a trivial copy assignment ([class.copy]) then the trait is
2192 // true, else it is false.
2193 // Note: the const and reference restrictions are interesting,
2194 // given that const and reference members don't prevent a class
2195 // from having a trivial copy assignment operator (but do cause
2196 // errors if the copy assignment operator is actually used, q.v.
2197 // [class.copy]p12).
2198
2199 if (C.getBaseElementType(T).isConstQualified())
2200 return false;
2201 if (T->isPODType())
2202 return true;
2203 if (const RecordType *RT = T->getAs<RecordType>())
2204 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2205 return false;
2206 case UTT_HasTrivialDestructor:
2207 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2208 // If __is_pod (type) is true or type is a reference type
2209 // then the trait is true, else if type is a cv class or union
2210 // type (or array thereof) with a trivial destructor
2211 // ([class.dtor]) then the trait is true, else it is
2212 // false.
2213 if (T->isPODType() || T->isReferenceType())
2214 return true;
2215 if (const RecordType *RT =
2216 C.getBaseElementType(T)->getAs<RecordType>())
2217 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2218 return false;
2219 // TODO: Propagate nothrowness for implicitly declared special members.
2220 case UTT_HasNothrowAssign:
2221 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2222 // If type is const qualified or is a reference type then the
2223 // trait is false. Otherwise if __has_trivial_assign (type)
2224 // is true then the trait is true, else if type is a cv class
2225 // or union type with copy assignment operators that are known
2226 // not to throw an exception then the trait is true, else it is
2227 // false.
2228 if (C.getBaseElementType(T).isConstQualified())
2229 return false;
2230 if (T->isReferenceType())
2231 return false;
2232 if (T->isPODType())
2233 return true;
2234 if (const RecordType *RT = T->getAs<RecordType>()) {
2235 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2236 if (RD->hasTrivialCopyAssignment())
2237 return true;
2238
2239 bool FoundAssign = false;
2240 bool AllNoThrow = true;
2241 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redl058fc822010-09-14 23:40:14 +00002242 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2243 Sema::LookupOrdinaryName);
2244 if (Self.LookupQualifiedName(Res, RD)) {
2245 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2246 Op != OpEnd; ++Op) {
2247 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2248 if (Operator->isCopyAssignmentOperator()) {
2249 FoundAssign = true;
2250 const FunctionProtoType *CPT
2251 = Operator->getType()->getAs<FunctionProtoType>();
2252 if (!CPT->hasEmptyExceptionSpec()) {
2253 AllNoThrow = false;
2254 break;
2255 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002256 }
2257 }
2258 }
2259
2260 return FoundAssign && AllNoThrow;
2261 }
2262 return false;
2263 case UTT_HasNothrowCopy:
2264 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2265 // If __has_trivial_copy (type) is true then the trait is true, else
2266 // if type is a cv class or union type with copy constructors that are
2267 // known not to throw an exception then the trait is true, else it is
2268 // false.
2269 if (T->isPODType() || T->isReferenceType())
2270 return true;
2271 if (const RecordType *RT = T->getAs<RecordType>()) {
2272 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2273 if (RD->hasTrivialCopyConstructor())
2274 return true;
2275
2276 bool FoundConstructor = false;
2277 bool AllNoThrow = true;
2278 unsigned FoundTQs;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002279 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl951006f2010-09-13 21:10:20 +00002280 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002281 Con != ConEnd; ++Con) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00002282 // A template constructor is never a copy constructor.
2283 // FIXME: However, it may actually be selected at the actual overload
2284 // resolution point.
2285 if (isa<FunctionTemplateDecl>(*Con))
2286 continue;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002287 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2288 if (Constructor->isCopyConstructor(FoundTQs)) {
2289 FoundConstructor = true;
2290 const FunctionProtoType *CPT
2291 = Constructor->getType()->getAs<FunctionProtoType>();
Sebastian Redlc15c3262010-09-13 22:02:47 +00002292 // TODO: check whether evaluating default arguments can throw.
2293 // For now, we'll be conservative and assume that they can throw.
2294 if (!CPT->hasEmptyExceptionSpec() || CPT->getNumArgs() > 1) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002295 AllNoThrow = false;
2296 break;
2297 }
2298 }
2299 }
2300
2301 return FoundConstructor && AllNoThrow;
2302 }
2303 return false;
2304 case UTT_HasNothrowConstructor:
2305 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2306 // If __has_trivial_constructor (type) is true then the trait is
2307 // true, else if type is a cv class or union type (or array
2308 // thereof) with a default constructor that is known not to
2309 // throw an exception then the trait is true, else it is false.
2310 if (T->isPODType())
2311 return true;
2312 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
2313 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2314 if (RD->hasTrivialConstructor())
2315 return true;
2316
Sebastian Redlc15c3262010-09-13 22:02:47 +00002317 DeclContext::lookup_const_iterator Con, ConEnd;
2318 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2319 Con != ConEnd; ++Con) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00002320 // FIXME: In C++0x, a constructor template can be a default constructor.
2321 if (isa<FunctionTemplateDecl>(*Con))
2322 continue;
Sebastian Redlc15c3262010-09-13 22:02:47 +00002323 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2324 if (Constructor->isDefaultConstructor()) {
2325 const FunctionProtoType *CPT
2326 = Constructor->getType()->getAs<FunctionProtoType>();
2327 // TODO: check whether evaluating default arguments can throw.
2328 // For now, we'll be conservative and assume that they can throw.
2329 return CPT->hasEmptyExceptionSpec() && CPT->getNumArgs() == 0;
2330 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002331 }
2332 }
2333 return false;
2334 case UTT_HasVirtualDestructor:
2335 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2336 // If type is a class type with a virtual destructor ([class.dtor])
2337 // then the trait is true, else it is false.
2338 if (const RecordType *Record = T->getAs<RecordType>()) {
2339 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redl058fc822010-09-14 23:40:14 +00002340 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002341 return Destructor->isVirtual();
2342 }
2343 return false;
2344 }
2345}
2346
2347ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor54e5b132010-09-09 16:14:44 +00002348 SourceLocation KWLoc,
2349 TypeSourceInfo *TSInfo,
2350 SourceLocation RParen) {
2351 QualType T = TSInfo->getType();
2352
Anders Carlsson1f9648d2009-07-07 19:06:02 +00002353 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
2354 // all traits except __is_class, __is_enum and __is_union require a the type
Sebastian Redla190d362010-09-08 00:48:43 +00002355 // to be complete, an array of unknown bound, or void.
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002356 if (UTT != UTT_IsClass && UTT != UTT_IsEnum && UTT != UTT_IsUnion) {
Sebastian Redla190d362010-09-08 00:48:43 +00002357 QualType E = T;
2358 if (T->isIncompleteArrayType())
2359 E = Context.getAsArrayType(T)->getElementType();
2360 if (!T->isVoidType() &&
2361 RequireCompleteType(KWLoc, E,
Anders Carlsson029fc692009-08-26 22:59:12 +00002362 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson1f9648d2009-07-07 19:06:02 +00002363 return ExprError();
2364 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002365
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002366 bool Value = false;
2367 if (!T->isDependentType())
Sebastian Redl058fc822010-09-14 23:40:14 +00002368 Value = EvaluateUnaryTypeTrait(*this, UTT, T, KWLoc);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002369
2370 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson1f9648d2009-07-07 19:06:02 +00002371 RParen, Context.BoolTy));
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002372}
Sebastian Redl5822f082009-02-07 20:10:22 +00002373
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002374ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
2375 SourceLocation KWLoc,
2376 ParsedType LhsTy,
2377 ParsedType RhsTy,
2378 SourceLocation RParen) {
2379 TypeSourceInfo *LhsTSInfo;
2380 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
2381 if (!LhsTSInfo)
2382 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
2383
2384 TypeSourceInfo *RhsTSInfo;
2385 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
2386 if (!RhsTSInfo)
2387 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
2388
2389 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
2390}
2391
2392static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
2393 QualType LhsT, QualType RhsT,
2394 SourceLocation KeyLoc) {
2395 assert((!LhsT->isDependentType() || RhsT->isDependentType()) &&
2396 "Cannot evaluate traits for dependent types.");
2397
2398 switch(BTT) {
2399 case BTT_IsBaseOf:
2400 // C++0x [meta.rel]p2
2401 // Base is a base class of Derived without regard to cv-qualifiers or
2402 // Base and Derived are not unions and name the same class type without
2403 // regard to cv-qualifiers.
2404 if (Self.IsDerivedFrom(RhsT, LhsT) ||
2405 (!LhsT->isUnionType() && !RhsT->isUnionType()
2406 && LhsT->getAsCXXRecordDecl() == RhsT->getAsCXXRecordDecl()))
2407 return true;
2408
2409 return false;
Francois Pichet34b21132010-12-08 22:35:30 +00002410 case BTT_TypeCompatible:
2411 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
2412 RhsT.getUnqualifiedType());
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002413 }
2414 llvm_unreachable("Unknown type trait or not implemented");
2415}
2416
2417ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
2418 SourceLocation KWLoc,
2419 TypeSourceInfo *LhsTSInfo,
2420 TypeSourceInfo *RhsTSInfo,
2421 SourceLocation RParen) {
2422 QualType LhsT = LhsTSInfo->getType();
2423 QualType RhsT = RhsTSInfo->getType();
2424
2425 if (BTT == BTT_IsBaseOf) {
2426 // C++0x [meta.rel]p2
2427 // If Base and Derived are class types and are different types
2428 // (ignoring possible cv-qualifiers) then Derived shall be a complete
2429 // type. []
2430 CXXRecordDecl *LhsDecl = LhsT->getAsCXXRecordDecl();
2431 CXXRecordDecl *RhsDecl = RhsT->getAsCXXRecordDecl();
2432 if (!LhsT->isDependentType() && !RhsT->isDependentType() &&
2433 LhsDecl && RhsDecl && LhsT != RhsT &&
2434 RequireCompleteType(KWLoc, RhsT,
2435 diag::err_incomplete_type_used_in_type_trait_expr))
2436 return ExprError();
Francois Pichet34b21132010-12-08 22:35:30 +00002437 } else if (BTT == BTT_TypeCompatible) {
2438 if (getLangOptions().CPlusPlus) {
2439 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
2440 << SourceRange(KWLoc, RParen);
2441 return ExprError();
2442 }
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002443 }
2444
2445 bool Value = false;
2446 if (!LhsT->isDependentType() && !RhsT->isDependentType())
2447 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
2448
Francois Pichet34b21132010-12-08 22:35:30 +00002449 // Select trait result type.
2450 QualType ResultType;
2451 switch (BTT) {
2452 default: llvm_unreachable("Unknown type trait or not implemented");
2453 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
2454 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
2455 }
2456
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002457 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
2458 RhsTSInfo, Value, RParen,
Francois Pichet34b21132010-12-08 22:35:30 +00002459 ResultType));
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002460}
2461
John McCall7decc9e2010-11-18 06:31:45 +00002462QualType Sema::CheckPointerToMemberOperands(Expr *&lex, Expr *&rex,
2463 ExprValueKind &VK,
2464 SourceLocation Loc,
2465 bool isIndirect) {
Sebastian Redl5822f082009-02-07 20:10:22 +00002466 const char *OpSpelling = isIndirect ? "->*" : ".*";
2467 // C++ 5.5p2
2468 // The binary operator .* [p3: ->*] binds its second operand, which shall
2469 // be of type "pointer to member of T" (where T is a completely-defined
2470 // class type) [...]
2471 QualType RType = rex->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002472 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00002473 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00002474 Diag(Loc, diag::err_bad_memptr_rhs)
2475 << OpSpelling << RType << rex->getSourceRange();
2476 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00002477 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00002478
Sebastian Redl5822f082009-02-07 20:10:22 +00002479 QualType Class(MemPtr->getClass(), 0);
2480
Douglas Gregord07ba342010-10-13 20:41:14 +00002481 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
2482 // member pointer points must be completely-defined. However, there is no
2483 // reason for this semantic distinction, and the rule is not enforced by
2484 // other compilers. Therefore, we do not check this property, as it is
2485 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00002486
Sebastian Redl5822f082009-02-07 20:10:22 +00002487 // C++ 5.5p2
2488 // [...] to its first operand, which shall be of class T or of a class of
2489 // which T is an unambiguous and accessible base class. [p3: a pointer to
2490 // such a class]
2491 QualType LType = lex->getType();
2492 if (isIndirect) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002493 if (const PointerType *Ptr = LType->getAs<PointerType>())
John McCall7decc9e2010-11-18 06:31:45 +00002494 LType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00002495 else {
2496 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanian59f64202009-10-26 20:45:27 +00002497 << OpSpelling << 1 << LType
Douglas Gregora771f462010-03-31 17:46:05 +00002498 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00002499 return QualType();
2500 }
2501 }
2502
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002503 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00002504 // If we want to check the hierarchy, we need a complete type.
2505 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
2506 << OpSpelling << (int)isIndirect)) {
2507 return QualType();
2508 }
Anders Carlssona70cff62010-04-24 19:06:50 +00002509 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002510 /*DetectVirtual=*/false);
Mike Stump87c57ac2009-05-16 07:39:55 +00002511 // FIXME: Would it be useful to print full ambiguity paths, or is that
2512 // overkill?
Sebastian Redl5822f082009-02-07 20:10:22 +00002513 if (!IsDerivedFrom(LType, Class, Paths) ||
2514 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
2515 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman1fcf66b2010-01-16 00:00:48 +00002516 << (int)isIndirect << lex->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00002517 return QualType();
2518 }
Eli Friedman1fcf66b2010-01-16 00:00:48 +00002519 // Cast LHS to type of use.
2520 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
John McCall2536c6d2010-08-25 10:28:54 +00002521 ExprValueKind VK =
2522 isIndirect ? VK_RValue : CastCategory(lex);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002523
John McCallcf142162010-08-07 06:22:56 +00002524 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00002525 BuildBasePathArray(Paths, BasePath);
John McCall2536c6d2010-08-25 10:28:54 +00002526 ImpCastExprToType(lex, UseType, CK_DerivedToBase, VK, &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00002527 }
2528
Douglas Gregor747eb782010-07-08 06:14:04 +00002529 if (isa<CXXScalarValueInitExpr>(rex->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00002530 // Diagnose use of pointer-to-member type which when used as
2531 // the functional cast in a pointer-to-member expression.
2532 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
2533 return QualType();
2534 }
John McCall7decc9e2010-11-18 06:31:45 +00002535
Sebastian Redl5822f082009-02-07 20:10:22 +00002536 // C++ 5.5p2
2537 // The result is an object or a function of the type specified by the
2538 // second operand.
2539 // The cv qualifiers are the union of those in the pointer and the left side,
2540 // in accordance with 5.5p5 and 5.2.5.
2541 // FIXME: This returns a dereferenced member function pointer as a normal
2542 // function type. However, the only operation valid on such functions is
Mike Stump87c57ac2009-05-16 07:39:55 +00002543 // calling them. There's also a GCC extension to get a function pointer to the
2544 // thing, which is another complication, because this type - unlike the type
2545 // that is the result of this expression - takes the class as the first
Sebastian Redl5822f082009-02-07 20:10:22 +00002546 // argument.
2547 // We probably need a "MemberFunctionClosureType" or something like that.
2548 QualType Result = MemPtr->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00002549 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00002550
2551 // C++ [expr.mptr.oper]p6:
2552 // The result of a .* expression whose second operand is a pointer
2553 // to a data member is of the same value category as its
2554 // first operand. The result of a .* expression whose second
2555 // operand is a pointer to a member function is a prvalue. The
2556 // result of an ->* expression is an lvalue if its second operand
2557 // is a pointer to data member and a prvalue otherwise.
2558 if (Result->isFunctionType())
2559 VK = VK_RValue;
2560 else if (isIndirect)
2561 VK = VK_LValue;
2562 else
2563 VK = lex->getValueKind();
2564
Sebastian Redl5822f082009-02-07 20:10:22 +00002565 return Result;
2566}
Sebastian Redl1a99f442009-04-16 17:51:27 +00002567
Sebastian Redl1a99f442009-04-16 17:51:27 +00002568/// \brief Try to convert a type to another according to C++0x 5.16p3.
2569///
2570/// This is part of the parameter validation for the ? operator. If either
2571/// value operand is a class type, the two operands are attempted to be
2572/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002573/// It returns true if the program is ill-formed and has already been diagnosed
2574/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00002575static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
2576 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00002577 bool &HaveConversion,
2578 QualType &ToType) {
2579 HaveConversion = false;
2580 ToType = To->getType();
2581
2582 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
2583 SourceLocation());
Sebastian Redl1a99f442009-04-16 17:51:27 +00002584 // C++0x 5.16p3
2585 // The process for determining whether an operand expression E1 of type T1
2586 // can be converted to match an operand expression E2 of type T2 is defined
2587 // as follows:
2588 // -- If E2 is an lvalue:
John McCall086a4642010-11-24 05:12:34 +00002589 bool ToIsLvalue = To->isLValue();
Douglas Gregorf9edf802010-03-26 20:59:55 +00002590 if (ToIsLvalue) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002591 // E1 can be converted to match E2 if E1 can be implicitly converted to
2592 // type "lvalue reference to T2", subject to the constraint that in the
2593 // conversion the reference must bind directly to E1.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002594 QualType T = Self.Context.getLValueReferenceType(ToType);
2595 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2596
2597 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2598 if (InitSeq.isDirectReferenceBinding()) {
2599 ToType = T;
2600 HaveConversion = true;
2601 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00002602 }
Douglas Gregor838fcc32010-03-26 20:14:36 +00002603
2604 if (InitSeq.isAmbiguous())
2605 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002606 }
John McCall65eb8792010-02-25 01:37:24 +00002607
Sebastian Redl1a99f442009-04-16 17:51:27 +00002608 // -- If E2 is an rvalue, or if the conversion above cannot be done:
2609 // -- if E1 and E2 have class type, and the underlying class types are
2610 // the same or one is a base class of the other:
2611 QualType FTy = From->getType();
2612 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002613 const RecordType *FRec = FTy->getAs<RecordType>();
2614 const RecordType *TRec = TTy->getAs<RecordType>();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002615 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
2616 Self.IsDerivedFrom(FTy, TTy);
2617 if (FRec && TRec &&
2618 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002619 // E1 can be converted to match E2 if the class of T2 is the
2620 // same type as, or a base class of, the class of T1, and
2621 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00002622 if (FRec == TRec || FDerivedFromT) {
2623 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00002624 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2625 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2626 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2627 HaveConversion = true;
2628 return false;
2629 }
2630
2631 if (InitSeq.isAmbiguous())
2632 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2633 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00002634 }
Douglas Gregor838fcc32010-03-26 20:14:36 +00002635
2636 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00002637 }
Douglas Gregor838fcc32010-03-26 20:14:36 +00002638
2639 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2640 // implicitly converted to the type that expression E2 would have
Douglas Gregorf9edf802010-03-26 20:59:55 +00002641 // if E2 were converted to an rvalue (or the type it has, if E2 is
2642 // an rvalue).
2643 //
2644 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2645 // to the array-to-pointer or function-to-pointer conversions.
2646 if (!TTy->getAs<TagType>())
2647 TTy = TTy.getUnqualifiedType();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002648
2649 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2650 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2651 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
2652 ToType = TTy;
2653 if (InitSeq.isAmbiguous())
2654 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2655
Sebastian Redl1a99f442009-04-16 17:51:27 +00002656 return false;
2657}
2658
2659/// \brief Try to find a common type for two according to C++0x 5.16p5.
2660///
2661/// This is part of the parameter validation for the ? operator. If either
2662/// value operand is a class type, overload resolution is used to find a
2663/// conversion to a common type.
2664static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2665 SourceLocation Loc) {
2666 Expr *Args[2] = { LHS, RHS };
John McCallbc077cf2010-02-08 23:07:23 +00002667 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002668 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002669
2670 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00002671 switch (CandidateSet.BestViableFunction(Self, Loc, Best)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002672 case OR_Success:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002673 // We found a match. Perform the conversions on the arguments and move on.
2674 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002675 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00002676 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002677 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002678 break;
2679 return false;
2680
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002681 case OR_No_Viable_Function:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002682 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2683 << LHS->getType() << RHS->getType()
2684 << LHS->getSourceRange() << RHS->getSourceRange();
2685 return true;
2686
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002687 case OR_Ambiguous:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002688 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2689 << LHS->getType() << RHS->getType()
2690 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00002691 // FIXME: Print the possible common types by printing the return types of
2692 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00002693 break;
2694
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002695 case OR_Deleted:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002696 assert(false && "Conditional operator has only built-in overloads");
2697 break;
2698 }
2699 return true;
2700}
2701
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002702/// \brief Perform an "extended" implicit conversion as returned by
2703/// TryClassUnification.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002704static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2705 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2706 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2707 SourceLocation());
2708 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
John McCallfaf5fb42010-08-26 23:41:50 +00002709 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&E, 1));
Douglas Gregor838fcc32010-03-26 20:14:36 +00002710 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002711 return true;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002712
2713 E = Result.takeAs<Expr>();
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002714 return false;
2715}
2716
Sebastian Redl1a99f442009-04-16 17:51:27 +00002717/// \brief Check the operands of ?: under C++ semantics.
2718///
2719/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2720/// extension. In this case, LHS == Cond. (But they're not aliases.)
2721QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
John McCall7decc9e2010-11-18 06:31:45 +00002722 Expr *&SAVE, ExprValueKind &VK,
John McCall4bc41ae2010-11-18 19:01:18 +00002723 ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00002724 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00002725 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2726 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00002727
2728 // C++0x 5.16p1
2729 // The first expression is contextually converted to bool.
2730 if (!Cond->isTypeDependent()) {
Fariborz Jahanian2b1d88a2010-09-18 19:38:38 +00002731 if (SAVE && Cond->getType()->isArrayType()) {
2732 QualType CondTy = Cond->getType();
2733 CondTy = Context.getArrayDecayedType(CondTy);
2734 ImpCastExprToType(Cond, CondTy, CK_ArrayToPointerDecay);
2735 SAVE = LHS = Cond;
2736 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00002737 if (CheckCXXBooleanCondition(Cond))
2738 return QualType();
2739 }
2740
John McCall7decc9e2010-11-18 06:31:45 +00002741 // Assume r-value.
2742 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00002743 OK = OK_Ordinary;
John McCall7decc9e2010-11-18 06:31:45 +00002744
Sebastian Redl1a99f442009-04-16 17:51:27 +00002745 // Either of the arguments dependent?
2746 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2747 return Context.DependentTy;
2748
2749 // C++0x 5.16p2
2750 // If either the second or the third operand has type (cv) void, ...
2751 QualType LTy = LHS->getType();
2752 QualType RTy = RHS->getType();
2753 bool LVoid = LTy->isVoidType();
2754 bool RVoid = RTy->isVoidType();
2755 if (LVoid || RVoid) {
2756 // ... then the [l2r] conversions are performed on the second and third
2757 // operands ...
Douglas Gregorb92a1562010-02-03 00:27:59 +00002758 DefaultFunctionArrayLvalueConversion(LHS);
2759 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002760 LTy = LHS->getType();
2761 RTy = RHS->getType();
2762
2763 // ... and one of the following shall hold:
2764 // -- The second or the third operand (but not both) is a throw-
2765 // expression; the result is of the type of the other and is an rvalue.
2766 bool LThrow = isa<CXXThrowExpr>(LHS);
2767 bool RThrow = isa<CXXThrowExpr>(RHS);
2768 if (LThrow && !RThrow)
2769 return RTy;
2770 if (RThrow && !LThrow)
2771 return LTy;
2772
2773 // -- Both the second and third operands have type void; the result is of
2774 // type void and is an rvalue.
2775 if (LVoid && RVoid)
2776 return Context.VoidTy;
2777
2778 // Neither holds, error.
2779 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2780 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2781 << LHS->getSourceRange() << RHS->getSourceRange();
2782 return QualType();
2783 }
2784
2785 // Neither is void.
2786
2787 // C++0x 5.16p3
2788 // Otherwise, if the second and third operand have different types, and
2789 // either has (cv) class type, and attempt is made to convert each of those
2790 // operands to the other.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002791 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00002792 (LTy->isRecordType() || RTy->isRecordType())) {
2793 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2794 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002795 QualType L2RType, R2LType;
2796 bool HaveL2R, HaveR2L;
2797 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002798 return QualType();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002799 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002800 return QualType();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002801
Sebastian Redl1a99f442009-04-16 17:51:27 +00002802 // If both can be converted, [...] the program is ill-formed.
2803 if (HaveL2R && HaveR2L) {
2804 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2805 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2806 return QualType();
2807 }
2808
2809 // If exactly one conversion is possible, that conversion is applied to
2810 // the chosen operand and the converted operands are used in place of the
2811 // original operands for the remainder of this section.
2812 if (HaveL2R) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00002813 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002814 return QualType();
2815 LTy = LHS->getType();
2816 } else if (HaveR2L) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00002817 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002818 return QualType();
2819 RTy = RHS->getType();
2820 }
2821 }
2822
2823 // C++0x 5.16p4
John McCall7decc9e2010-11-18 06:31:45 +00002824 // If the second and third operands are glvalues of the same value
2825 // category and have the same type, the result is of that type and
2826 // value category and it is a bit-field if the second or the third
2827 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00002828 // We only extend this to bitfields, not to the crazy other kinds of
2829 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00002830 bool Same = Context.hasSameType(LTy, RTy);
John McCall7decc9e2010-11-18 06:31:45 +00002831 if (Same &&
2832 LHS->getValueKind() != VK_RValue &&
2833 LHS->getValueKind() == RHS->getValueKind() &&
John McCall4bc41ae2010-11-18 19:01:18 +00002834 (LHS->getObjectKind() == OK_Ordinary ||
2835 LHS->getObjectKind() == OK_BitField) &&
2836 (RHS->getObjectKind() == OK_Ordinary ||
2837 RHS->getObjectKind() == OK_BitField)) {
John McCall7decc9e2010-11-18 06:31:45 +00002838 VK = LHS->getValueKind();
John McCall4bc41ae2010-11-18 19:01:18 +00002839 if (LHS->getObjectKind() == OK_BitField ||
2840 RHS->getObjectKind() == OK_BitField)
2841 OK = OK_BitField;
John McCall7decc9e2010-11-18 06:31:45 +00002842 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00002843 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00002844
2845 // C++0x 5.16p5
2846 // Otherwise, the result is an rvalue. If the second and third operands
2847 // do not have the same type, and either has (cv) class type, ...
2848 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2849 // ... overload resolution is used to determine the conversions (if any)
2850 // to be applied to the operands. If the overload resolution fails, the
2851 // program is ill-formed.
2852 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2853 return QualType();
2854 }
2855
2856 // C++0x 5.16p6
2857 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2858 // conversions are performed on the second and third operands.
Douglas Gregorb92a1562010-02-03 00:27:59 +00002859 DefaultFunctionArrayLvalueConversion(LHS);
2860 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002861 LTy = LHS->getType();
2862 RTy = RHS->getType();
2863
2864 // After those conversions, one of the following shall hold:
2865 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00002866 // is of that type. If the operands have class type, the result
2867 // is a prvalue temporary of the result type, which is
2868 // copy-initialized from either the second operand or the third
2869 // operand depending on the value of the first operand.
2870 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
2871 if (LTy->isRecordType()) {
2872 // The operands have class type. Make a temporary copy.
2873 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
John McCalldadc5752010-08-24 06:29:42 +00002874 ExprResult LHSCopy = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00002875 SourceLocation(),
2876 Owned(LHS));
Douglas Gregorfa6010b2010-05-19 23:40:50 +00002877 if (LHSCopy.isInvalid())
2878 return QualType();
2879
John McCalldadc5752010-08-24 06:29:42 +00002880 ExprResult RHSCopy = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00002881 SourceLocation(),
2882 Owned(RHS));
Douglas Gregorfa6010b2010-05-19 23:40:50 +00002883 if (RHSCopy.isInvalid())
2884 return QualType();
2885
2886 LHS = LHSCopy.takeAs<Expr>();
2887 RHS = RHSCopy.takeAs<Expr>();
2888 }
2889
Sebastian Redl1a99f442009-04-16 17:51:27 +00002890 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00002891 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00002892
Douglas Gregor46188682010-05-18 22:42:18 +00002893 // Extension: conditional operator involving vector types.
2894 if (LTy->isVectorType() || RTy->isVectorType())
2895 return CheckVectorOperands(QuestionLoc, LHS, RHS);
2896
Sebastian Redl1a99f442009-04-16 17:51:27 +00002897 // -- The second and third operands have arithmetic or enumeration type;
2898 // the usual arithmetic conversions are performed to bring them to a
2899 // common type, and the result is of that type.
2900 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2901 UsualArithmeticConversions(LHS, RHS);
2902 return LHS->getType();
2903 }
2904
2905 // -- The second and third operands have pointer type, or one has pointer
2906 // type and the other is a null pointer constant; pointer conversions
2907 // and qualification conversions are performed to bring them to their
2908 // composite pointer type. The result is of the composite pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00002909 // -- The second and third operands have pointer to member type, or one has
2910 // pointer to member type and the other is a null pointer constant;
2911 // pointer to member conversions and qualification conversions are
2912 // performed to bring them to a common type, whose cv-qualification
2913 // shall match the cv-qualification of either the second or the third
2914 // operand. The result is of the common type.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002915 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00002916 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002917 isSFINAEContext()? 0 : &NonStandardCompositeType);
2918 if (!Composite.isNull()) {
2919 if (NonStandardCompositeType)
2920 Diag(QuestionLoc,
2921 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2922 << LTy << RTy << Composite
2923 << LHS->getSourceRange() << RHS->getSourceRange();
2924
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002925 return Composite;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002926 }
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00002927
Douglas Gregor697a3912010-04-01 22:47:07 +00002928 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00002929 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2930 if (!Composite.isNull())
2931 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00002932
Sebastian Redl1a99f442009-04-16 17:51:27 +00002933 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2934 << LHS->getType() << RHS->getType()
2935 << LHS->getSourceRange() << RHS->getSourceRange();
2936 return QualType();
2937}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002938
2939/// \brief Find a merged pointer type and convert the two expressions to it.
2940///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002941/// This finds the composite pointer type (or member pointer type) for @p E1
2942/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2943/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002944/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002945///
Douglas Gregor19175ff2010-04-16 23:20:25 +00002946/// \param Loc The location of the operator requiring these two expressions to
2947/// be converted to the composite pointer type.
2948///
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002949/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2950/// a non-standard (but still sane) composite type to which both expressions
2951/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2952/// will be set true.
Douglas Gregor19175ff2010-04-16 23:20:25 +00002953QualType Sema::FindCompositePointerType(SourceLocation Loc,
2954 Expr *&E1, Expr *&E2,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002955 bool *NonStandardCompositeType) {
2956 if (NonStandardCompositeType)
2957 *NonStandardCompositeType = false;
2958
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002959 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2960 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002961
Fariborz Jahanian33e148f2009-12-08 20:04:24 +00002962 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2963 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002964 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002965
2966 // C++0x 5.9p2
2967 // Pointer conversions and qualification conversions are performed on
2968 // pointer operands to bring them to their composite pointer type. If
2969 // one operand is a null pointer constant, the composite pointer type is
2970 // the type of the other operand.
Douglas Gregor56751b52009-09-25 04:25:58 +00002971 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002972 if (T2->isMemberPointerType())
John McCalle3027922010-08-25 11:45:40 +00002973 ImpCastExprToType(E1, T2, CK_NullToMemberPointer);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002974 else
John McCalle84af4e2010-11-13 01:35:44 +00002975 ImpCastExprToType(E1, T2, CK_NullToPointer);
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002976 return T2;
2977 }
Douglas Gregor56751b52009-09-25 04:25:58 +00002978 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002979 if (T1->isMemberPointerType())
John McCalle3027922010-08-25 11:45:40 +00002980 ImpCastExprToType(E2, T1, CK_NullToMemberPointer);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002981 else
John McCalle84af4e2010-11-13 01:35:44 +00002982 ImpCastExprToType(E2, T1, CK_NullToPointer);
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002983 return T1;
2984 }
Mike Stump11289f42009-09-09 15:08:12 +00002985
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002986 // Now both have to be pointers or member pointers.
Sebastian Redl658262f2009-11-16 21:03:45 +00002987 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2988 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002989 return QualType();
2990
2991 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2992 // the other has type "pointer to cv2 T" and the composite pointer type is
2993 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2994 // Otherwise, the composite pointer type is a pointer type similar to the
2995 // type of one of the operands, with a cv-qualification signature that is
2996 // the union of the cv-qualification signatures of the operand types.
2997 // In practice, the first part here is redundant; it's subsumed by the second.
2998 // What we do here is, we build the two possible composite types, and try the
2999 // conversions in both directions. If only one works, or if the two composite
3000 // types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00003001 // FIXME: extended qualifiers?
Sebastian Redl658262f2009-11-16 21:03:45 +00003002 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
3003 QualifierVector QualifierUnion;
3004 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
3005 ContainingClassVector;
3006 ContainingClassVector MemberOfClass;
3007 QualType Composite1 = Context.getCanonicalType(T1),
3008 Composite2 = Context.getCanonicalType(T2);
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003009 unsigned NeedConstBefore = 0;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003010 do {
3011 const PointerType *Ptr1, *Ptr2;
3012 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3013 (Ptr2 = Composite2->getAs<PointerType>())) {
3014 Composite1 = Ptr1->getPointeeType();
3015 Composite2 = Ptr2->getPointeeType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003016
3017 // If we're allowed to create a non-standard composite type, keep track
3018 // of where we need to fill in additional 'const' qualifiers.
3019 if (NonStandardCompositeType &&
3020 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3021 NeedConstBefore = QualifierUnion.size();
3022
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003023 QualifierUnion.push_back(
3024 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3025 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3026 continue;
3027 }
Mike Stump11289f42009-09-09 15:08:12 +00003028
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003029 const MemberPointerType *MemPtr1, *MemPtr2;
3030 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3031 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3032 Composite1 = MemPtr1->getPointeeType();
3033 Composite2 = MemPtr2->getPointeeType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003034
3035 // If we're allowed to create a non-standard composite type, keep track
3036 // of where we need to fill in additional 'const' qualifiers.
3037 if (NonStandardCompositeType &&
3038 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3039 NeedConstBefore = QualifierUnion.size();
3040
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003041 QualifierUnion.push_back(
3042 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3043 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
3044 MemPtr2->getClass()));
3045 continue;
3046 }
Mike Stump11289f42009-09-09 15:08:12 +00003047
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003048 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00003049
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003050 // Cannot unwrap any more types.
3051 break;
3052 } while (true);
Mike Stump11289f42009-09-09 15:08:12 +00003053
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003054 if (NeedConstBefore && NonStandardCompositeType) {
3055 // Extension: Add 'const' to qualifiers that come before the first qualifier
3056 // mismatch, so that our (non-standard!) composite type meets the
3057 // requirements of C++ [conv.qual]p4 bullet 3.
3058 for (unsigned I = 0; I != NeedConstBefore; ++I) {
3059 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
3060 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
3061 *NonStandardCompositeType = true;
3062 }
3063 }
3064 }
3065
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003066 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redl658262f2009-11-16 21:03:45 +00003067 ContainingClassVector::reverse_iterator MOC
3068 = MemberOfClass.rbegin();
3069 for (QualifierVector::reverse_iterator
3070 I = QualifierUnion.rbegin(),
3071 E = QualifierUnion.rend();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003072 I != E; (void)++I, ++MOC) {
John McCall8ccfcb52009-09-24 19:53:00 +00003073 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003074 if (MOC->first && MOC->second) {
3075 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00003076 Composite1 = Context.getMemberPointerType(
3077 Context.getQualifiedType(Composite1, Quals),
3078 MOC->first);
3079 Composite2 = Context.getMemberPointerType(
3080 Context.getQualifiedType(Composite2, Quals),
3081 MOC->second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003082 } else {
3083 // Rebuild pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00003084 Composite1
3085 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
3086 Composite2
3087 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003088 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003089 }
3090
Douglas Gregor19175ff2010-04-16 23:20:25 +00003091 // Try to convert to the first composite pointer type.
3092 InitializedEntity Entity1
3093 = InitializedEntity::InitializeTemporary(Composite1);
3094 InitializationKind Kind
3095 = InitializationKind::CreateCopy(Loc, SourceLocation());
3096 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
3097 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump11289f42009-09-09 15:08:12 +00003098
Douglas Gregor19175ff2010-04-16 23:20:25 +00003099 if (E1ToC1 && E2ToC1) {
3100 // Conversion to Composite1 is viable.
3101 if (!Context.hasSameType(Composite1, Composite2)) {
3102 // Composite2 is a different type from Composite1. Check whether
3103 // Composite2 is also viable.
3104 InitializedEntity Entity2
3105 = InitializedEntity::InitializeTemporary(Composite2);
3106 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3107 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3108 if (E1ToC2 && E2ToC2) {
3109 // Both Composite1 and Composite2 are viable and are different;
3110 // this is an ambiguity.
3111 return QualType();
3112 }
3113 }
3114
3115 // Convert E1 to Composite1
John McCalldadc5752010-08-24 06:29:42 +00003116 ExprResult E1Result
John McCall37ad5512010-08-23 06:44:23 +00003117 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00003118 if (E1Result.isInvalid())
3119 return QualType();
3120 E1 = E1Result.takeAs<Expr>();
3121
3122 // Convert E2 to Composite1
John McCalldadc5752010-08-24 06:29:42 +00003123 ExprResult E2Result
John McCall37ad5512010-08-23 06:44:23 +00003124 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00003125 if (E2Result.isInvalid())
3126 return QualType();
3127 E2 = E2Result.takeAs<Expr>();
3128
3129 return Composite1;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003130 }
3131
Douglas Gregor19175ff2010-04-16 23:20:25 +00003132 // Check whether Composite2 is viable.
3133 InitializedEntity Entity2
3134 = InitializedEntity::InitializeTemporary(Composite2);
3135 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3136 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3137 if (!E1ToC2 || !E2ToC2)
3138 return QualType();
3139
3140 // Convert E1 to Composite2
John McCalldadc5752010-08-24 06:29:42 +00003141 ExprResult E1Result
John McCall37ad5512010-08-23 06:44:23 +00003142 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00003143 if (E1Result.isInvalid())
3144 return QualType();
3145 E1 = E1Result.takeAs<Expr>();
3146
3147 // Convert E2 to Composite2
John McCalldadc5752010-08-24 06:29:42 +00003148 ExprResult E2Result
John McCall37ad5512010-08-23 06:44:23 +00003149 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00003150 if (E2Result.isInvalid())
3151 return QualType();
3152 E2 = E2Result.takeAs<Expr>();
3153
3154 return Composite2;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003155}
Anders Carlsson85a307d2009-05-17 18:41:29 +00003156
John McCalldadc5752010-08-24 06:29:42 +00003157ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00003158 if (!E)
3159 return ExprError();
3160
Anders Carlssonf86a8d12009-08-15 23:41:35 +00003161 if (!Context.getLangOptions().CPlusPlus)
3162 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00003163
Douglas Gregor363b1512009-12-24 18:51:59 +00003164 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
3165
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003166 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlsson2d4cada2009-05-30 20:36:53 +00003167 if (!RT)
3168 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00003169
Anders Carlssonbb4cfdf2010-07-16 21:18:37 +00003170 // If this is the result of a call or an Objective-C message send expression,
3171 // our source might actually be a reference, in which case we shouldn't bind.
Anders Carlssonaedb46f2009-09-14 01:30:44 +00003172 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
Anders Carlssonbb4cfdf2010-07-16 21:18:37 +00003173 if (CE->getCallReturnType()->isReferenceType())
Anders Carlssonaedb46f2009-09-14 01:30:44 +00003174 return Owned(E);
Anders Carlssonbb4cfdf2010-07-16 21:18:37 +00003175 } else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
3176 if (const ObjCMethodDecl *MD = ME->getMethodDecl()) {
3177 if (MD->getResultType()->isReferenceType())
3178 return Owned(E);
3179 }
Anders Carlssonaedb46f2009-09-14 01:30:44 +00003180 }
John McCall67da35c2010-02-04 22:26:26 +00003181
3182 // That should be enough to guarantee that this type is complete.
3183 // If it has a trivial destructor, we can avoid the extra copy.
3184 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCallbdb989e2010-08-12 02:40:37 +00003185 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall67da35c2010-02-04 22:26:26 +00003186 return Owned(E);
3187
Douglas Gregore71edda2010-07-01 22:47:18 +00003188 CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD));
Anders Carlssonc78576e2009-05-30 21:21:49 +00003189 ExprTemporaries.push_back(Temp);
Douglas Gregore71edda2010-07-01 22:47:18 +00003190 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Fariborz Jahanian67828442009-08-03 19:13:25 +00003191 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00003192 CheckDestructorAccess(E->getExprLoc(), Destructor,
3193 PDiag(diag::err_access_dtor_temp)
3194 << E->getType());
3195 }
Anders Carlsson2d4cada2009-05-30 20:36:53 +00003196 // FIXME: Add the temporary to the temporaries vector.
3197 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
3198}
3199
John McCall5d413782010-12-06 08:20:24 +00003200Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Anders Carlssonb3d05d62009-06-05 15:38:08 +00003201 assert(SubExpr && "sub expression can't be null!");
Mike Stump11289f42009-09-09 15:08:12 +00003202
Douglas Gregor580cd4a2009-12-03 17:10:37 +00003203 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3204 assert(ExprTemporaries.size() >= FirstTemporary);
3205 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlssonb3d05d62009-06-05 15:38:08 +00003206 return SubExpr;
Mike Stump11289f42009-09-09 15:08:12 +00003207
John McCall5d413782010-12-06 08:20:24 +00003208 Expr *E = ExprWithCleanups::Create(Context, SubExpr,
3209 &ExprTemporaries[FirstTemporary],
3210 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor580cd4a2009-12-03 17:10:37 +00003211 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
3212 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00003213
Anders Carlssonb3d05d62009-06-05 15:38:08 +00003214 return E;
3215}
3216
John McCalldadc5752010-08-24 06:29:42 +00003217ExprResult
John McCall5d413782010-12-06 08:20:24 +00003218Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00003219 if (SubExpr.isInvalid())
3220 return ExprError();
3221
John McCall5d413782010-12-06 08:20:24 +00003222 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00003223}
3224
John McCall5d413782010-12-06 08:20:24 +00003225Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00003226 assert(SubStmt && "sub statement can't be null!");
3227
3228 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3229 assert(ExprTemporaries.size() >= FirstTemporary);
3230 if (ExprTemporaries.size() == FirstTemporary)
3231 return SubStmt;
3232
3233 // FIXME: In order to attach the temporaries, wrap the statement into
3234 // a StmtExpr; currently this is only used for asm statements.
3235 // This is hacky, either create a new CXXStmtWithTemporaries statement or
3236 // a new AsmStmtWithTemporaries.
3237 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
3238 SourceLocation(),
3239 SourceLocation());
3240 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
3241 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00003242 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00003243}
3244
John McCalldadc5752010-08-24 06:29:42 +00003245ExprResult
John McCallb268a282010-08-23 23:25:46 +00003246Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallba7bf592010-08-24 05:47:05 +00003247 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregore610ada2010-02-24 18:44:31 +00003248 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003249 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003250 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003251 if (Result.isInvalid()) return ExprError();
3252 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00003253
John McCallb268a282010-08-23 23:25:46 +00003254 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00003255 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003256 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00003257 // If we have a pointer to a dependent type and are using the -> operator,
3258 // the object type is the type that the pointer points to. We might still
3259 // have enough information about that type to do something useful.
3260 if (OpKind == tok::arrow)
3261 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3262 BaseType = Ptr->getPointeeType();
3263
John McCallba7bf592010-08-24 05:47:05 +00003264 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00003265 MayBePseudoDestructor = true;
John McCallb268a282010-08-23 23:25:46 +00003266 return Owned(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003267 }
Mike Stump11289f42009-09-09 15:08:12 +00003268
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003269 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00003270 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003271 // returned, with the original second operand.
3272 if (OpKind == tok::arrow) {
John McCallc1538c02009-09-30 01:01:30 +00003273 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00003274 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00003275 llvm::SmallVector<SourceLocation, 8> Locations;
John McCallbd0465b2009-09-30 01:30:54 +00003276 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc1538c02009-09-30 01:01:30 +00003277
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003278 while (BaseType->isRecordType()) {
John McCallb268a282010-08-23 23:25:46 +00003279 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
3280 if (Result.isInvalid())
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003281 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00003282 Base = Result.get();
3283 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonfbd2d492009-10-13 22:55:59 +00003284 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallb268a282010-08-23 23:25:46 +00003285 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00003286 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCallbd0465b2009-09-30 01:30:54 +00003287 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00003288 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00003289 for (unsigned i = 0; i < Locations.size(); i++)
3290 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00003291 return ExprError();
3292 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003293 }
Mike Stump11289f42009-09-09 15:08:12 +00003294
Douglas Gregore4f764f2009-11-20 19:58:21 +00003295 if (BaseType->isPointerType())
3296 BaseType = BaseType->getPointeeType();
3297 }
Mike Stump11289f42009-09-09 15:08:12 +00003298
3299 // We could end up with various non-record types here, such as extended
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003300 // vector types or Objective-C interfaces. Just return early and let
3301 // ActOnMemberReferenceExpr do the work.
Douglas Gregor2b6ca462009-09-03 21:38:09 +00003302 if (!BaseType->isRecordType()) {
3303 // C++ [basic.lookup.classref]p2:
3304 // [...] If the type of the object expression is of pointer to scalar
3305 // type, the unqualified-id is looked up in the context of the complete
3306 // postfix-expression.
Douglas Gregore610ada2010-02-24 18:44:31 +00003307 //
3308 // This also indicates that we should be parsing a
3309 // pseudo-destructor-name.
John McCallba7bf592010-08-24 05:47:05 +00003310 ObjectType = ParsedType();
Douglas Gregore610ada2010-02-24 18:44:31 +00003311 MayBePseudoDestructor = true;
John McCallb268a282010-08-23 23:25:46 +00003312 return Owned(Base);
Douglas Gregor2b6ca462009-09-03 21:38:09 +00003313 }
Mike Stump11289f42009-09-09 15:08:12 +00003314
Douglas Gregor3fad6172009-11-17 05:17:33 +00003315 // The object type must be complete (or dependent).
3316 if (!BaseType->isDependentType() &&
3317 RequireCompleteType(OpLoc, BaseType,
3318 PDiag(diag::err_incomplete_member_access)))
3319 return ExprError();
3320
Douglas Gregor2b6ca462009-09-03 21:38:09 +00003321 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00003322 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00003323 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00003324 // type C (or of pointer to a class type C), the unqualified-id is looked
3325 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00003326 ObjectType = ParsedType::make(BaseType);
Mike Stump11289f42009-09-09 15:08:12 +00003327 return move(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003328}
3329
John McCalldadc5752010-08-24 06:29:42 +00003330ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCallb268a282010-08-23 23:25:46 +00003331 Expr *MemExpr) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003332 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCallb268a282010-08-23 23:25:46 +00003333 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
3334 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregora771f462010-03-31 17:46:05 +00003335 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003336
3337 return ActOnCallExpr(/*Scope*/ 0,
John McCallb268a282010-08-23 23:25:46 +00003338 MemExpr,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003339 /*LPLoc*/ ExpectedLParenLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00003340 MultiExprArg(),
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003341 /*RPLoc*/ ExpectedLParenLoc);
3342}
Douglas Gregore610ada2010-02-24 18:44:31 +00003343
John McCalldadc5752010-08-24 06:29:42 +00003344ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003345 SourceLocation OpLoc,
3346 tok::TokenKind OpKind,
3347 const CXXScopeSpec &SS,
Douglas Gregor651fe5e2010-02-24 23:40:28 +00003348 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003349 SourceLocation CCLoc,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00003350 SourceLocation TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00003351 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003352 bool HasTrailingLParen) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00003353 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003354
3355 // C++ [expr.pseudo]p2:
3356 // The left-hand side of the dot operator shall be of scalar type. The
3357 // left-hand side of the arrow operator shall be of pointer to scalar type.
3358 // This scalar type is the object type.
John McCallb268a282010-08-23 23:25:46 +00003359 QualType ObjectType = Base->getType();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003360 if (OpKind == tok::arrow) {
3361 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3362 ObjectType = Ptr->getPointeeType();
John McCallb268a282010-08-23 23:25:46 +00003363 } else if (!Base->isTypeDependent()) {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003364 // The user wrote "p->" when she probably meant "p."; fix it.
3365 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3366 << ObjectType << true
Douglas Gregora771f462010-03-31 17:46:05 +00003367 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003368 if (isSFINAEContext())
3369 return ExprError();
3370
3371 OpKind = tok::period;
3372 }
3373 }
3374
3375 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
3376 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
John McCallb268a282010-08-23 23:25:46 +00003377 << ObjectType << Base->getSourceRange();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003378 return ExprError();
3379 }
3380
3381 // C++ [expr.pseudo]p2:
3382 // [...] The cv-unqualified versions of the object type and of the type
3383 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00003384 if (DestructedTypeInfo) {
3385 QualType DestructedType = DestructedTypeInfo->getType();
3386 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00003387 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
Douglas Gregor678f90d2010-02-25 01:56:36 +00003388 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
3389 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
3390 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00003391 << ObjectType << DestructedType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00003392 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor678f90d2010-02-25 01:56:36 +00003393
3394 // Recover by setting the destructed type to the object type.
3395 DestructedType = ObjectType;
3396 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
3397 DestructedTypeStart);
3398 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3399 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003400 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00003401
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003402 // C++ [expr.pseudo]p2:
3403 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
3404 // form
3405 //
3406 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
3407 //
3408 // shall designate the same scalar type.
3409 if (ScopeTypeInfo) {
3410 QualType ScopeType = ScopeTypeInfo->getType();
3411 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00003412 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003413
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00003414 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003415 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00003416 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00003417 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003418
3419 ScopeType = QualType();
3420 ScopeTypeInfo = 0;
3421 }
3422 }
3423
John McCallb268a282010-08-23 23:25:46 +00003424 Expr *Result
3425 = new (Context) CXXPseudoDestructorExpr(Context, Base,
3426 OpKind == tok::arrow, OpLoc,
3427 SS.getScopeRep(), SS.getRange(),
3428 ScopeTypeInfo,
3429 CCLoc,
3430 TildeLoc,
3431 Destructed);
Douglas Gregor678f90d2010-02-25 01:56:36 +00003432
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003433 if (HasTrailingLParen)
John McCallb268a282010-08-23 23:25:46 +00003434 return Owned(Result);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003435
John McCallb268a282010-08-23 23:25:46 +00003436 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003437}
3438
John McCalldadc5752010-08-24 06:29:42 +00003439ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003440 SourceLocation OpLoc,
3441 tok::TokenKind OpKind,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003442 CXXScopeSpec &SS,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003443 UnqualifiedId &FirstTypeName,
3444 SourceLocation CCLoc,
3445 SourceLocation TildeLoc,
3446 UnqualifiedId &SecondTypeName,
3447 bool HasTrailingLParen) {
3448 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3449 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3450 "Invalid first type name in pseudo-destructor");
3451 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3452 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3453 "Invalid second type name in pseudo-destructor");
3454
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003455 // C++ [expr.pseudo]p2:
3456 // The left-hand side of the dot operator shall be of scalar type. The
3457 // left-hand side of the arrow operator shall be of pointer to scalar type.
3458 // This scalar type is the object type.
John McCallb268a282010-08-23 23:25:46 +00003459 QualType ObjectType = Base->getType();
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003460 if (OpKind == tok::arrow) {
3461 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3462 ObjectType = Ptr->getPointeeType();
Douglas Gregor678f90d2010-02-25 01:56:36 +00003463 } else if (!ObjectType->isDependentType()) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003464 // The user wrote "p->" when she probably meant "p."; fix it.
3465 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregor678f90d2010-02-25 01:56:36 +00003466 << ObjectType << true
Douglas Gregora771f462010-03-31 17:46:05 +00003467 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003468 if (isSFINAEContext())
3469 return ExprError();
3470
3471 OpKind = tok::period;
3472 }
3473 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00003474
3475 // Compute the object type that we should use for name lookup purposes. Only
3476 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00003477 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00003478 if (!SS.isSet()) {
John McCallba7bf592010-08-24 05:47:05 +00003479 if (const Type *T = ObjectType->getAs<RecordType>())
3480 ObjectTypePtrForLookup = ParsedType::make(QualType(T, 0));
3481 else if (ObjectType->isDependentType())
3482 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00003483 }
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003484
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003485 // Convert the name of the type being destructed (following the ~) into a
3486 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003487 QualType DestructedType;
3488 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregor678f90d2010-02-25 01:56:36 +00003489 PseudoDestructorTypeStorage Destructed;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003490 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
John McCallba7bf592010-08-24 05:47:05 +00003491 ParsedType T = getTypeName(*SecondTypeName.Identifier,
3492 SecondTypeName.StartLocation,
3493 S, &SS, true, ObjectTypePtrForLookup);
Douglas Gregor678f90d2010-02-25 01:56:36 +00003494 if (!T &&
3495 ((SS.isSet() && !computeDeclContext(SS, false)) ||
3496 (!SS.isSet() && ObjectType->isDependentType()))) {
3497 // The name of the type being destroyed is a dependent name, and we
3498 // couldn't find anything useful in scope. Just store the identifier and
3499 // it's location, and we'll perform (qualified) name lookup again at
3500 // template instantiation time.
3501 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
3502 SecondTypeName.StartLocation);
3503 } else if (!T) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003504 Diag(SecondTypeName.StartLocation,
3505 diag::err_pseudo_dtor_destructor_non_type)
3506 << SecondTypeName.Identifier << ObjectType;
3507 if (isSFINAEContext())
3508 return ExprError();
3509
3510 // Recover by assuming we had the right type all along.
3511 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003512 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003513 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003514 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003515 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003516 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003517 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3518 TemplateId->getTemplateArgs(),
3519 TemplateId->NumArgs);
John McCall3e56fd42010-08-23 07:28:44 +00003520 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003521 TemplateId->TemplateNameLoc,
3522 TemplateId->LAngleLoc,
3523 TemplateArgsPtr,
3524 TemplateId->RAngleLoc);
3525 if (T.isInvalid() || !T.get()) {
3526 // Recover by assuming we had the right type all along.
3527 DestructedType = ObjectType;
3528 } else
3529 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003530 }
3531
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003532 // If we've performed some kind of recovery, (re-)build the type source
3533 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00003534 if (!DestructedType.isNull()) {
3535 if (!DestructedTypeInfo)
3536 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003537 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00003538 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3539 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003540
3541 // Convert the name of the scope type (the type prior to '::') into a type.
3542 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003543 QualType ScopeType;
3544 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3545 FirstTypeName.Identifier) {
3546 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
John McCallba7bf592010-08-24 05:47:05 +00003547 ParsedType T = getTypeName(*FirstTypeName.Identifier,
3548 FirstTypeName.StartLocation,
3549 S, &SS, false, ObjectTypePtrForLookup);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003550 if (!T) {
3551 Diag(FirstTypeName.StartLocation,
3552 diag::err_pseudo_dtor_destructor_non_type)
3553 << FirstTypeName.Identifier << ObjectType;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003554
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003555 if (isSFINAEContext())
3556 return ExprError();
3557
3558 // Just drop this type. It's unnecessary anyway.
3559 ScopeType = QualType();
3560 } else
3561 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003562 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003563 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003564 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003565 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3566 TemplateId->getTemplateArgs(),
3567 TemplateId->NumArgs);
John McCall3e56fd42010-08-23 07:28:44 +00003568 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003569 TemplateId->TemplateNameLoc,
3570 TemplateId->LAngleLoc,
3571 TemplateArgsPtr,
3572 TemplateId->RAngleLoc);
3573 if (T.isInvalid() || !T.get()) {
3574 // Recover by dropping this type.
3575 ScopeType = QualType();
3576 } else
3577 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003578 }
3579 }
Douglas Gregor90ad9222010-02-24 23:02:30 +00003580
3581 if (!ScopeType.isNull() && !ScopeTypeInfo)
3582 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
3583 FirstTypeName.StartLocation);
3584
3585
John McCallb268a282010-08-23 23:25:46 +00003586 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00003587 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00003588 Destructed, HasTrailingLParen);
Douglas Gregore610ada2010-02-24 18:44:31 +00003589}
3590
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00003591CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
John McCall16df1e52010-03-30 21:47:33 +00003592 NamedDecl *FoundDecl,
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00003593 CXXMethodDecl *Method) {
John McCall16df1e52010-03-30 21:47:33 +00003594 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
3595 FoundDecl, Method))
Eli Friedmanf7195532009-12-09 04:53:56 +00003596 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
3597
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00003598 MemberExpr *ME =
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003599 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
John McCall7decc9e2010-11-18 06:31:45 +00003600 SourceLocation(), Method->getType(),
3601 VK_RValue, OK_Ordinary);
3602 QualType ResultType = Method->getResultType();
3603 ExprValueKind VK = Expr::getValueKindForType(ResultType);
3604 ResultType = ResultType.getNonLValueExprType(Context);
3605
Douglas Gregor27381f32009-11-23 12:27:39 +00003606 MarkDeclarationReferenced(Exp->getLocStart(), Method);
3607 CXXMemberCallExpr *CE =
John McCall7decc9e2010-11-18 06:31:45 +00003608 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
Douglas Gregor27381f32009-11-23 12:27:39 +00003609 Exp->getLocEnd());
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00003610 return CE;
3611}
3612
Sebastian Redl4202c0f2010-09-10 20:55:43 +00003613ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
3614 SourceLocation RParen) {
Sebastian Redl4202c0f2010-09-10 20:55:43 +00003615 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
3616 Operand->CanThrow(Context),
3617 KeyLoc, RParen));
3618}
3619
3620ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
3621 Expr *Operand, SourceLocation RParen) {
3622 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00003623}
3624
John McCall34376a62010-12-04 03:47:34 +00003625/// Perform the conversions required for an expression used in a
3626/// context that ignores the result.
3627void Sema::IgnoredValueConversions(Expr *&E) {
John McCallfee942d2010-12-02 02:07:15 +00003628 // C99 6.3.2.1:
3629 // [Except in specific positions,] an lvalue that does not have
3630 // array type is converted to the value stored in the
3631 // designated object (and is no longer an lvalue).
John McCall34376a62010-12-04 03:47:34 +00003632 if (E->isRValue()) return;
John McCallfee942d2010-12-02 02:07:15 +00003633
John McCall34376a62010-12-04 03:47:34 +00003634 // We always want to do this on ObjC property references.
3635 if (E->getObjectKind() == OK_ObjCProperty) {
3636 ConvertPropertyForRValue(E);
3637 if (E->isRValue()) return;
3638 }
3639
3640 // Otherwise, this rule does not apply in C++, at least not for the moment.
3641 if (getLangOptions().CPlusPlus) return;
3642
3643 // GCC seems to also exclude expressions of incomplete enum type.
3644 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
3645 if (!T->getDecl()->isComplete()) {
3646 // FIXME: stupid workaround for a codegen bug!
3647 ImpCastExprToType(E, Context.VoidTy, CK_ToVoid);
3648 return;
3649 }
3650 }
3651
3652 DefaultFunctionArrayLvalueConversion(E);
John McCallca61b652010-12-04 12:29:11 +00003653 if (!E->getType()->isVoidType())
3654 RequireCompleteType(E->getExprLoc(), E->getType(),
3655 diag::err_incomplete_type);
John McCall34376a62010-12-04 03:47:34 +00003656}
3657
3658ExprResult Sema::ActOnFinishFullExpr(Expr *FullExpr) {
Douglas Gregora6e053e2010-12-15 01:34:56 +00003659 if (!FullExpr)
3660 return ExprError();
John McCall34376a62010-12-04 03:47:34 +00003661
Douglas Gregor506bd562010-12-13 22:49:22 +00003662 if (DiagnoseUnexpandedParameterPack(FullExpr))
3663 return ExprError();
3664
John McCall34376a62010-12-04 03:47:34 +00003665 IgnoredValueConversions(FullExpr);
John McCallacf0ee52010-10-08 02:01:28 +00003666 CheckImplicitConversions(FullExpr);
John McCall5d413782010-12-06 08:20:24 +00003667 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00003668}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00003669
3670StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
3671 if (!FullStmt) return StmtError();
3672
John McCall5d413782010-12-06 08:20:24 +00003673 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00003674}