blob: 3d155a5cf3a7323d0b8a467c3add94bac6de7dc3 [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"
John McCallc63de662011-02-02 13:00:07 +000019#include "clang/Sema/ScopeInfo.h"
Richard Smith938f40b2011-06-11 17:19:42 +000020#include "clang/Sema/Scope.h"
John McCall19c1bfd2010-08-25 05:32:35 +000021#include "clang/Sema/TemplateDeduction.h"
Steve Naroffaac94152007-08-25 14:02:58 +000022#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000023#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000024#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000025#include "clang/AST/ExprCXX.h"
Fariborz Jahanian1d446082010-06-16 18:56:04 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregorb1dd23f2010-02-24 22:38:50 +000027#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000028#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlfaf68082008-12-03 20:26:15 +000029#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000030#include "clang/Lex/Preprocessor.h"
David Blaikie1d578782011-12-16 16:03:09 +000031#include "TypeLocBuilder.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000032#include "llvm/ADT/STLExtras.h"
Chandler Carruth8b0cf1d2011-05-01 07:23:17 +000033#include "llvm/Support/ErrorHandling.h"
Chris Lattner29375652006-12-04 18:06:35 +000034using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000035using namespace sema;
Chris Lattner29375652006-12-04 18:06:35 +000036
John McCallba7bf592010-08-24 05:47:05 +000037ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000038 IdentifierInfo &II,
John McCallba7bf592010-08-24 05:47:05 +000039 SourceLocation NameLoc,
40 Scope *S, CXXScopeSpec &SS,
41 ParsedType ObjectTypePtr,
42 bool EnteringContext) {
Douglas Gregorfe17d252010-02-16 19:09:40 +000043 // Determine where to perform name lookup.
44
45 // FIXME: This area of the standard is very messy, and the current
46 // wording is rather unclear about which scopes we search for the
47 // destructor name; see core issues 399 and 555. Issue 399 in
48 // particular shows where the current description of destructor name
49 // lookup is completely out of line with existing practice, e.g.,
50 // this appears to be ill-formed:
51 //
52 // namespace N {
53 // template <typename T> struct S {
54 // ~S();
55 // };
56 // }
57 //
58 // void f(N::S<int>* s) {
59 // s->N::S<int>::~S();
60 // }
61 //
Douglas Gregor46841e12010-02-23 00:15:22 +000062 // See also PR6358 and PR6359.
Sebastian Redla771d222010-07-07 23:17:38 +000063 // For this reason, we're currently only doing the C++03 version of this
64 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregorfe17d252010-02-16 19:09:40 +000065 QualType SearchType;
66 DeclContext *LookupCtx = 0;
67 bool isDependent = false;
68 bool LookInScope = false;
69
70 // If we have an object type, it's because we are in a
71 // pseudo-destructor-expression or a member access expression, and
72 // we know what type we're looking for.
73 if (ObjectTypePtr)
74 SearchType = GetTypeFromParser(ObjectTypePtr);
75
76 if (SS.isSet()) {
Douglas Gregor46841e12010-02-23 00:15:22 +000077 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000078
Douglas Gregor46841e12010-02-23 00:15:22 +000079 bool AlreadySearched = false;
80 bool LookAtPrefix = true;
Sebastian Redla771d222010-07-07 23:17:38 +000081 // C++ [basic.lookup.qual]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000082 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redla771d222010-07-07 23:17:38 +000083 // the type-names are looked up as types in the scope designated by the
84 // nested-name-specifier. In a qualified-id of the form:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +000085 //
86 // ::[opt] nested-name-specifier ~ class-name
Sebastian Redla771d222010-07-07 23:17:38 +000087 //
88 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth8f254812010-02-21 10:19:54 +000089 // a qualified-id of the form:
Douglas Gregorfe17d252010-02-16 19:09:40 +000090 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +000091 // ::opt nested-name-specifier class-name :: ~ class-name
Douglas Gregorfe17d252010-02-16 19:09:40 +000092 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000093 // the class-names are looked up as types in the scope designated by
Sebastian Redla771d222010-07-07 23:17:38 +000094 // the nested-name-specifier.
Douglas Gregorfe17d252010-02-16 19:09:40 +000095 //
Sebastian Redla771d222010-07-07 23:17:38 +000096 // Here, we check the first case (completely) and determine whether the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000097 // code below is permitted to look at the prefix of the
Sebastian Redla771d222010-07-07 23:17:38 +000098 // nested-name-specifier.
99 DeclContext *DC = computeDeclContext(SS, EnteringContext);
100 if (DC && DC->isFileContext()) {
101 AlreadySearched = true;
102 LookupCtx = DC;
103 isDependent = false;
104 } else if (DC && isa<CXXRecordDecl>(DC))
105 LookAtPrefix = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000106
Sebastian Redla771d222010-07-07 23:17:38 +0000107 // The second case from the C++03 rules quoted further above.
Douglas Gregor46841e12010-02-23 00:15:22 +0000108 NestedNameSpecifier *Prefix = 0;
109 if (AlreadySearched) {
110 // Nothing left to do.
111 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
112 CXXScopeSpec PrefixSS;
Douglas Gregor10176412011-02-25 16:07:42 +0000113 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor46841e12010-02-23 00:15:22 +0000114 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
115 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor46841e12010-02-23 00:15:22 +0000116 } else if (ObjectTypePtr) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000117 LookupCtx = computeDeclContext(SearchType);
118 isDependent = SearchType->isDependentType();
119 } else {
120 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor46841e12010-02-23 00:15:22 +0000121 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000122 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000123
Douglas Gregorcd3f49f2010-02-25 04:46:04 +0000124 LookInScope = false;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000125 } else if (ObjectTypePtr) {
126 // C++ [basic.lookup.classref]p3:
127 // If the unqualified-id is ~type-name, the type-name is looked up
128 // in the context of the entire postfix-expression. If the type T
129 // of the object expression is of a class type C, the type-name is
130 // also looked up in the scope of class C. At least one of the
131 // lookups shall find a name that refers to (possibly
132 // cv-qualified) T.
133 LookupCtx = computeDeclContext(SearchType);
134 isDependent = SearchType->isDependentType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000135 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregorfe17d252010-02-16 19:09:40 +0000136 "Caller should have completed object type");
137
138 LookInScope = true;
139 } else {
140 // Perform lookup into the current scope (only).
141 LookInScope = true;
142 }
143
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000144 TypeDecl *NonMatchingTypeDecl = 0;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000145 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
146 for (unsigned Step = 0; Step != 2; ++Step) {
147 // Look for the name first in the computed lookup context (if we
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000148 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregorfe17d252010-02-16 19:09:40 +0000149 // we're allowed to look there).
150 Found.clear();
151 if (Step == 0 && LookupCtx)
152 LookupQualifiedName(Found, LookupCtx);
Douglas Gregor678f90d2010-02-25 01:56:36 +0000153 else if (Step == 1 && LookInScope && S)
Douglas Gregorfe17d252010-02-16 19:09:40 +0000154 LookupName(Found, S);
155 else
156 continue;
157
158 // FIXME: Should we be suppressing ambiguities here?
159 if (Found.isAmbiguous())
John McCallba7bf592010-08-24 05:47:05 +0000160 return ParsedType();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000161
162 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
163 QualType T = Context.getTypeDeclType(Type);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000164
165 if (SearchType.isNull() || SearchType->isDependentType() ||
166 Context.hasSameUnqualifiedType(T, SearchType)) {
167 // We found our type!
168
John McCallba7bf592010-08-24 05:47:05 +0000169 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000170 }
John Wiegleyb4a9e512011-03-08 08:13:22 +0000171
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000172 if (!SearchType.isNull())
173 NonMatchingTypeDecl = Type;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000174 }
175
176 // If the name that we found is a class template name, and it is
177 // the same name as the template name in the last part of the
178 // nested-name-specifier (if present) or the object type, then
179 // this is the destructor for that class.
180 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000181 // issue 399, for which there isn't even an obvious direction.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000182 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
183 QualType MemberOfType;
184 if (SS.isSet()) {
185 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
186 // Figure out the type of the context, if it has one.
John McCalle78aac42010-03-10 03:28:59 +0000187 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
188 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000189 }
190 }
191 if (MemberOfType.isNull())
192 MemberOfType = SearchType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000193
Douglas Gregorfe17d252010-02-16 19:09:40 +0000194 if (MemberOfType.isNull())
195 continue;
196
197 // We're referring into a class template specialization. If the
198 // class template we found is the same as the template being
199 // specialized, we found what we are looking for.
200 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
201 if (ClassTemplateSpecializationDecl *Spec
202 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
203 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
204 Template->getCanonicalDecl())
John McCallba7bf592010-08-24 05:47:05 +0000205 return ParsedType::make(MemberOfType);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000206 }
207
208 continue;
209 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000210
Douglas Gregorfe17d252010-02-16 19:09:40 +0000211 // We're referring to an unresolved class template
212 // specialization. Determine whether we class template we found
213 // is the same as the template being specialized or, if we don't
214 // know which template is being specialized, that it at least
215 // has the same name.
216 if (const TemplateSpecializationType *SpecType
217 = MemberOfType->getAs<TemplateSpecializationType>()) {
218 TemplateName SpecName = SpecType->getTemplateName();
219
220 // The class template we found is the same template being
221 // specialized.
222 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
223 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
John McCallba7bf592010-08-24 05:47:05 +0000224 return ParsedType::make(MemberOfType);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000225
226 continue;
227 }
228
229 // The class template we found has the same name as the
230 // (dependent) template name being specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000231 if (DependentTemplateName *DepTemplate
Douglas Gregorfe17d252010-02-16 19:09:40 +0000232 = SpecName.getAsDependentTemplateName()) {
233 if (DepTemplate->isIdentifier() &&
234 DepTemplate->getIdentifier() == Template->getIdentifier())
John McCallba7bf592010-08-24 05:47:05 +0000235 return ParsedType::make(MemberOfType);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000236
237 continue;
238 }
239 }
240 }
241 }
242
243 if (isDependent) {
244 // We didn't find our type, but that's okay: it's dependent
245 // anyway.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +0000246
247 // FIXME: What if we have no nested-name-specifier?
248 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
249 SS.getWithLocInContext(Context),
250 II, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +0000251 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000252 }
253
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000254 if (NonMatchingTypeDecl) {
255 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
256 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
257 << T << SearchType;
258 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
259 << T;
260 } else if (ObjectTypePtr)
261 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000262 << &II;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000263 else
264 Diag(NameLoc, diag::err_destructor_class_name);
265
John McCallba7bf592010-08-24 05:47:05 +0000266 return ParsedType();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000267}
268
David Blaikieecd8a942011-12-08 16:13:53 +0000269ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) {
David Blaikie08608f62011-12-12 04:13:55 +0000270 if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType)
David Blaikieecd8a942011-12-08 16:13:53 +0000271 return ParsedType();
272 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype
273 && "only get destructor types from declspecs");
274 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
275 QualType SearchType = GetTypeFromParser(ObjectType);
276 if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(SearchType, T)) {
277 return ParsedType::make(T);
278 }
279
280 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
281 << T << SearchType;
282 return ParsedType();
283}
284
Douglas Gregor9da64192010-04-26 22:37:10 +0000285/// \brief Build a C++ typeid expression with a type operand.
John McCalldadc5752010-08-24 06:29:42 +0000286ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000287 SourceLocation TypeidLoc,
288 TypeSourceInfo *Operand,
289 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000290 // C++ [expr.typeid]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000291 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor9da64192010-04-26 22:37:10 +0000292 // that is the operand of typeid are always ignored.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000293 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor9da64192010-04-26 22:37:10 +0000294 // type, the class shall be completely-defined.
Douglas Gregor876cec22010-06-02 06:16:02 +0000295 Qualifiers Quals;
296 QualType T
297 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
298 Quals);
Douglas Gregor9da64192010-04-26 22:37:10 +0000299 if (T->getAs<RecordType>() &&
300 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
301 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000302
Douglas Gregor9da64192010-04-26 22:37:10 +0000303 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
304 Operand,
305 SourceRange(TypeidLoc, RParenLoc)));
306}
307
308/// \brief Build a C++ typeid expression with an expression operand.
John McCalldadc5752010-08-24 06:29:42 +0000309ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000310 SourceLocation TypeidLoc,
311 Expr *E,
312 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000313 if (E && !E->isTypeDependent()) {
John McCall50a2c2c2011-10-11 23:14:30 +0000314 if (E->getType()->isPlaceholderType()) {
315 ExprResult result = CheckPlaceholderExpr(E);
316 if (result.isInvalid()) return ExprError();
317 E = result.take();
318 }
319
Douglas Gregor9da64192010-04-26 22:37:10 +0000320 QualType T = E->getType();
321 if (const RecordType *RecordT = T->getAs<RecordType>()) {
322 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
323 // C++ [expr.typeid]p3:
324 // [...] If the type of the expression is a class type, the class
325 // shall be completely-defined.
326 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
327 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000328
Douglas Gregor9da64192010-04-26 22:37:10 +0000329 // C++ [expr.typeid]p3:
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000330 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor9da64192010-04-26 22:37:10 +0000331 // polymorphic class type [...] [the] expression is an unevaluated
332 // operand. [...]
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000333 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
Eli Friedman456f0182012-01-20 01:26:23 +0000334 // The subexpression is potentially evaluated; switch the context
335 // and recheck the subexpression.
336 ExprResult Result = TranformToPotentiallyEvaluated(E);
337 if (Result.isInvalid()) return ExprError();
338 E = Result.take();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000339
340 // We require a vtable to query the type at run time.
341 MarkVTableUsed(TypeidLoc, RecordD);
342 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000343 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000344
Douglas Gregor9da64192010-04-26 22:37:10 +0000345 // C++ [expr.typeid]p4:
346 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000347 // cv-qualified type, the result of the typeid expression refers to a
348 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor9da64192010-04-26 22:37:10 +0000349 // type.
Douglas Gregor876cec22010-06-02 06:16:02 +0000350 Qualifiers Quals;
351 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
352 if (!Context.hasSameType(T, UnqualT)) {
353 T = UnqualT;
Eli Friedmanbe4b3632011-09-27 21:58:52 +0000354 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).take();
Douglas Gregor9da64192010-04-26 22:37:10 +0000355 }
356 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000357
Douglas Gregor9da64192010-04-26 22:37:10 +0000358 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCallb268a282010-08-23 23:25:46 +0000359 E,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000360 SourceRange(TypeidLoc, RParenLoc)));
Douglas Gregor9da64192010-04-26 22:37:10 +0000361}
362
363/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCalldadc5752010-08-24 06:29:42 +0000364ExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000365Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
366 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000367 // Find the std::type_info type.
Sebastian Redl7ac97412011-03-31 19:29:24 +0000368 if (!getStdNamespace())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000369 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000370
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000371 if (!CXXTypeInfoDecl) {
372 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
373 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
374 LookupQualifiedName(R, getStdNamespace());
375 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
376 if (!CXXTypeInfoDecl)
377 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
378 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000379
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000380 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000381
Douglas Gregor9da64192010-04-26 22:37:10 +0000382 if (isType) {
383 // The operand is a type; handle it as such.
384 TypeSourceInfo *TInfo = 0;
John McCallba7bf592010-08-24 05:47:05 +0000385 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
386 &TInfo);
Douglas Gregor9da64192010-04-26 22:37:10 +0000387 if (T.isNull())
388 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000389
Douglas Gregor9da64192010-04-26 22:37:10 +0000390 if (!TInfo)
391 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000392
Douglas Gregor9da64192010-04-26 22:37:10 +0000393 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000394 }
Mike Stump11289f42009-09-09 15:08:12 +0000395
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000396 // The operand is an expression.
John McCallb268a282010-08-23 23:25:46 +0000397 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000398}
399
Francois Pichetb7577652010-12-27 01:32:00 +0000400/// Retrieve the UuidAttr associated with QT.
401static UuidAttr *GetUuidAttrOfType(QualType QT) {
402 // Optionally remove one level of pointer, reference or array indirection.
John McCall424cec92011-01-19 06:33:43 +0000403 const Type *Ty = QT.getTypePtr();;
Francois Pichet9dddd402010-12-20 03:51:03 +0000404 if (QT->isPointerType() || QT->isReferenceType())
405 Ty = QT->getPointeeType().getTypePtr();
406 else if (QT->isArrayType())
407 Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
408
Francois Pichet59d2b012011-05-08 10:02:20 +0000409 // Loop all record redeclaration looking for an uuid attribute.
Francois Pichetb7577652010-12-27 01:32:00 +0000410 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Francois Pichet59d2b012011-05-08 10:02:20 +0000411 for (CXXRecordDecl::redecl_iterator I = RD->redecls_begin(),
412 E = RD->redecls_end(); I != E; ++I) {
413 if (UuidAttr *Uuid = I->getAttr<UuidAttr>())
Francois Pichetb7577652010-12-27 01:32:00 +0000414 return Uuid;
Francois Pichetb7577652010-12-27 01:32:00 +0000415 }
Francois Pichet59d2b012011-05-08 10:02:20 +0000416
Francois Pichetb7577652010-12-27 01:32:00 +0000417 return 0;
Francois Pichet9dddd402010-12-20 03:51:03 +0000418}
419
Francois Pichet9f4f2072010-09-08 12:20:18 +0000420/// \brief Build a Microsoft __uuidof expression with a type operand.
421ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
422 SourceLocation TypeidLoc,
423 TypeSourceInfo *Operand,
424 SourceLocation RParenLoc) {
Francois Pichetb7577652010-12-27 01:32:00 +0000425 if (!Operand->getType()->isDependentType()) {
426 if (!GetUuidAttrOfType(Operand->getType()))
427 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
428 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000429
Francois Pichet9f4f2072010-09-08 12:20:18 +0000430 // FIXME: add __uuidof semantic analysis for type operand.
431 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
432 Operand,
433 SourceRange(TypeidLoc, RParenLoc)));
434}
435
436/// \brief Build a Microsoft __uuidof expression with an expression operand.
437ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
438 SourceLocation TypeidLoc,
439 Expr *E,
440 SourceLocation RParenLoc) {
Francois Pichetb7577652010-12-27 01:32:00 +0000441 if (!E->getType()->isDependentType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000442 if (!GetUuidAttrOfType(E->getType()) &&
Francois Pichetb7577652010-12-27 01:32:00 +0000443 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
444 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
445 }
446 // FIXME: add __uuidof semantic analysis for type operand.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000447 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
448 E,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000449 SourceRange(TypeidLoc, RParenLoc)));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000450}
451
452/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
453ExprResult
454Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
455 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000456 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000457 if (!MSVCGuidDecl) {
458 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
459 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
460 LookupQualifiedName(R, Context.getTranslationUnitDecl());
461 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
462 if (!MSVCGuidDecl)
463 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000464 }
465
Francois Pichet9f4f2072010-09-08 12:20:18 +0000466 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000467
Francois Pichet9f4f2072010-09-08 12:20:18 +0000468 if (isType) {
469 // The operand is a type; handle it as such.
470 TypeSourceInfo *TInfo = 0;
471 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
472 &TInfo);
473 if (T.isNull())
474 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000475
Francois Pichet9f4f2072010-09-08 12:20:18 +0000476 if (!TInfo)
477 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
478
479 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
480 }
481
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000482 // The operand is an expression.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000483 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
484}
485
Steve Naroff66356bd2007-09-16 14:56:35 +0000486/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCalldadc5752010-08-24 06:29:42 +0000487ExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000488Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000489 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000490 "Unknown C++ Boolean value!");
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000491 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
492 Context.BoolTy, OpLoc));
Bill Wendling4073ed52007-02-13 01:51:42 +0000493}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000494
Sebastian Redl576fd422009-05-10 18:38:11 +0000495/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCalldadc5752010-08-24 06:29:42 +0000496ExprResult
Sebastian Redl576fd422009-05-10 18:38:11 +0000497Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
498 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
499}
500
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000501/// ActOnCXXThrow - Parse throw expressions.
John McCalldadc5752010-08-24 06:29:42 +0000502ExprResult
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000503Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
504 bool IsThrownVarInScope = false;
505 if (Ex) {
506 // C++0x [class.copymove]p31:
507 // When certain criteria are met, an implementation is allowed to omit the
508 // copy/move construction of a class object [...]
509 //
510 // - in a throw-expression, when the operand is the name of a
511 // non-volatile automatic object (other than a function or catch-
512 // clause parameter) whose scope does not extend beyond the end of the
513 // innermost enclosing try-block (if there is one), the copy/move
514 // operation from the operand to the exception object (15.1) can be
515 // omitted by constructing the automatic object directly into the
516 // exception object
517 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
518 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
519 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
520 for( ; S; S = S->getParent()) {
521 if (S->isDeclScope(Var)) {
522 IsThrownVarInScope = true;
523 break;
524 }
525
526 if (S->getFlags() &
527 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
528 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
529 Scope::TryScope))
530 break;
531 }
532 }
533 }
534 }
535
536 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
537}
538
539ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
540 bool IsThrownVarInScope) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000541 // Don't report an error if 'throw' is used in system headers.
Anders Carlssone96ab552011-02-28 02:27:16 +0000542 if (!getLangOptions().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000543 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb94ad3e2011-02-19 21:53:09 +0000544 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000545
John Wiegley01296292011-04-08 18:41:53 +0000546 if (Ex && !Ex->isTypeDependent()) {
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000547 ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex, IsThrownVarInScope);
John Wiegley01296292011-04-08 18:41:53 +0000548 if (ExRes.isInvalid())
549 return ExprError();
550 Ex = ExRes.take();
551 }
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000552
553 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc,
554 IsThrownVarInScope));
Sebastian Redl4de47b42009-04-27 20:27:31 +0000555}
556
557/// CheckCXXThrowOperand - Validate the operand of a throw.
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000558ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
559 bool IsThrownVarInScope) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000560 // C++ [except.throw]p3:
Douglas Gregor247894b2009-12-23 22:04:40 +0000561 // A throw-expression initializes a temporary object, called the exception
562 // object, the type of which is determined by removing any top-level
563 // cv-qualifiers from the static type of the operand of throw and adjusting
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000564 // the type from "array of T" or "function returning T" to "pointer to T"
Douglas Gregor247894b2009-12-23 22:04:40 +0000565 // or "pointer to function returning T", [...]
566 if (E->getType().hasQualifiers())
John Wiegley01296292011-04-08 18:41:53 +0000567 E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
Eli Friedmanbe4b3632011-09-27 21:58:52 +0000568 E->getValueKind()).take();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000569
John Wiegley01296292011-04-08 18:41:53 +0000570 ExprResult Res = DefaultFunctionArrayConversion(E);
571 if (Res.isInvalid())
572 return ExprError();
573 E = Res.take();
Sebastian Redl4de47b42009-04-27 20:27:31 +0000574
575 // If the type of the exception would be an incomplete type or a pointer
576 // to an incomplete type other than (cv) void the program is ill-formed.
577 QualType Ty = E->getType();
John McCall2e6567a2010-04-22 01:10:34 +0000578 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000579 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000580 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000581 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000582 }
583 if (!isPointer || !Ty->isVoidType()) {
584 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlsson029fc692009-08-26 22:59:12 +0000585 PDiag(isPointer ? diag::err_throw_incomplete_ptr
586 : diag::err_throw_incomplete)
587 << E->getSourceRange()))
John Wiegley01296292011-04-08 18:41:53 +0000588 return ExprError();
Rafael Espindola70e040d2010-03-02 21:28:26 +0000589
Douglas Gregore8154332010-04-15 18:05:39 +0000590 if (RequireNonAbstractType(ThrowLoc, E->getType(),
591 PDiag(diag::err_throw_abstract_type)
592 << E->getSourceRange()))
John Wiegley01296292011-04-08 18:41:53 +0000593 return ExprError();
Sebastian Redl4de47b42009-04-27 20:27:31 +0000594 }
595
John McCall2e6567a2010-04-22 01:10:34 +0000596 // Initialize the exception result. This implicitly weeds out
597 // abstract types or types with inaccessible copy constructors.
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000598
599 // C++0x [class.copymove]p31:
600 // When certain criteria are met, an implementation is allowed to omit the
601 // copy/move construction of a class object [...]
602 //
603 // - in a throw-expression, when the operand is the name of a
604 // non-volatile automatic object (other than a function or catch-clause
605 // parameter) whose scope does not extend beyond the end of the
606 // innermost enclosing try-block (if there is one), the copy/move
607 // operation from the operand to the exception object (15.1) can be
608 // omitted by constructing the automatic object directly into the
609 // exception object
610 const VarDecl *NRVOVariable = 0;
611 if (IsThrownVarInScope)
612 NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
613
John McCall2e6567a2010-04-22 01:10:34 +0000614 InitializedEntity Entity =
Douglas Gregorc74edc22011-01-21 22:46:35 +0000615 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000616 /*NRVO=*/NRVOVariable != 0);
John Wiegley01296292011-04-08 18:41:53 +0000617 Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000618 QualType(), E,
619 IsThrownVarInScope);
John McCall2e6567a2010-04-22 01:10:34 +0000620 if (Res.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000621 return ExprError();
622 E = Res.take();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000623
Eli Friedman91a3d272010-06-03 20:39:03 +0000624 // If the exception has class type, we need additional handling.
625 const RecordType *RecordTy = Ty->getAs<RecordType>();
626 if (!RecordTy)
John Wiegley01296292011-04-08 18:41:53 +0000627 return Owned(E);
Eli Friedman91a3d272010-06-03 20:39:03 +0000628 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
629
Douglas Gregor88d292c2010-05-13 16:44:06 +0000630 // If we are throwing a polymorphic class type or pointer thereof,
631 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000632 MarkVTableUsed(ThrowLoc, RD);
633
Eli Friedman36ebbec2010-10-12 20:32:36 +0000634 // If a pointer is thrown, the referenced object will not be destroyed.
635 if (isPointer)
John Wiegley01296292011-04-08 18:41:53 +0000636 return Owned(E);
Eli Friedman36ebbec2010-10-12 20:32:36 +0000637
Eli Friedman91a3d272010-06-03 20:39:03 +0000638 // If the class has a non-trivial destructor, we must be able to call it.
639 if (RD->hasTrivialDestructor())
John Wiegley01296292011-04-08 18:41:53 +0000640 return Owned(E);
Eli Friedman91a3d272010-06-03 20:39:03 +0000641
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000642 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +0000643 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman91a3d272010-06-03 20:39:03 +0000644 if (!Destructor)
John Wiegley01296292011-04-08 18:41:53 +0000645 return Owned(E);
Eli Friedman91a3d272010-06-03 20:39:03 +0000646
647 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
648 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregor747eb782010-07-08 06:14:04 +0000649 PDiag(diag::err_access_dtor_exception) << Ty);
John Wiegley01296292011-04-08 18:41:53 +0000650 return Owned(E);
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000651}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000652
Eli Friedman73a04092012-01-07 04:59:52 +0000653QualType Sema::getCurrentThisType() {
654 DeclContext *DC = getFunctionLevelDeclContext();
Richard Smith938f40b2011-06-11 17:19:42 +0000655 QualType ThisTy;
656 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
657 if (method && method->isInstance())
658 ThisTy = method->getThisType(Context);
659 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
660 // C++0x [expr.prim]p4:
661 // Otherwise, if a member-declarator declares a non-static data member
662 // of a class X, the expression this is a prvalue of type "pointer to X"
663 // within the optional brace-or-equal-initializer.
664 Scope *S = getScopeForContext(DC);
665 if (!S || S->getFlags() & Scope::ThisScope)
666 ThisTy = Context.getPointerType(Context.getRecordType(RD));
667 }
John McCallc63de662011-02-02 13:00:07 +0000668
Richard Smith938f40b2011-06-11 17:19:42 +0000669 return ThisTy;
John McCallf3a88602011-02-03 08:15:49 +0000670}
671
Eli Friedman73a04092012-01-07 04:59:52 +0000672void Sema::CheckCXXThisCapture(SourceLocation Loc) {
673 // We don't need to capture this in an unevaluated context.
674 if (ExprEvalContexts.back().Context == Unevaluated)
675 return;
676
677 // Otherwise, check that we can capture 'this'.
678 unsigned NumClosures = 0;
679 for (unsigned idx = FunctionScopes.size() - 1; idx != 0; idx--) {
Eli Friedman20139d32012-01-11 02:36:31 +0000680 if (CapturingScopeInfo *CSI =
681 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
682 if (CSI->CXXThisCaptureIndex != 0) {
683 // 'this' is already being captured; there isn't anything more to do.
Eli Friedman73a04092012-01-07 04:59:52 +0000684 break;
685 }
Eli Friedman20139d32012-01-11 02:36:31 +0000686 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
687 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block) {
688 // This closure can implicitly capture 'this'; continue looking upwards.
Eli Friedman73a04092012-01-07 04:59:52 +0000689 // FIXME: Is this check correct? The rules in the standard are a bit
690 // unclear.
691 NumClosures++;
692 continue;
693 }
Eli Friedman20139d32012-01-11 02:36:31 +0000694 // This context can't implicitly capture 'this'; fail out.
Eli Friedman456f0182012-01-20 01:26:23 +0000695 Diag(Loc, diag::err_implicit_this_capture);
Eli Friedman73a04092012-01-07 04:59:52 +0000696 return;
697 }
Eli Friedman73a04092012-01-07 04:59:52 +0000698 break;
699 }
700
701 // Mark that we're implicitly capturing 'this' in all the scopes we skipped.
702 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
703 // contexts.
704 for (unsigned idx = FunctionScopes.size() - 1;
705 NumClosures; --idx, --NumClosures) {
Eli Friedman20139d32012-01-11 02:36:31 +0000706 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
707 bool isNested = NumClosures > 1;
708 CSI->AddThisCapture(isNested);
Eli Friedman73a04092012-01-07 04:59:52 +0000709 }
710}
711
Richard Smith938f40b2011-06-11 17:19:42 +0000712ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCallf3a88602011-02-03 08:15:49 +0000713 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
714 /// is a non-lvalue expression whose value is the address of the object for
715 /// which the function is called.
716
Douglas Gregor09deffa2011-10-18 16:47:30 +0000717 QualType ThisTy = getCurrentThisType();
Richard Smith938f40b2011-06-11 17:19:42 +0000718 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCallf3a88602011-02-03 08:15:49 +0000719
Eli Friedman73a04092012-01-07 04:59:52 +0000720 CheckCXXThisCapture(Loc);
Richard Smith938f40b2011-06-11 17:19:42 +0000721 return Owned(new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000722}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000723
John McCalldadc5752010-08-24 06:29:42 +0000724ExprResult
Douglas Gregor2b88c112010-09-08 00:15:04 +0000725Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000726 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000727 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000728 SourceLocation RParenLoc) {
Douglas Gregor7df89f52010-02-05 19:11:37 +0000729 if (!TypeRep)
730 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000731
John McCall97513962010-01-15 18:39:57 +0000732 TypeSourceInfo *TInfo;
733 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
734 if (!TInfo)
735 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregor2b88c112010-09-08 00:15:04 +0000736
737 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
738}
739
740/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
741/// Can be interpreted either as function-style casting ("int(x)")
742/// or class type construction ("ClassType(x,y,z)")
743/// or creation of a value-initialized type ("int()").
744ExprResult
745Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
746 SourceLocation LParenLoc,
747 MultiExprArg exprs,
748 SourceLocation RParenLoc) {
749 QualType Ty = TInfo->getType();
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000750 unsigned NumExprs = exprs.size();
751 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregor2b88c112010-09-08 00:15:04 +0000752 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000753 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
754
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000755 if (Ty->isDependentType() ||
Douglas Gregor0950e412009-03-13 21:01:28 +0000756 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000757 exprs.release();
Mike Stump11289f42009-09-09 15:08:12 +0000758
Douglas Gregor2b88c112010-09-08 00:15:04 +0000759 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregorce934142009-05-20 18:46:25 +0000760 LParenLoc,
761 Exprs, NumExprs,
762 RParenLoc));
Douglas Gregor0950e412009-03-13 21:01:28 +0000763 }
764
Anders Carlsson55243162009-08-27 03:53:50 +0000765 if (Ty->isArrayType())
766 return ExprError(Diag(TyBeginLoc,
767 diag::err_value_init_for_array_type) << FullRange);
768 if (!Ty->isVoidType() &&
769 RequireCompleteType(TyBeginLoc, Ty,
770 PDiag(diag::err_invalid_incomplete_type_use)
771 << FullRange))
772 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000773
Anders Carlsson55243162009-08-27 03:53:50 +0000774 if (RequireNonAbstractType(TyBeginLoc, Ty,
775 diag::err_allocation_of_abstract_type))
776 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000777
778
Douglas Gregordd04d332009-01-16 18:33:17 +0000779 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000780 // If the expression list is a single expression, the type conversion
781 // expression is equivalent (in definedness, and if defined in meaning) to the
782 // corresponding cast expression.
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000783 if (NumExprs == 1) {
John McCallb50451a2011-10-05 07:41:44 +0000784 Expr *Arg = Exprs[0];
Anders Carlssone9766d52009-09-09 21:33:21 +0000785 exprs.release();
John McCallb50451a2011-10-05 07:41:44 +0000786 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000787 }
788
Douglas Gregor8ec51732010-09-08 21:40:08 +0000789 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
790 InitializationKind Kind
791 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
792 LParenLoc, RParenLoc)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000793 : InitializationKind::CreateValue(TyBeginLoc,
Douglas Gregor8ec51732010-09-08 21:40:08 +0000794 LParenLoc, RParenLoc);
795 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
796 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000797
Douglas Gregor8ec51732010-09-08 21:40:08 +0000798 // FIXME: Improve AST representation?
799 return move(Result);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000800}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000801
John McCall284c48f2011-01-27 09:37:56 +0000802/// doesUsualArrayDeleteWantSize - Answers whether the usual
803/// operator delete[] for the given type has a size_t parameter.
804static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
805 QualType allocType) {
806 const RecordType *record =
807 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
808 if (!record) return false;
809
810 // Try to find an operator delete[] in class scope.
811
812 DeclarationName deleteName =
813 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
814 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
815 S.LookupQualifiedName(ops, record->getDecl());
816
817 // We're just doing this for information.
818 ops.suppressDiagnostics();
819
820 // Very likely: there's no operator delete[].
821 if (ops.empty()) return false;
822
823 // If it's ambiguous, it should be illegal to call operator delete[]
824 // on this thing, so it doesn't matter if we allocate extra space or not.
825 if (ops.isAmbiguous()) return false;
826
827 LookupResult::Filter filter = ops.makeFilter();
828 while (filter.hasNext()) {
829 NamedDecl *del = filter.next()->getUnderlyingDecl();
830
831 // C++0x [basic.stc.dynamic.deallocation]p2:
832 // A template instance is never a usual deallocation function,
833 // regardless of its signature.
834 if (isa<FunctionTemplateDecl>(del)) {
835 filter.erase();
836 continue;
837 }
838
839 // C++0x [basic.stc.dynamic.deallocation]p2:
840 // If class T does not declare [an operator delete[] with one
841 // parameter] but does declare a member deallocation function
842 // named operator delete[] with exactly two parameters, the
843 // second of which has type std::size_t, then this function
844 // is a usual deallocation function.
845 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
846 filter.erase();
847 continue;
848 }
849 }
850 filter.done();
851
852 if (!ops.isSingleResult()) return false;
853
854 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
855 return (del->getNumParams() == 2);
856}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000857
Sebastian Redlbd150f42008-11-21 19:14:01 +0000858/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
859/// @code new (memory) int[size][4] @endcode
860/// or
861/// @code ::new Foo(23, "hello") @endcode
862/// For the interpretation of this heap of arguments, consult the base version.
John McCalldadc5752010-08-24 06:29:42 +0000863ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +0000864Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000865 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000866 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl351bb782008-12-02 14:43:59 +0000867 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000868 MultiExprArg ConstructorArgs,
Mike Stump11289f42009-09-09 15:08:12 +0000869 SourceLocation ConstructorRParen) {
Richard Smith30482bc2011-02-20 03:19:35 +0000870 bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
871
Sebastian Redl351bb782008-12-02 14:43:59 +0000872 Expr *ArraySize = 0;
Sebastian Redl351bb782008-12-02 14:43:59 +0000873 // If the specified type is an array, unwrap it and save the expression.
874 if (D.getNumTypeObjects() > 0 &&
875 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
876 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smith30482bc2011-02-20 03:19:35 +0000877 if (TypeContainsAuto)
878 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
879 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000880 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000881 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
882 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000883 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000884 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
885 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000886
Sebastian Redl351bb782008-12-02 14:43:59 +0000887 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000888 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +0000889 }
890
Douglas Gregor73341c42009-09-11 00:18:58 +0000891 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000892 if (ArraySize) {
893 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +0000894 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
895 break;
896
897 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
898 if (Expr *NumElts = (Expr *)Array.NumElts) {
899 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
900 !NumElts->isIntegerConstantExpr(Context)) {
901 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
902 << NumElts->getSourceRange();
903 return ExprError();
904 }
905 }
906 }
907 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000908
Argyrios Kyrtzidis3ff13572011-06-28 03:01:23 +0000909 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
John McCall8cb7bdf2010-06-04 23:28:52 +0000910 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000911 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000912 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000913
Mike Stump11289f42009-09-09 15:08:12 +0000914 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000915 PlacementLParen,
Mike Stump11289f42009-09-09 15:08:12 +0000916 move(PlacementArgs),
Douglas Gregord0fefba2009-05-21 00:00:09 +0000917 PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +0000918 TypeIdParens,
Mike Stump11289f42009-09-09 15:08:12 +0000919 AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +0000920 TInfo,
John McCallb268a282010-08-23 23:25:46 +0000921 ArraySize,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000922 ConstructorLParen,
923 move(ConstructorArgs),
Richard Smith30482bc2011-02-20 03:19:35 +0000924 ConstructorRParen,
925 TypeContainsAuto);
Douglas Gregord0fefba2009-05-21 00:00:09 +0000926}
927
John McCalldadc5752010-08-24 06:29:42 +0000928ExprResult
Douglas Gregord0fefba2009-05-21 00:00:09 +0000929Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
930 SourceLocation PlacementLParen,
931 MultiExprArg PlacementArgs,
932 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +0000933 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000934 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +0000935 TypeSourceInfo *AllocTypeInfo,
John McCallb268a282010-08-23 23:25:46 +0000936 Expr *ArraySize,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000937 SourceLocation ConstructorLParen,
938 MultiExprArg ConstructorArgs,
Richard Smith30482bc2011-02-20 03:19:35 +0000939 SourceLocation ConstructorRParen,
940 bool TypeMayContainAuto) {
Douglas Gregor0744ef62010-09-07 21:49:58 +0000941 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
Sebastian Redl351bb782008-12-02 14:43:59 +0000942
Richard Smith30482bc2011-02-20 03:19:35 +0000943 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
944 if (TypeMayContainAuto && AllocType->getContainedAutoType()) {
945 if (ConstructorArgs.size() == 0)
946 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
947 << AllocType << TypeRange);
948 if (ConstructorArgs.size() != 1) {
949 Expr *FirstBad = ConstructorArgs.get()[1];
950 return ExprError(Diag(FirstBad->getSourceRange().getBegin(),
951 diag::err_auto_new_ctor_multiple_expressions)
952 << AllocType << TypeRange);
953 }
Richard Smith9647d3c2011-03-17 16:11:59 +0000954 TypeSourceInfo *DeducedType = 0;
955 if (!DeduceAutoType(AllocTypeInfo, ConstructorArgs.get()[0], DeducedType))
Richard Smith30482bc2011-02-20 03:19:35 +0000956 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
957 << AllocType
958 << ConstructorArgs.get()[0]->getType()
959 << TypeRange
960 << ConstructorArgs.get()[0]->getSourceRange());
Richard Smith9647d3c2011-03-17 16:11:59 +0000961 if (!DeducedType)
962 return ExprError();
Richard Smith30482bc2011-02-20 03:19:35 +0000963
Richard Smith9647d3c2011-03-17 16:11:59 +0000964 AllocTypeInfo = DeducedType;
965 AllocType = AllocTypeInfo->getType();
Richard Smith30482bc2011-02-20 03:19:35 +0000966 }
967
Douglas Gregorcda95f42010-05-16 16:01:03 +0000968 // Per C++0x [expr.new]p5, the type being constructed may be a
969 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +0000970 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +0000971 if (const ConstantArrayType *Array
972 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000973 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
974 Context.getSizeType(),
975 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +0000976 AllocType = Array->getElementType();
977 }
978 }
Sebastian Redlbd150f42008-11-21 19:14:01 +0000979
Douglas Gregor3999e152010-10-06 16:00:31 +0000980 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
981 return ExprError();
982
John McCall31168b02011-06-15 23:02:42 +0000983 // In ARC, infer 'retaining' for the allocated
984 if (getLangOptions().ObjCAutoRefCount &&
985 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
986 AllocType->isObjCLifetimeType()) {
987 AllocType = Context.getLifetimeQualifiedType(AllocType,
988 AllocType->getObjCARCImplicitLifetime());
989 }
Sebastian Redl351bb782008-12-02 14:43:59 +0000990
John McCall31168b02011-06-15 23:02:42 +0000991 QualType ResultType = Context.getPointerType(AllocType);
992
Sebastian Redlbd150f42008-11-21 19:14:01 +0000993 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
994 // or enumeration type with a non-negative value."
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000995 if (ArraySize && !ArraySize->isTypeDependent()) {
Eli Friedman844f9452012-01-23 02:35:22 +0000996 ExprResult ConvertedSize = DefaultFunctionArrayLvalueConversion(ArraySize);
John McCall9b80c212012-01-11 00:14:46 +0000997 if (ConvertedSize.isInvalid())
998 return ExprError();
999 ArraySize = ConvertedSize.take();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001000
John McCall9b80c212012-01-11 00:14:46 +00001001 ConvertedSize = ConvertToIntegralOrEnumerationType(
Richard Smith0bf8a4922011-10-18 20:49:44 +00001002 StartLoc, ArraySize,
1003 PDiag(diag::err_array_size_not_integral),
1004 PDiag(diag::err_array_size_incomplete_type)
1005 << ArraySize->getSourceRange(),
1006 PDiag(diag::err_array_size_explicit_conversion),
1007 PDiag(diag::note_array_size_conversion),
1008 PDiag(diag::err_array_size_ambiguous_conversion),
1009 PDiag(diag::note_array_size_conversion),
1010 PDiag(getLangOptions().CPlusPlus0x ?
1011 diag::warn_cxx98_compat_array_size_conversion :
1012 diag::ext_array_size_conversion));
Douglas Gregor4799d032010-06-30 00:20:43 +00001013 if (ConvertedSize.isInvalid())
1014 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001015
John McCallb268a282010-08-23 23:25:46 +00001016 ArraySize = ConvertedSize.take();
John McCall9b80c212012-01-11 00:14:46 +00001017 QualType SizeType = ArraySize->getType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00001018 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +00001019 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001020
Sebastian Redl351bb782008-12-02 14:43:59 +00001021 // Let's see if this is a constant < 0. If so, we reject it out of hand.
1022 // We don't care about special rules, so we tell the machinery it's not
1023 // evaluated - it gives us a result in more cases.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001024 if (!ArraySize->isValueDependent()) {
1025 llvm::APSInt Value;
1026 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
1027 if (Value < llvm::APSInt(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001028 llvm::APInt::getNullValue(Value.getBitWidth()),
Anders Carlsson8ab20bb2009-09-23 00:37:25 +00001029 Value.isUnsigned()))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001030 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00001031 diag::err_typecheck_negative_array_size)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001032 << ArraySize->getSourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001033
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00001034 if (!AllocType->isDependentType()) {
1035 unsigned ActiveSizeBits
1036 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1037 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001038 Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00001039 diag::err_array_too_large)
1040 << Value.toString(10)
1041 << ArraySize->getSourceRange();
1042 return ExprError();
1043 }
1044 }
Douglas Gregorf2753b32010-07-13 15:54:32 +00001045 } else if (TypeIdParens.isValid()) {
1046 // Can't have dynamic array size when the type-id is in parentheses.
1047 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1048 << ArraySize->getSourceRange()
1049 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1050 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001051
Douglas Gregorf2753b32010-07-13 15:54:32 +00001052 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001053 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001054 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001055
John McCall31168b02011-06-15 23:02:42 +00001056 // ARC: warn about ABI issues.
1057 if (getLangOptions().ObjCAutoRefCount) {
1058 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1059 if (BaseAllocType.hasStrongOrWeakObjCLifetime())
1060 Diag(StartLoc, diag::warn_err_new_delete_object_array)
1061 << 0 << BaseAllocType;
1062 }
1063
John McCall036f2f62011-05-15 07:14:44 +00001064 // Note that we do *not* convert the argument in any way. It can
1065 // be signed, larger than size_t, whatever.
Sebastian Redl351bb782008-12-02 14:43:59 +00001066 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001067
Sebastian Redlbd150f42008-11-21 19:14:01 +00001068 FunctionDecl *OperatorNew = 0;
1069 FunctionDecl *OperatorDelete = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001070 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
1071 unsigned NumPlaceArgs = PlacementArgs.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001072
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001073 if (!AllocType->isDependentType() &&
1074 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
1075 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001076 SourceRange(PlacementLParen, PlacementRParen),
1077 UseGlobal, AllocType, ArraySize, PlaceArgs,
1078 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001079 return ExprError();
John McCall284c48f2011-01-27 09:37:56 +00001080
1081 // If this is an array allocation, compute whether the usual array
1082 // deallocation function for the type has a size_t parameter.
1083 bool UsualArrayDeleteWantsSize = false;
1084 if (ArraySize && !AllocType->isDependentType())
1085 UsualArrayDeleteWantsSize
1086 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1087
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001088 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001089 if (OperatorNew) {
1090 // Add default arguments, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001091 const FunctionProtoType *Proto =
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001092 OperatorNew->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001093 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00001094 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001095
Anders Carlssonc144bc22010-05-03 02:07:56 +00001096 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001097 Proto, 1, PlaceArgs, NumPlaceArgs,
Anders Carlssonc144bc22010-05-03 02:07:56 +00001098 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001099 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001100
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001101 NumPlaceArgs = AllPlaceArgs.size();
1102 if (NumPlaceArgs > 0)
1103 PlaceArgs = &AllPlaceArgs[0];
1104 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001105
Sebastian Redlbd150f42008-11-21 19:14:01 +00001106 bool Init = ConstructorLParen.isValid();
1107 // --- Choosing a constructor ---
Sebastian Redlbd150f42008-11-21 19:14:01 +00001108 CXXConstructorDecl *Constructor = 0;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00001109 bool HadMultipleCandidates = false;
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001110 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
1111 unsigned NumConsArgs = ConstructorArgs.size();
John McCall37ad5512010-08-23 06:44:23 +00001112 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmanfd8d4e12009-11-08 22:15:39 +00001113
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00001114 // Array 'new' can't have any initializers.
Anders Carlssone6ae81b2010-05-16 16:24:20 +00001115 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00001116 SourceRange InitRange(ConsArgs[0]->getLocStart(),
1117 ConsArgs[NumConsArgs - 1]->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001118
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00001119 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1120 return ExprError();
1121 }
1122
Douglas Gregor85dabae2009-12-16 01:38:02 +00001123 if (!AllocType->isDependentType() &&
1124 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
1125 // C++0x [expr.new]p15:
1126 // A new-expression that creates an object of type T initializes that
1127 // object as follows:
1128 InitializationKind Kind
1129 // - If the new-initializer is omitted, the object is default-
1130 // initialized (8.5); if no initialization is performed,
1131 // the object has indeterminate value
Douglas Gregor0744ef62010-09-07 21:49:58 +00001132 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001133 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor85dabae2009-12-16 01:38:02 +00001134 // initialization rules of 8.5 for direct-initialization.
Douglas Gregor0744ef62010-09-07 21:49:58 +00001135 : InitializationKind::CreateDirect(TypeRange.getBegin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001136 ConstructorLParen,
Douglas Gregor85dabae2009-12-16 01:38:02 +00001137 ConstructorRParen);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001138
Douglas Gregor85dabae2009-12-16 01:38:02 +00001139 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00001140 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00001141 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001142 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor85dabae2009-12-16 01:38:02 +00001143 move(ConstructorArgs));
1144 if (FullInit.isInvalid())
1145 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001146
1147 // FullInit is our initializer; walk through it to determine if it's a
Douglas Gregor85dabae2009-12-16 01:38:02 +00001148 // constructor call, which CXXNewExpr handles directly.
1149 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
1150 if (CXXBindTemporaryExpr *Binder
1151 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
1152 FullInitExpr = Binder->getSubExpr();
1153 if (CXXConstructExpr *Construct
1154 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
1155 Constructor = Construct->getConstructor();
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00001156 HadMultipleCandidates = Construct->hadMultipleCandidates();
Douglas Gregor85dabae2009-12-16 01:38:02 +00001157 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
1158 AEnd = Construct->arg_end();
1159 A != AEnd; ++A)
John McCallc3007a22010-10-26 07:05:15 +00001160 ConvertedConstructorArgs.push_back(*A);
Douglas Gregor85dabae2009-12-16 01:38:02 +00001161 } else {
1162 // Take the converted initializer.
1163 ConvertedConstructorArgs.push_back(FullInit.release());
1164 }
1165 } else {
1166 // No initialization required.
1167 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001168
Douglas Gregor85dabae2009-12-16 01:38:02 +00001169 // Take the converted arguments and use them for the new expression.
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001170 NumConsArgs = ConvertedConstructorArgs.size();
1171 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redlbd150f42008-11-21 19:14:01 +00001172 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001173
Douglas Gregor6642ca22010-02-26 05:06:18 +00001174 // Mark the new and delete operators as referenced.
1175 if (OperatorNew)
1176 MarkDeclarationReferenced(StartLoc, OperatorNew);
1177 if (OperatorDelete)
1178 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1179
John McCall928a2572011-07-13 20:12:57 +00001180 // C++0x [expr.new]p17:
1181 // If the new expression creates an array of objects of class type,
1182 // access and ambiguity control are done for the destructor.
1183 if (ArraySize && Constructor) {
1184 if (CXXDestructorDecl *dtor = LookupDestructor(Constructor->getParent())) {
1185 MarkDeclarationReferenced(StartLoc, dtor);
1186 CheckDestructorAccess(StartLoc, dtor,
1187 PDiag(diag::err_access_dtor)
1188 << Context.getBaseElementType(AllocType));
1189 }
1190 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001191
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001192 PlacementArgs.release();
1193 ConstructorArgs.release();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001194
Ted Kremenek9d6eb402010-02-11 22:51:03 +00001195 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001196 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenek9d6eb402010-02-11 22:51:03 +00001197 ArraySize, Constructor, Init,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00001198 ConsArgs, NumConsArgs,
1199 HadMultipleCandidates,
1200 OperatorDelete,
John McCall284c48f2011-01-27 09:37:56 +00001201 UsualArrayDeleteWantsSize,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001202 ResultType, AllocTypeInfo,
1203 StartLoc,
Ted Kremenek9d6eb402010-02-11 22:51:03 +00001204 Init ? ConstructorRParen :
Chandler Carruth01718152010-10-25 08:47:36 +00001205 TypeRange.getEnd(),
1206 ConstructorLParen, ConstructorRParen));
Sebastian Redlbd150f42008-11-21 19:14:01 +00001207}
1208
1209/// CheckAllocatedType - Checks that a type is suitable as the allocated type
1210/// in a new-expression.
1211/// dimension off and stores the size expression in ArraySize.
Douglas Gregord0fefba2009-05-21 00:00:09 +00001212bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00001213 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00001214 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1215 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +00001216 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00001217 return Diag(Loc, diag::err_bad_new_type)
1218 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00001219 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00001220 return Diag(Loc, diag::err_bad_new_type)
1221 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00001222 else if (!AllocType->isDependentType() &&
Douglas Gregord0fefba2009-05-21 00:00:09 +00001223 RequireCompleteType(Loc, AllocType,
Anders Carlssond624e162009-08-26 23:45:07 +00001224 PDiag(diag::err_new_incomplete_type)
1225 << R))
Sebastian Redlbd150f42008-11-21 19:14:01 +00001226 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +00001227 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +00001228 diag::err_allocation_of_abstract_type))
1229 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +00001230 else if (AllocType->isVariablyModifiedType())
1231 return Diag(Loc, diag::err_variably_modified_new_type)
1232 << AllocType;
Douglas Gregor39d1a092011-04-15 19:46:20 +00001233 else if (unsigned AddressSpace = AllocType.getAddressSpace())
1234 return Diag(Loc, diag::err_address_space_qualified_new)
1235 << AllocType.getUnqualifiedType() << AddressSpace;
John McCall31168b02011-06-15 23:02:42 +00001236 else if (getLangOptions().ObjCAutoRefCount) {
1237 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
1238 QualType BaseAllocType = Context.getBaseElementType(AT);
1239 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1240 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001241 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCall31168b02011-06-15 23:02:42 +00001242 << BaseAllocType;
1243 }
1244 }
Douglas Gregor39d1a092011-04-15 19:46:20 +00001245
Sebastian Redlbd150f42008-11-21 19:14:01 +00001246 return false;
1247}
1248
Douglas Gregor6642ca22010-02-26 05:06:18 +00001249/// \brief Determine whether the given function is a non-placement
1250/// deallocation function.
1251static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1252 if (FD->isInvalidDecl())
1253 return false;
1254
1255 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1256 return Method->isUsualDeallocationFunction();
1257
1258 return ((FD->getOverloadedOperator() == OO_Delete ||
1259 FD->getOverloadedOperator() == OO_Array_Delete) &&
1260 FD->getNumParams() == 1);
1261}
1262
Sebastian Redlfaf68082008-12-03 20:26:15 +00001263/// FindAllocationFunctions - Finds the overloads of operator new and delete
1264/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001265bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1266 bool UseGlobal, QualType AllocType,
1267 bool IsArray, Expr **PlaceArgs,
1268 unsigned NumPlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +00001269 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +00001270 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001271 // --- Choosing an allocation function ---
1272 // C++ 5.3.4p8 - 14 & 18
1273 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1274 // in the scope of the allocated class.
1275 // 2) If an array size is given, look for operator new[], else look for
1276 // operator new.
1277 // 3) The first argument is always size_t. Append the arguments from the
1278 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +00001279
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001280 SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001281 // We don't care about the actual value of this argument.
1282 // FIXME: Should the Sema create the expression and embed it in the syntax
1283 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001284 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregore8bbc122011-09-02 00:18:52 +00001285 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssona471db02009-08-16 20:29:29 +00001286 Context.getSizeType(),
1287 SourceLocation());
1288 AllocArgs[0] = &Size;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001289 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1290
Douglas Gregor6642ca22010-02-26 05:06:18 +00001291 // C++ [expr.new]p8:
1292 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001293 // function's name is operator new and the deallocation function's
Douglas Gregor6642ca22010-02-26 05:06:18 +00001294 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001295 // type, the allocation function's name is operator new[] and the
1296 // deallocation function's name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +00001297 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1298 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001299 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1300 IsArray ? OO_Array_Delete : OO_Delete);
1301
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001302 QualType AllocElemType = Context.getBaseElementType(AllocType);
1303
1304 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump11289f42009-09-09 15:08:12 +00001305 CXXRecordDecl *Record
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001306 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001307 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +00001308 AllocArgs.size(), Record, /*AllowMissing=*/true,
1309 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +00001310 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001311 }
1312 if (!OperatorNew) {
1313 // Didn't find a member overload. Look for a global one.
1314 DeclareGlobalNewDelete();
Sebastian Redl33a31012008-12-04 22:20:51 +00001315 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001316 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +00001317 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1318 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +00001319 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001320 }
1321
John McCall0f55a032010-04-20 02:18:25 +00001322 // We don't need an operator delete if we're running under
1323 // -fno-exceptions.
1324 if (!getLangOptions().Exceptions) {
1325 OperatorDelete = 0;
1326 return false;
1327 }
1328
Anders Carlsson6f9dabf2009-05-31 20:26:12 +00001329 // FindAllocationOverload can change the passed in arguments, so we need to
1330 // copy them back.
1331 if (NumPlaceArgs > 0)
1332 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001333
Douglas Gregor6642ca22010-02-26 05:06:18 +00001334 // C++ [expr.new]p19:
1335 //
1336 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001337 // deallocation function's name is looked up in the global
Douglas Gregor6642ca22010-02-26 05:06:18 +00001338 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001339 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6642ca22010-02-26 05:06:18 +00001340 // the scope of T. If this lookup fails to find the name, or if
1341 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001342 // deallocation function's name is looked up in the global scope.
Douglas Gregor6642ca22010-02-26 05:06:18 +00001343 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001344 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00001345 CXXRecordDecl *RD
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001346 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00001347 LookupQualifiedName(FoundDelete, RD);
1348 }
John McCallfb6f5262010-03-18 08:19:33 +00001349 if (FoundDelete.isAmbiguous())
1350 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00001351
1352 if (FoundDelete.empty()) {
1353 DeclareGlobalNewDelete();
1354 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1355 }
1356
1357 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00001358
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001359 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCalla0296f72010-03-19 07:35:19 +00001360
John McCalld3be2c82010-09-14 21:34:24 +00001361 // Whether we're looking for a placement operator delete is dictated
1362 // by whether we selected a placement operator new, not by whether
1363 // we had explicit placement arguments. This matters for things like
1364 // struct A { void *operator new(size_t, int = 0); ... };
1365 // A *a = new A()
1366 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1367
1368 if (isPlacementNew) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00001369 // C++ [expr.new]p20:
1370 // A declaration of a placement deallocation function matches the
1371 // declaration of a placement allocation function if it has the
1372 // same number of parameters and, after parameter transformations
1373 // (8.3.5), all parameter types except the first are
1374 // identical. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001375 //
Douglas Gregor6642ca22010-02-26 05:06:18 +00001376 // To perform this comparison, we compute the function type that
1377 // the deallocation function should have, and use that type both
1378 // for template argument deduction and for comparison purposes.
John McCalldb40c7f2010-12-14 08:05:40 +00001379 //
1380 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6642ca22010-02-26 05:06:18 +00001381 QualType ExpectedFunctionType;
1382 {
1383 const FunctionProtoType *Proto
1384 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00001385
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001386 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001387 ArgTypes.push_back(Context.VoidPtrTy);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001388 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1389 ArgTypes.push_back(Proto->getArgType(I));
1390
John McCalldb40c7f2010-12-14 08:05:40 +00001391 FunctionProtoType::ExtProtoInfo EPI;
1392 EPI.Variadic = Proto->isVariadic();
1393
Douglas Gregor6642ca22010-02-26 05:06:18 +00001394 ExpectedFunctionType
1395 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
John McCalldb40c7f2010-12-14 08:05:40 +00001396 ArgTypes.size(), EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001397 }
1398
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001399 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00001400 DEnd = FoundDelete.end();
1401 D != DEnd; ++D) {
1402 FunctionDecl *Fn = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001403 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6642ca22010-02-26 05:06:18 +00001404 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1405 // Perform template argument deduction to try to match the
1406 // expected function type.
1407 TemplateDeductionInfo Info(Context, StartLoc);
1408 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1409 continue;
1410 } else
1411 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1412
1413 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00001414 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001415 }
1416 } else {
1417 // C++ [expr.new]p20:
1418 // [...] Any non-placement deallocation function matches a
1419 // non-placement allocation function. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001420 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00001421 DEnd = FoundDelete.end();
1422 D != DEnd; ++D) {
1423 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1424 if (isNonPlacementDeallocationFunction(Fn))
John McCalla0296f72010-03-19 07:35:19 +00001425 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001426 }
1427 }
1428
1429 // C++ [expr.new]p20:
1430 // [...] If the lookup finds a single matching deallocation
1431 // function, that function will be called; otherwise, no
1432 // deallocation function will be called.
1433 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00001434 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00001435
1436 // C++0x [expr.new]p20:
1437 // If the lookup finds the two-parameter form of a usual
1438 // deallocation function (3.7.4.2) and that function, considered
1439 // as a placement deallocation function, would have been
1440 // selected as a match for the allocation function, the program
1441 // is ill-formed.
1442 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1443 isNonPlacementDeallocationFunction(OperatorDelete)) {
1444 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001445 << SourceRange(PlaceArgs[0]->getLocStart(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00001446 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1447 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1448 << DeleteName;
John McCallfb6f5262010-03-18 08:19:33 +00001449 } else {
1450 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCalla0296f72010-03-19 07:35:19 +00001451 Matches[0].first);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001452 }
1453 }
1454
Sebastian Redlfaf68082008-12-03 20:26:15 +00001455 return false;
1456}
1457
Sebastian Redl33a31012008-12-04 22:20:51 +00001458/// FindAllocationOverload - Find an fitting overload for the allocation
1459/// function in the specified scope.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001460bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1461 DeclarationName Name, Expr** Args,
1462 unsigned NumArgs, DeclContext *Ctx,
Alexis Hunt1f69a022011-05-12 22:46:29 +00001463 bool AllowMissing, FunctionDecl *&Operator,
1464 bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00001465 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1466 LookupQualifiedName(R, Ctx);
John McCall9f3059a2009-10-09 21:13:30 +00001467 if (R.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001468 if (AllowMissing || !Diagnose)
Sebastian Redl33a31012008-12-04 22:20:51 +00001469 return false;
Sebastian Redl33a31012008-12-04 22:20:51 +00001470 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00001471 << Name << Range;
Sebastian Redl33a31012008-12-04 22:20:51 +00001472 }
1473
John McCallfb6f5262010-03-18 08:19:33 +00001474 if (R.isAmbiguous())
1475 return true;
1476
1477 R.suppressDiagnostics();
John McCall9f3059a2009-10-09 21:13:30 +00001478
John McCallbc077cf2010-02-08 23:07:23 +00001479 OverloadCandidateSet Candidates(StartLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001480 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor80a6cc52009-09-30 00:03:47 +00001481 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor55297ac2008-12-23 00:26:44 +00001482 // Even member operator new/delete are implicitly treated as
1483 // static, so don't use AddMemberCandidate.
John McCalla0296f72010-03-19 07:35:19 +00001484 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth93538422010-02-03 11:02:14 +00001485
John McCalla0296f72010-03-19 07:35:19 +00001486 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1487 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth93538422010-02-03 11:02:14 +00001488 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1489 Candidates,
1490 /*SuppressUserConversions=*/false);
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001491 continue;
Chandler Carruth93538422010-02-03 11:02:14 +00001492 }
1493
John McCalla0296f72010-03-19 07:35:19 +00001494 FunctionDecl *Fn = cast<FunctionDecl>(D);
1495 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth93538422010-02-03 11:02:14 +00001496 /*SuppressUserConversions=*/false);
Sebastian Redl33a31012008-12-04 22:20:51 +00001497 }
1498
1499 // Do the resolution.
1500 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00001501 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl33a31012008-12-04 22:20:51 +00001502 case OR_Success: {
1503 // Got one!
1504 FunctionDecl *FnDecl = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00001505 MarkDeclarationReferenced(StartLoc, FnDecl);
Sebastian Redl33a31012008-12-04 22:20:51 +00001506 // The first argument is size_t, and the first parameter must be size_t,
1507 // too. This is checked on declaration and can be assumed. (It can't be
1508 // asserted on, though, since invalid decls are left in there.)
John McCallfb6f5262010-03-18 08:19:33 +00001509 // Watch out for variadic allocator function.
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001510 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1511 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001512 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1513 FnDecl->getParamDecl(i));
1514
1515 if (!Diagnose && !CanPerformCopyInitialization(Entity, Owned(Args[i])))
1516 return true;
1517
John McCalldadc5752010-08-24 06:29:42 +00001518 ExprResult Result
Alexis Hunt1f69a022011-05-12 22:46:29 +00001519 = PerformCopyInitialization(Entity, SourceLocation(), Owned(Args[i]));
Douglas Gregor34147272010-03-26 20:35:59 +00001520 if (Result.isInvalid())
Sebastian Redl33a31012008-12-04 22:20:51 +00001521 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001522
Douglas Gregor34147272010-03-26 20:35:59 +00001523 Args[i] = Result.takeAs<Expr>();
Sebastian Redl33a31012008-12-04 22:20:51 +00001524 }
1525 Operator = FnDecl;
Alexis Hunt1f69a022011-05-12 22:46:29 +00001526 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl,
1527 Diagnose);
Sebastian Redl33a31012008-12-04 22:20:51 +00001528 return false;
1529 }
1530
1531 case OR_No_Viable_Function:
Chandler Carruthe6c88182011-06-08 10:26:03 +00001532 if (Diagnose) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001533 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1534 << Name << Range;
Chandler Carruthe6c88182011-06-08 10:26:03 +00001535 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1536 }
Sebastian Redl33a31012008-12-04 22:20:51 +00001537 return true;
1538
1539 case OR_Ambiguous:
Chandler Carruthe6c88182011-06-08 10:26:03 +00001540 if (Diagnose) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001541 Diag(StartLoc, diag::err_ovl_ambiguous_call)
1542 << Name << Range;
Chandler Carruthe6c88182011-06-08 10:26:03 +00001543 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
1544 }
Sebastian Redl33a31012008-12-04 22:20:51 +00001545 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001546
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001547 case OR_Deleted: {
Chandler Carruthe6c88182011-06-08 10:26:03 +00001548 if (Diagnose) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001549 Diag(StartLoc, diag::err_ovl_deleted_call)
1550 << Best->Function->isDeleted()
1551 << Name
1552 << getDeletedOrUnavailableSuffix(Best->Function)
1553 << Range;
Chandler Carruthe6c88182011-06-08 10:26:03 +00001554 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1555 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00001556 return true;
Sebastian Redl33a31012008-12-04 22:20:51 +00001557 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001558 }
David Blaikie83d382b2011-09-23 05:06:16 +00001559 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Sebastian Redl33a31012008-12-04 22:20:51 +00001560}
1561
1562
Sebastian Redlfaf68082008-12-03 20:26:15 +00001563/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1564/// delete. These are:
1565/// @code
Sebastian Redl37588092011-03-14 18:08:30 +00001566/// // C++03:
Sebastian Redlfaf68082008-12-03 20:26:15 +00001567/// void* operator new(std::size_t) throw(std::bad_alloc);
1568/// void* operator new[](std::size_t) throw(std::bad_alloc);
1569/// void operator delete(void *) throw();
1570/// void operator delete[](void *) throw();
Sebastian Redl37588092011-03-14 18:08:30 +00001571/// // C++0x:
1572/// void* operator new(std::size_t);
1573/// void* operator new[](std::size_t);
1574/// void operator delete(void *);
1575/// void operator delete[](void *);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001576/// @endcode
Sebastian Redl37588092011-03-14 18:08:30 +00001577/// C++0x operator delete is implicitly noexcept.
Sebastian Redlfaf68082008-12-03 20:26:15 +00001578/// Note that the placement and nothrow forms of new are *not* implicitly
1579/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00001580void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001581 if (GlobalNewDeleteDeclared)
1582 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001583
Douglas Gregor87f54062009-09-15 22:30:29 +00001584 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001585 // [...] The following allocation and deallocation functions (18.4) are
1586 // implicitly declared in global scope in each translation unit of a
Douglas Gregor87f54062009-09-15 22:30:29 +00001587 // program
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001588 //
Sebastian Redl37588092011-03-14 18:08:30 +00001589 // C++03:
Douglas Gregor87f54062009-09-15 22:30:29 +00001590 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001591 // void* operator new[](std::size_t) throw(std::bad_alloc);
1592 // void operator delete(void*) throw();
Douglas Gregor87f54062009-09-15 22:30:29 +00001593 // void operator delete[](void*) throw();
Sebastian Redl37588092011-03-14 18:08:30 +00001594 // C++0x:
1595 // void* operator new(std::size_t);
1596 // void* operator new[](std::size_t);
1597 // void operator delete(void*);
1598 // void operator delete[](void*);
Douglas Gregor87f54062009-09-15 22:30:29 +00001599 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001600 // These implicit declarations introduce only the function names operator
Douglas Gregor87f54062009-09-15 22:30:29 +00001601 // new, operator new[], operator delete, operator delete[].
1602 //
1603 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1604 // "std" or "bad_alloc" as necessary to form the exception specification.
1605 // However, we do not make these implicit declarations visible to name
1606 // lookup.
Sebastian Redl37588092011-03-14 18:08:30 +00001607 // Note that the C++0x versions of operator delete are deallocation functions,
1608 // and thus are implicitly noexcept.
1609 if (!StdBadAlloc && !getLangOptions().CPlusPlus0x) {
Douglas Gregor87f54062009-09-15 22:30:29 +00001610 // The "std::bad_alloc" class has not yet been declared, so build it
1611 // implicitly.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001612 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1613 getOrCreateStdNamespace(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001614 SourceLocation(), SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001615 &PP.getIdentifierTable().get("bad_alloc"),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001616 0);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00001617 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00001618 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001619
Sebastian Redlfaf68082008-12-03 20:26:15 +00001620 GlobalNewDeleteDeclared = true;
1621
1622 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1623 QualType SizeT = Context.getSizeType();
Nuno Lopes13c88c72009-12-16 16:59:22 +00001624 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001625
Sebastian Redlfaf68082008-12-03 20:26:15 +00001626 DeclareGlobalAllocationFunction(
1627 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001628 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001629 DeclareGlobalAllocationFunction(
1630 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001631 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001632 DeclareGlobalAllocationFunction(
1633 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1634 Context.VoidTy, VoidPtr);
1635 DeclareGlobalAllocationFunction(
1636 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1637 Context.VoidTy, VoidPtr);
1638}
1639
1640/// DeclareGlobalAllocationFunction - Declares a single implicit global
1641/// allocation function if it doesn't already exist.
1642void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopes13c88c72009-12-16 16:59:22 +00001643 QualType Return, QualType Argument,
1644 bool AddMallocAttr) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001645 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1646
1647 // Check if this function is already declared.
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001648 {
Douglas Gregor17eb26b2008-12-23 22:05:29 +00001649 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001650 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001651 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth93538422010-02-03 11:02:14 +00001652 // Only look at non-template functions, as it is the predefined,
1653 // non-templated allocation function we are trying to declare here.
1654 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1655 QualType InitialParamType =
Douglas Gregor684d7bd2009-12-22 23:42:49 +00001656 Context.getCanonicalType(
Chandler Carruth93538422010-02-03 11:02:14 +00001657 Func->getParamDecl(0)->getType().getUnqualifiedType());
1658 // FIXME: Do we need to check for default arguments here?
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00001659 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1660 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001661 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth93538422010-02-03 11:02:14 +00001662 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00001663 }
Chandler Carruth93538422010-02-03 11:02:14 +00001664 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00001665 }
1666 }
1667
Douglas Gregor87f54062009-09-15 22:30:29 +00001668 QualType BadAllocType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001669 bool HasBadAllocExceptionSpec
Douglas Gregor87f54062009-09-15 22:30:29 +00001670 = (Name.getCXXOverloadedOperator() == OO_New ||
1671 Name.getCXXOverloadedOperator() == OO_Array_New);
Sebastian Redl37588092011-03-14 18:08:30 +00001672 if (HasBadAllocExceptionSpec && !getLangOptions().CPlusPlus0x) {
Douglas Gregor87f54062009-09-15 22:30:29 +00001673 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00001674 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor87f54062009-09-15 22:30:29 +00001675 }
John McCalldb40c7f2010-12-14 08:05:40 +00001676
1677 FunctionProtoType::ExtProtoInfo EPI;
John McCalldb40c7f2010-12-14 08:05:40 +00001678 if (HasBadAllocExceptionSpec) {
Sebastian Redl37588092011-03-14 18:08:30 +00001679 if (!getLangOptions().CPlusPlus0x) {
1680 EPI.ExceptionSpecType = EST_Dynamic;
1681 EPI.NumExceptions = 1;
1682 EPI.Exceptions = &BadAllocType;
1683 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001684 } else {
Sebastian Redl37588092011-03-14 18:08:30 +00001685 EPI.ExceptionSpecType = getLangOptions().CPlusPlus0x ?
1686 EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00001687 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001688
John McCalldb40c7f2010-12-14 08:05:40 +00001689 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001690 FunctionDecl *Alloc =
Abramo Bagnaradff19302011-03-08 08:55:46 +00001691 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
1692 SourceLocation(), Name,
John McCall8e7d6562010-08-26 03:08:43 +00001693 FnType, /*TInfo=*/0, SC_None,
1694 SC_None, false, true);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001695 Alloc->setImplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001696
Nuno Lopes13c88c72009-12-16 16:59:22 +00001697 if (AddMallocAttr)
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001698 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001699
Sebastian Redlfaf68082008-12-03 20:26:15 +00001700 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001701 SourceLocation(), 0,
1702 Argument, /*TInfo=*/0,
1703 SC_None, SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00001704 Alloc->setParams(Param);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001705
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001706 // FIXME: Also add this declaration to the IdentifierResolver, but
1707 // make sure it is at the end of the chain to coincide with the
1708 // global scope.
John McCallcc14d1f2010-08-24 08:50:51 +00001709 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001710}
1711
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001712bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1713 DeclarationName Name,
Alexis Hunt1f69a022011-05-12 22:46:29 +00001714 FunctionDecl* &Operator, bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00001715 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001716 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00001717 LookupQualifiedName(Found, RD);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001718
John McCall27b18f82009-11-17 02:14:36 +00001719 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001720 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001721
Chandler Carruthb6f99172010-06-28 00:30:51 +00001722 Found.suppressDiagnostics();
1723
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001724 SmallVector<DeclAccessPair,4> Matches;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001725 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1726 F != FEnd; ++F) {
Chandler Carruth9b418232010-08-08 07:04:00 +00001727 NamedDecl *ND = (*F)->getUnderlyingDecl();
1728
1729 // Ignore template operator delete members from the check for a usual
1730 // deallocation function.
1731 if (isa<FunctionTemplateDecl>(ND))
1732 continue;
1733
1734 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall66a87592010-08-04 00:31:26 +00001735 Matches.push_back(F.getPair());
1736 }
1737
1738 // There's exactly one suitable operator; pick it.
1739 if (Matches.size() == 1) {
1740 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
Alexis Hunt1f69a022011-05-12 22:46:29 +00001741
1742 if (Operator->isDeleted()) {
1743 if (Diagnose) {
1744 Diag(StartLoc, diag::err_deleted_function_use);
1745 Diag(Operator->getLocation(), diag::note_unavailable_here) << true;
1746 }
1747 return true;
1748 }
1749
John McCall66a87592010-08-04 00:31:26 +00001750 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Alexis Hunt1f69a022011-05-12 22:46:29 +00001751 Matches[0], Diagnose);
John McCall66a87592010-08-04 00:31:26 +00001752 return false;
1753
1754 // We found multiple suitable operators; complain about the ambiguity.
1755 } else if (!Matches.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001756 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00001757 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1758 << Name << RD;
John McCall66a87592010-08-04 00:31:26 +00001759
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001760 for (SmallVectorImpl<DeclAccessPair>::iterator
Alexis Huntf91729462011-05-12 22:46:25 +00001761 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1762 Diag((*F)->getUnderlyingDecl()->getLocation(),
1763 diag::note_member_declared_here) << Name;
1764 }
John McCall66a87592010-08-04 00:31:26 +00001765 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001766 }
1767
1768 // We did find operator delete/operator delete[] declarations, but
1769 // none of them were suitable.
1770 if (!Found.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001771 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00001772 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1773 << Name << RD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001774
Alexis Huntf91729462011-05-12 22:46:25 +00001775 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1776 F != FEnd; ++F)
1777 Diag((*F)->getUnderlyingDecl()->getLocation(),
1778 diag::note_member_declared_here) << Name;
1779 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001780 return true;
1781 }
1782
1783 // Look for a global declaration.
1784 DeclareGlobalNewDelete();
1785 DeclContext *TUDecl = Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001786
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001787 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1788 Expr* DeallocArgs[1];
1789 DeallocArgs[0] = &Null;
1790 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
Alexis Hunt1f69a022011-05-12 22:46:29 +00001791 DeallocArgs, 1, TUDecl, !Diagnose,
1792 Operator, Diagnose))
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001793 return true;
1794
1795 assert(Operator && "Did not find a deallocation function!");
1796 return false;
1797}
1798
Sebastian Redlbd150f42008-11-21 19:14:01 +00001799/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1800/// @code ::delete ptr; @endcode
1801/// or
1802/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00001803ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001804Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley01296292011-04-08 18:41:53 +00001805 bool ArrayForm, Expr *ExE) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001806 // C++ [expr.delete]p1:
1807 // The operand shall have a pointer type, or a class type having a single
1808 // conversion function to a pointer type. The result has type void.
1809 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00001810 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1811
John Wiegley01296292011-04-08 18:41:53 +00001812 ExprResult Ex = Owned(ExE);
Anders Carlssona471db02009-08-16 20:29:29 +00001813 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00001814 bool ArrayFormAsWritten = ArrayForm;
John McCall284c48f2011-01-27 09:37:56 +00001815 bool UsualArrayDeleteWantsSize = false;
Mike Stump11289f42009-09-09 15:08:12 +00001816
John Wiegley01296292011-04-08 18:41:53 +00001817 if (!Ex.get()->isTypeDependent()) {
1818 QualType Type = Ex.get()->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00001819
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001820 if (const RecordType *Record = Type->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001821 if (RequireCompleteType(StartLoc, Type,
Douglas Gregorf65f4902010-07-29 14:44:35 +00001822 PDiag(diag::err_delete_incomplete_class_type)))
1823 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001824
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001825 SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
John McCallda4458e2010-03-31 01:36:47 +00001826
Fariborz Jahanianb54ccb22009-09-11 21:44:33 +00001827 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001828 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001829 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001830 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00001831 NamedDecl *D = I.getDecl();
1832 if (isa<UsingShadowDecl>(D))
1833 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1834
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001835 // Skip over templated conversion functions; they aren't considered.
John McCallda4458e2010-03-31 01:36:47 +00001836 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001837 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001838
John McCallda4458e2010-03-31 01:36:47 +00001839 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001840
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001841 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1842 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00001843 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001844 ObjectPtrConversions.push_back(Conv);
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001845 }
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001846 if (ObjectPtrConversions.size() == 1) {
1847 // We have a single conversion to a pointer-to-object type. Perform
1848 // that conversion.
John McCallda4458e2010-03-31 01:36:47 +00001849 // TODO: don't redo the conversion calculation.
John Wiegley01296292011-04-08 18:41:53 +00001850 ExprResult Res =
1851 PerformImplicitConversion(Ex.get(),
John McCallda4458e2010-03-31 01:36:47 +00001852 ObjectPtrConversions.front()->getConversionType(),
John Wiegley01296292011-04-08 18:41:53 +00001853 AA_Converting);
1854 if (Res.isUsable()) {
1855 Ex = move(Res);
1856 Type = Ex.get()->getType();
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001857 }
1858 }
1859 else if (ObjectPtrConversions.size() > 1) {
1860 Diag(StartLoc, diag::err_ambiguous_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00001861 << Type << Ex.get()->getSourceRange();
John McCallda4458e2010-03-31 01:36:47 +00001862 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1863 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001864 return ExprError();
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001865 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001866 }
1867
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001868 if (!Type->isPointerType())
1869 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00001870 << Type << Ex.get()->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001871
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001872 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmanae4280f2011-07-26 22:25:31 +00001873 QualType PointeeElem = Context.getBaseElementType(Pointee);
1874
1875 if (unsigned AddressSpace = Pointee.getAddressSpace())
1876 return Diag(Ex.get()->getLocStart(),
1877 diag::err_address_space_qualified_delete)
1878 << Pointee.getUnqualifiedType() << AddressSpace;
1879
1880 CXXRecordDecl *PointeeRD = 0;
Douglas Gregorbb3348e2010-05-24 17:01:56 +00001881 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001882 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregorbb3348e2010-05-24 17:01:56 +00001883 // effectively bans deletion of "void*". However, most compilers support
1884 // this, so we treat it as a warning unless we're in a SFINAE context.
1885 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley01296292011-04-08 18:41:53 +00001886 << Type << Ex.get()->getSourceRange();
Eli Friedmanae4280f2011-07-26 22:25:31 +00001887 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001888 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00001889 << Type << Ex.get()->getSourceRange());
Eli Friedmanae4280f2011-07-26 22:25:31 +00001890 } else if (!Pointee->isDependentType()) {
1891 if (!RequireCompleteType(StartLoc, Pointee,
1892 PDiag(diag::warn_delete_incomplete)
1893 << Ex.get()->getSourceRange())) {
1894 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
1895 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
1896 }
1897 }
1898
Abramo Bagnarad4756b92011-11-16 15:42:13 +00001899 // Perform lvalue-to-rvalue cast, if needed.
1900 Ex = DefaultLvalueConversion(Ex.take());
1901
Douglas Gregor98496dc2009-09-29 21:38:53 +00001902 // C++ [expr.delete]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001903 // [Note: a pointer to a const type can be the operand of a
1904 // delete-expression; it is not necessary to cast away the constness
1905 // (5.2.11) of the pointer expression before it is used as the operand
Douglas Gregor98496dc2009-09-29 21:38:53 +00001906 // of the delete-expression. ]
John McCall31168b02011-06-15 23:02:42 +00001907 if (!Context.hasSameType(Ex.get()->getType(), Context.VoidPtrTy))
Abramo Bagnarad4756b92011-11-16 15:42:13 +00001908 Ex = Owned(ImplicitCastExpr::Create(Context, Context.VoidPtrTy,
1909 CK_BitCast, Ex.take(), 0, VK_RValue));
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00001910
1911 if (Pointee->isArrayType() && !ArrayForm) {
1912 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley01296292011-04-08 18:41:53 +00001913 << Type << Ex.get()->getSourceRange()
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00001914 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1915 ArrayForm = true;
1916 }
1917
Anders Carlssona471db02009-08-16 20:29:29 +00001918 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1919 ArrayForm ? OO_Array_Delete : OO_Delete);
1920
Eli Friedmanae4280f2011-07-26 22:25:31 +00001921 if (PointeeRD) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001922 if (!UseGlobal &&
Eli Friedmanae4280f2011-07-26 22:25:31 +00001923 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
1924 OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00001925 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001926
John McCall284c48f2011-01-27 09:37:56 +00001927 // If we're allocating an array of records, check whether the
1928 // usual operator delete[] has a size_t parameter.
1929 if (ArrayForm) {
1930 // If the user specifically asked to use the global allocator,
1931 // we'll need to do the lookup into the class.
1932 if (UseGlobal)
1933 UsualArrayDeleteWantsSize =
1934 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
1935
1936 // Otherwise, the usual operator delete[] should be the
1937 // function we just found.
1938 else if (isa<CXXMethodDecl>(OperatorDelete))
1939 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
1940 }
1941
Eli Friedmanae4280f2011-07-26 22:25:31 +00001942 if (!PointeeRD->hasTrivialDestructor())
1943 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Mike Stump11289f42009-09-09 15:08:12 +00001944 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001945 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001946 DiagnoseUseOfDecl(Dtor, StartLoc);
1947 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00001948
1949 // C++ [expr.delete]p3:
1950 // In the first alternative (delete object), if the static type of the
1951 // object to be deleted is different from its dynamic type, the static
1952 // type shall be a base class of the dynamic type of the object to be
1953 // deleted and the static type shall have a virtual destructor or the
1954 // behavior is undefined.
1955 //
1956 // Note: a final class cannot be derived from, no issue there
Eli Friedman1b71a222011-07-26 23:27:24 +00001957 if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) {
Eli Friedmanae4280f2011-07-26 22:25:31 +00001958 CXXDestructorDecl *dtor = PointeeRD->getDestructor();
Eli Friedman1b71a222011-07-26 23:27:24 +00001959 if (dtor && !dtor->isVirtual()) {
1960 if (PointeeRD->isAbstract()) {
1961 // If the class is abstract, we warn by default, because we're
1962 // sure the code has undefined behavior.
1963 Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor)
1964 << PointeeElem;
1965 } else if (!ArrayForm) {
1966 // Otherwise, if this is not an array delete, it's a bit suspect,
1967 // but not necessarily wrong.
1968 Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
1969 }
1970 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00001971 }
John McCall31168b02011-06-15 23:02:42 +00001972
1973 } else if (getLangOptions().ObjCAutoRefCount &&
1974 PointeeElem->isObjCLifetimeType() &&
1975 (PointeeElem.getObjCLifetime() == Qualifiers::OCL_Strong ||
1976 PointeeElem.getObjCLifetime() == Qualifiers::OCL_Weak) &&
1977 ArrayForm) {
1978 Diag(StartLoc, diag::warn_err_new_delete_object_array)
1979 << 1 << PointeeElem;
Anders Carlssona471db02009-08-16 20:29:29 +00001980 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001981
Anders Carlssona471db02009-08-16 20:29:29 +00001982 if (!OperatorDelete) {
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001983 // Look for a global declaration.
Anders Carlssona471db02009-08-16 20:29:29 +00001984 DeclareGlobalNewDelete();
1985 DeclContext *TUDecl = Context.getTranslationUnitDecl();
John Wiegley01296292011-04-08 18:41:53 +00001986 Expr *Arg = Ex.get();
Mike Stump11289f42009-09-09 15:08:12 +00001987 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
John Wiegley01296292011-04-08 18:41:53 +00001988 &Arg, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssona471db02009-08-16 20:29:29 +00001989 OperatorDelete))
1990 return ExprError();
1991 }
Mike Stump11289f42009-09-09 15:08:12 +00001992
John McCall0f55a032010-04-20 02:18:25 +00001993 MarkDeclarationReferenced(StartLoc, OperatorDelete);
John McCall284c48f2011-01-27 09:37:56 +00001994
Douglas Gregorfa778132011-02-01 15:50:11 +00001995 // Check access and ambiguity of operator delete and destructor.
Eli Friedmanae4280f2011-07-26 22:25:31 +00001996 if (PointeeRD) {
1997 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
John Wiegley01296292011-04-08 18:41:53 +00001998 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregorfa778132011-02-01 15:50:11 +00001999 PDiag(diag::err_access_dtor) << PointeeElem);
2000 }
2001 }
2002
Sebastian Redlbd150f42008-11-21 19:14:01 +00002003 }
2004
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002005 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
John McCall284c48f2011-01-27 09:37:56 +00002006 ArrayFormAsWritten,
2007 UsualArrayDeleteWantsSize,
John Wiegley01296292011-04-08 18:41:53 +00002008 OperatorDelete, Ex.take(), StartLoc));
Sebastian Redlbd150f42008-11-21 19:14:01 +00002009}
2010
Douglas Gregor633caca2009-11-23 23:44:04 +00002011/// \brief Check the use of the given variable as a C++ condition in an if,
2012/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00002013ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00002014 SourceLocation StmtLoc,
2015 bool ConvertToBoolean) {
Douglas Gregor633caca2009-11-23 23:44:04 +00002016 QualType T = ConditionVar->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002017
Douglas Gregor633caca2009-11-23 23:44:04 +00002018 // C++ [stmt.select]p2:
2019 // The declarator shall not specify a function or an array.
2020 if (T->isFunctionType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002021 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00002022 diag::err_invalid_use_of_function_type)
2023 << ConditionVar->getSourceRange());
2024 else if (T->isArrayType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002025 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00002026 diag::err_invalid_use_of_array_type)
2027 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00002028
John Wiegley01296292011-04-08 18:41:53 +00002029 ExprResult Condition =
2030 Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
Douglas Gregorea972d32011-02-28 21:54:11 +00002031 ConditionVar,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002032 ConditionVar->getLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00002033 ConditionVar->getType().getNonReferenceType(),
John Wiegley01296292011-04-08 18:41:53 +00002034 VK_LValue));
Eli Friedman2dfa7932012-01-16 21:00:51 +00002035
2036 MarkDeclarationReferenced(ConditionVar->getLocation(), ConditionVar);
2037
John Wiegley01296292011-04-08 18:41:53 +00002038 if (ConvertToBoolean) {
2039 Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
2040 if (Condition.isInvalid())
2041 return ExprError();
2042 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002043
John Wiegley01296292011-04-08 18:41:53 +00002044 return move(Condition);
Douglas Gregor633caca2009-11-23 23:44:04 +00002045}
2046
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00002047/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
John Wiegley01296292011-04-08 18:41:53 +00002048ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00002049 // C++ 6.4p4:
2050 // The value of a condition that is an initialized declaration in a statement
2051 // other than a switch statement is the value of the declared variable
2052 // implicitly converted to type bool. If that conversion is ill-formed, the
2053 // program is ill-formed.
2054 // The value of a condition that is an expression is the value of the
2055 // expression, implicitly converted to bool.
2056 //
Douglas Gregor5fb53972009-01-14 15:45:31 +00002057 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00002058}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00002059
2060/// Helper function to determine whether this is the (deprecated) C++
2061/// conversion from a string literal to a pointer to non-const char or
2062/// non-const wchar_t (for narrow and wide string literals,
2063/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00002064bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00002065Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
2066 // Look inside the implicit cast, if it exists.
2067 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
2068 From = Cast->getSubExpr();
2069
2070 // A string literal (2.13.4) that is not a wide string literal can
2071 // be converted to an rvalue of type "pointer to char"; a wide
2072 // string literal can be converted to an rvalue of type "pointer
2073 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00002074 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002075 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00002076 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00002077 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00002078 // This conversion is considered only when there is an
2079 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregorfb65e592011-07-27 05:40:30 +00002080 if (!ToPtrType->getPointeeType().hasQualifiers()) {
2081 switch (StrLit->getKind()) {
2082 case StringLiteral::UTF8:
2083 case StringLiteral::UTF16:
2084 case StringLiteral::UTF32:
2085 // We don't allow UTF literals to be implicitly converted
2086 break;
2087 case StringLiteral::Ascii:
2088 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
2089 ToPointeeType->getKind() == BuiltinType::Char_S);
2090 case StringLiteral::Wide:
2091 return ToPointeeType->isWideCharType();
2092 }
2093 }
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00002094 }
2095
2096 return false;
2097}
Douglas Gregor39c16d42008-10-24 04:54:22 +00002098
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002099static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00002100 SourceLocation CastLoc,
2101 QualType Ty,
2102 CastKind Kind,
2103 CXXMethodDecl *Method,
John McCall30909032011-09-21 08:36:56 +00002104 DeclAccessPair FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002105 bool HadMultipleCandidates,
John McCalle3027922010-08-25 11:45:40 +00002106 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00002107 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002108 default: llvm_unreachable("Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00002109 case CK_ConstructorConversion: {
Douglas Gregorc7a31072011-10-10 22:41:00 +00002110 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
John McCall37ad5512010-08-23 06:44:23 +00002111 ASTOwningVector<Expr*> ConstructorArgs(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002112
Douglas Gregorc7a31072011-10-10 22:41:00 +00002113 if (S.CompleteConstructorCall(Constructor,
John McCallfaf5fb42010-08-26 23:41:50 +00002114 MultiExprArg(&From, 1),
Douglas Gregora4253922010-04-16 22:17:36 +00002115 CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00002116 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002117
Douglas Gregorc7a31072011-10-10 22:41:00 +00002118 S.CheckConstructorAccess(CastLoc, Constructor, Constructor->getAccess(),
2119 S.PDiag(diag::err_access_ctor));
2120
2121 ExprResult Result
2122 = S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2123 move_arg(ConstructorArgs),
2124 HadMultipleCandidates, /*ZeroInit*/ false,
2125 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00002126 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00002127 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002128
Douglas Gregora4253922010-04-16 22:17:36 +00002129 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
2130 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002131
John McCalle3027922010-08-25 11:45:40 +00002132 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00002133 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002134
Douglas Gregora4253922010-04-16 22:17:36 +00002135 // Create an implicit call expr that calls it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002136 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method,
2137 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00002138 if (Result.isInvalid())
2139 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00002140 // Record usage of conversion in an implicit cast.
2141 Result = S.Owned(ImplicitCastExpr::Create(S.Context,
2142 Result.get()->getType(),
2143 CK_UserDefinedConversion,
2144 Result.get(), 0,
2145 Result.get()->getValueKind()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002146
John McCall30909032011-09-21 08:36:56 +00002147 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ 0, FoundDecl);
2148
Douglas Gregor668443e2011-01-20 00:18:04 +00002149 return S.MaybeBindToTemporary(Result.get());
Douglas Gregora4253922010-04-16 22:17:36 +00002150 }
2151 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002152}
Douglas Gregora4253922010-04-16 22:17:36 +00002153
Douglas Gregor5fb53972009-01-14 15:45:31 +00002154/// PerformImplicitConversion - Perform an implicit conversion of the
2155/// expression From to the type ToType using the pre-computed implicit
John Wiegley01296292011-04-08 18:41:53 +00002156/// conversion sequence ICS. Returns the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002157/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002158/// used in the error message.
John Wiegley01296292011-04-08 18:41:53 +00002159ExprResult
2160Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002161 const ImplicitConversionSequence &ICS,
John McCall31168b02011-06-15 23:02:42 +00002162 AssignmentAction Action,
2163 CheckedConversionKind CCK) {
John McCall0d1da222010-01-12 00:44:57 +00002164 switch (ICS.getKind()) {
John Wiegley01296292011-04-08 18:41:53 +00002165 case ImplicitConversionSequence::StandardConversion: {
Richard Smith507840d2011-11-29 22:48:16 +00002166 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
2167 Action, CCK);
John Wiegley01296292011-04-08 18:41:53 +00002168 if (Res.isInvalid())
2169 return ExprError();
2170 From = Res.take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002171 break;
John Wiegley01296292011-04-08 18:41:53 +00002172 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00002173
Anders Carlsson110b07b2009-09-15 06:28:28 +00002174 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002175
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00002176 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00002177 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00002178 QualType BeforeToType;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00002179 assert(FD && "FIXME: aggregate initialization from init list");
Anders Carlsson110b07b2009-09-15 06:28:28 +00002180 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00002181 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002182
Anders Carlsson110b07b2009-09-15 06:28:28 +00002183 // If the user-defined conversion is specified by a conversion function,
2184 // the initial standard conversion sequence converts the source type to
2185 // the implicit object parameter of the conversion function.
2186 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00002187 } else {
2188 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00002189 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002190 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00002191 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002192 // If the user-defined conversion is specified by a constructor, the
Fariborz Jahanian55824512009-11-06 00:23:08 +00002193 // initial standard conversion sequence converts the source type to the
2194 // type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00002195 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
2196 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002197 }
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00002198 // Watch out for elipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00002199 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley01296292011-04-08 18:41:53 +00002200 ExprResult Res =
Richard Smith507840d2011-11-29 22:48:16 +00002201 PerformImplicitConversion(From, BeforeToType,
2202 ICS.UserDefined.Before, AA_Converting,
2203 CCK);
John Wiegley01296292011-04-08 18:41:53 +00002204 if (Res.isInvalid())
2205 return ExprError();
2206 From = Res.take();
Fariborz Jahanian55824512009-11-06 00:23:08 +00002207 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002208
2209 ExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00002210 = BuildCXXCastArgument(*this,
2211 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00002212 ToType.getNonReferenceType(),
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002213 CastKind, cast<CXXMethodDecl>(FD),
2214 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002215 ICS.UserDefined.HadMultipleCandidates,
John McCallb268a282010-08-23 23:25:46 +00002216 From);
Anders Carlssone9766d52009-09-09 21:33:21 +00002217
2218 if (CastArg.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00002219 return ExprError();
Eli Friedmane96f1d32009-11-27 04:41:50 +00002220
John Wiegley01296292011-04-08 18:41:53 +00002221 From = CastArg.take();
Eli Friedmane96f1d32009-11-27 04:41:50 +00002222
Richard Smith507840d2011-11-29 22:48:16 +00002223 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
2224 AA_Converting, CCK);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00002225 }
John McCall0d1da222010-01-12 00:44:57 +00002226
2227 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00002228 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00002229 PDiag(diag::err_typecheck_ambiguous_condition)
2230 << From->getSourceRange());
John Wiegley01296292011-04-08 18:41:53 +00002231 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002232
Douglas Gregor39c16d42008-10-24 04:54:22 +00002233 case ImplicitConversionSequence::EllipsisConversion:
David Blaikie83d382b2011-09-23 05:06:16 +00002234 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00002235
2236 case ImplicitConversionSequence::BadConversion:
John Wiegley01296292011-04-08 18:41:53 +00002237 return ExprError();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002238 }
2239
2240 // Everything went well.
John Wiegley01296292011-04-08 18:41:53 +00002241 return Owned(From);
Douglas Gregor39c16d42008-10-24 04:54:22 +00002242}
2243
Richard Smith507840d2011-11-29 22:48:16 +00002244/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor39c16d42008-10-24 04:54:22 +00002245/// expression From to the type ToType by following the standard
John Wiegley01296292011-04-08 18:41:53 +00002246/// conversion sequence SCS. Returns the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00002247/// expression. Flavor is the context in which we're performing this
2248/// conversion, for use in error messages.
John Wiegley01296292011-04-08 18:41:53 +00002249ExprResult
Richard Smith507840d2011-11-29 22:48:16 +00002250Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002251 const StandardConversionSequence& SCS,
John McCall31168b02011-06-15 23:02:42 +00002252 AssignmentAction Action,
2253 CheckedConversionKind CCK) {
2254 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
2255
Mike Stump87c57ac2009-05-16 07:39:55 +00002256 // Overall FIXME: we are recomputing too many types here and doing far too
2257 // much extra work. What this means is that we need to keep track of more
2258 // information that is computed when we try the implicit conversion initially,
2259 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00002260 QualType FromType = From->getType();
John McCall31168b02011-06-15 23:02:42 +00002261
Douglas Gregor2fe98832008-11-03 19:09:14 +00002262 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00002263 // FIXME: When can ToType be a reference type?
2264 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00002265 if (SCS.Second == ICK_Derived_To_Base) {
John McCall37ad5512010-08-23 06:44:23 +00002266 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanian49850df2009-09-25 18:59:21 +00002267 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCall37ad5512010-08-23 06:44:23 +00002268 MultiExprArg(*this, &From, 1),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002269 /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00002270 ConstructorArgs))
John Wiegley01296292011-04-08 18:41:53 +00002271 return ExprError();
2272 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2273 ToType, SCS.CopyConstructor,
2274 move_arg(ConstructorArgs),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002275 /*HadMultipleCandidates*/ false,
John Wiegley01296292011-04-08 18:41:53 +00002276 /*ZeroInit*/ false,
2277 CXXConstructExpr::CK_Complete,
2278 SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00002279 }
John Wiegley01296292011-04-08 18:41:53 +00002280 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2281 ToType, SCS.CopyConstructor,
2282 MultiExprArg(*this, &From, 1),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002283 /*HadMultipleCandidates*/ false,
John Wiegley01296292011-04-08 18:41:53 +00002284 /*ZeroInit*/ false,
2285 CXXConstructExpr::CK_Complete,
2286 SourceRange());
Douglas Gregor2fe98832008-11-03 19:09:14 +00002287 }
2288
Douglas Gregor980fb162010-04-29 18:24:40 +00002289 // Resolve overloaded function references.
2290 if (Context.hasSameType(FromType, Context.OverloadTy)) {
2291 DeclAccessPair Found;
2292 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2293 true, Found);
2294 if (!Fn)
John Wiegley01296292011-04-08 18:41:53 +00002295 return ExprError();
Douglas Gregor980fb162010-04-29 18:24:40 +00002296
2297 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
John Wiegley01296292011-04-08 18:41:53 +00002298 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002299
Douglas Gregor980fb162010-04-29 18:24:40 +00002300 From = FixOverloadedFunctionReference(From, Found, Fn);
2301 FromType = From->getType();
2302 }
2303
Richard Smith507840d2011-11-29 22:48:16 +00002304 // Perform the first implicit conversion.
Douglas Gregor39c16d42008-10-24 04:54:22 +00002305 switch (SCS.First) {
2306 case ICK_Identity:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002307 // Nothing to do.
2308 break;
2309
John McCall34376a62010-12-04 03:47:34 +00002310 case ICK_Lvalue_To_Rvalue:
John McCall526ab472011-10-25 17:37:35 +00002311 assert(From->getObjectKind() != OK_ObjCProperty);
John McCall34376a62010-12-04 03:47:34 +00002312 FromType = FromType.getUnqualifiedType();
2313 From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
2314 From, 0, VK_RValue);
2315 break;
2316
Douglas Gregor39c16d42008-10-24 04:54:22 +00002317 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00002318 FromType = Context.getArrayDecayedType(FromType);
Richard Smith507840d2011-11-29 22:48:16 +00002319 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
2320 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor171c45a2009-02-18 21:56:37 +00002321 break;
2322
2323 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002324 FromType = Context.getPointerType(FromType);
Richard Smith507840d2011-11-29 22:48:16 +00002325 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
2326 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002327 break;
2328
2329 default:
David Blaikie83d382b2011-09-23 05:06:16 +00002330 llvm_unreachable("Improper first standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00002331 }
2332
Richard Smith507840d2011-11-29 22:48:16 +00002333 // Perform the second implicit conversion
Douglas Gregor39c16d42008-10-24 04:54:22 +00002334 switch (SCS.Second) {
2335 case ICK_Identity:
Sebastian Redl5d431642009-10-10 12:04:10 +00002336 // If both sides are functions (or pointers/references to them), there could
2337 // be incompatible exception declarations.
2338 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00002339 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00002340 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00002341 break;
2342
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00002343 case ICK_NoReturn_Adjustment:
2344 // If both sides are functions (or pointers/references to them), there could
2345 // be incompatible exception declarations.
2346 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00002347 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002348
Richard Smith507840d2011-11-29 22:48:16 +00002349 From = ImpCastExprToType(From, ToType, CK_NoOp,
2350 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00002351 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002352
Douglas Gregor39c16d42008-10-24 04:54:22 +00002353 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002354 case ICK_Integral_Conversion:
Richard Smith507840d2011-11-29 22:48:16 +00002355 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
2356 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002357 break;
2358
2359 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002360 case ICK_Floating_Conversion:
Richard Smith507840d2011-11-29 22:48:16 +00002361 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
2362 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002363 break;
2364
2365 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00002366 case ICK_Complex_Conversion: {
2367 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2368 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2369 CastKind CK;
2370 if (FromEl->isRealFloatingType()) {
2371 if (ToEl->isRealFloatingType())
2372 CK = CK_FloatingComplexCast;
2373 else
2374 CK = CK_FloatingComplexToIntegralComplex;
2375 } else if (ToEl->isRealFloatingType()) {
2376 CK = CK_IntegralComplexToFloatingComplex;
2377 } else {
2378 CK = CK_IntegralComplexCast;
2379 }
Richard Smith507840d2011-11-29 22:48:16 +00002380 From = ImpCastExprToType(From, ToType, CK,
2381 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002382 break;
John McCall8cb679e2010-11-15 09:13:47 +00002383 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00002384
Douglas Gregor39c16d42008-10-24 04:54:22 +00002385 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00002386 if (ToType->isRealFloatingType())
Richard Smith507840d2011-11-29 22:48:16 +00002387 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
2388 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002389 else
Richard Smith507840d2011-11-29 22:48:16 +00002390 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
2391 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002392 break;
2393
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002394 case ICK_Compatible_Conversion:
Richard Smith507840d2011-11-29 22:48:16 +00002395 From = ImpCastExprToType(From, ToType, CK_NoOp,
2396 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002397 break;
2398
John McCall31168b02011-06-15 23:02:42 +00002399 case ICK_Writeback_Conversion:
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002400 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00002401 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002402 // Diagnose incompatible Objective-C conversions
Douglas Gregor2720dc62011-06-11 04:42:12 +00002403 if (Action == AA_Initializing || Action == AA_Assigning)
Fariborz Jahanian413e0642011-03-21 19:08:42 +00002404 Diag(From->getSourceRange().getBegin(),
2405 diag::ext_typecheck_convert_incompatible_pointer)
2406 << ToType << From->getType() << Action
Anna Zaks3b402712011-07-28 19:51:27 +00002407 << From->getSourceRange() << 0;
Fariborz Jahanian413e0642011-03-21 19:08:42 +00002408 else
2409 Diag(From->getSourceRange().getBegin(),
2410 diag::ext_typecheck_convert_incompatible_pointer)
2411 << From->getType() << ToType << Action
Anna Zaks3b402712011-07-28 19:51:27 +00002412 << From->getSourceRange() << 0;
John McCall31168b02011-06-15 23:02:42 +00002413
Douglas Gregor33823722011-06-11 01:09:30 +00002414 if (From->getType()->isObjCObjectPointerType() &&
2415 ToType->isObjCObjectPointerType())
2416 EmitRelatedResultTypeNote(From);
Fariborz Jahanianf2913402011-07-08 17:41:42 +00002417 }
2418 else if (getLangOptions().ObjCAutoRefCount &&
2419 !CheckObjCARCUnavailableWeakConversion(ToType,
2420 From->getType())) {
John McCall9c3467e2011-09-09 06:12:06 +00002421 if (Action == AA_Initializing)
2422 Diag(From->getSourceRange().getBegin(),
2423 diag::err_arc_weak_unavailable_assign);
2424 else
2425 Diag(From->getSourceRange().getBegin(),
2426 diag::err_arc_convesion_of_weak_unavailable)
2427 << (Action == AA_Casting) << From->getType() << ToType
2428 << From->getSourceRange();
2429 }
Fariborz Jahanianf2913402011-07-08 17:41:42 +00002430
John McCall8cb679e2010-11-15 09:13:47 +00002431 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00002432 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00002433 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00002434 return ExprError();
John McCallcd78e802011-09-10 01:16:55 +00002435
2436 // Make sure we extend blocks if necessary.
2437 // FIXME: doing this here is really ugly.
2438 if (Kind == CK_BlockPointerToObjCPointerCast) {
2439 ExprResult E = From;
2440 (void) PrepareCastToObjCObjectPointer(E);
2441 From = E.take();
2442 }
2443
Richard Smith507840d2011-11-29 22:48:16 +00002444 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2445 .take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002446 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002447 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002448
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002449 case ICK_Pointer_Member: {
John McCall8cb679e2010-11-15 09:13:47 +00002450 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00002451 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00002452 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00002453 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00002454 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00002455 return ExprError();
Richard Smith507840d2011-11-29 22:48:16 +00002456 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2457 .take();
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002458 break;
2459 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002460
Abramo Bagnara7ccce982011-04-07 09:26:19 +00002461 case ICK_Boolean_Conversion:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002462 // Perform half-to-boolean conversion via float.
2463 if (From->getType()->isHalfType()) {
2464 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).take();
2465 FromType = Context.FloatTy;
2466 }
2467
Richard Smith507840d2011-11-29 22:48:16 +00002468 From = ImpCastExprToType(From, Context.BoolTy,
2469 ScalarTypeToBooleanCastKind(FromType),
2470 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002471 break;
2472
Douglas Gregor88d292c2010-05-13 16:44:06 +00002473 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00002474 CXXCastPath BasePath;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002475 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00002476 ToType.getNonReferenceType(),
2477 From->getLocStart(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002478 From->getSourceRange(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00002479 &BasePath,
Douglas Gregor58281352011-01-27 00:58:17 +00002480 CStyle))
John Wiegley01296292011-04-08 18:41:53 +00002481 return ExprError();
Douglas Gregor88d292c2010-05-13 16:44:06 +00002482
Richard Smith507840d2011-11-29 22:48:16 +00002483 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
2484 CK_DerivedToBase, From->getValueKind(),
2485 &BasePath, CCK).take();
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00002486 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00002487 }
2488
Douglas Gregor46188682010-05-18 22:42:18 +00002489 case ICK_Vector_Conversion:
Richard Smith507840d2011-11-29 22:48:16 +00002490 From = ImpCastExprToType(From, ToType, CK_BitCast,
2491 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor46188682010-05-18 22:42:18 +00002492 break;
2493
2494 case ICK_Vector_Splat:
Richard Smith507840d2011-11-29 22:48:16 +00002495 From = ImpCastExprToType(From, ToType, CK_VectorSplat,
2496 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor46188682010-05-18 22:42:18 +00002497 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002498
Douglas Gregor46188682010-05-18 22:42:18 +00002499 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00002500 // Case 1. x -> _Complex y
2501 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2502 QualType ElType = ToComplex->getElementType();
2503 bool isFloatingComplex = ElType->isRealFloatingType();
2504
2505 // x -> y
2506 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2507 // do nothing
2508 } else if (From->getType()->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00002509 From = ImpCastExprToType(From, ElType,
2510 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
John McCall8cb679e2010-11-15 09:13:47 +00002511 } else {
2512 assert(From->getType()->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00002513 From = ImpCastExprToType(From, ElType,
2514 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
John McCall8cb679e2010-11-15 09:13:47 +00002515 }
2516 // y -> _Complex y
Richard Smith507840d2011-11-29 22:48:16 +00002517 From = ImpCastExprToType(From, ToType,
2518 isFloatingComplex ? CK_FloatingRealToComplex
2519 : CK_IntegralRealToComplex).take();
John McCall8cb679e2010-11-15 09:13:47 +00002520
2521 // Case 2. _Complex x -> y
2522 } else {
2523 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2524 assert(FromComplex);
2525
2526 QualType ElType = FromComplex->getElementType();
2527 bool isFloatingComplex = ElType->isRealFloatingType();
2528
2529 // _Complex x -> x
Richard Smith507840d2011-11-29 22:48:16 +00002530 From = ImpCastExprToType(From, ElType,
2531 isFloatingComplex ? CK_FloatingComplexToReal
2532 : CK_IntegralComplexToReal,
2533 VK_RValue, /*BasePath=*/0, CCK).take();
John McCall8cb679e2010-11-15 09:13:47 +00002534
2535 // x -> y
2536 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2537 // do nothing
2538 } else if (ToType->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00002539 From = ImpCastExprToType(From, ToType,
2540 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
2541 VK_RValue, /*BasePath=*/0, CCK).take();
John McCall8cb679e2010-11-15 09:13:47 +00002542 } else {
2543 assert(ToType->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00002544 From = ImpCastExprToType(From, ToType,
2545 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
2546 VK_RValue, /*BasePath=*/0, CCK).take();
John McCall8cb679e2010-11-15 09:13:47 +00002547 }
2548 }
Douglas Gregor46188682010-05-18 22:42:18 +00002549 break;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002550
2551 case ICK_Block_Pointer_Conversion: {
Richard Smith507840d2011-11-29 22:48:16 +00002552 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
2553 VK_RValue, /*BasePath=*/0, CCK).take();
John McCall31168b02011-06-15 23:02:42 +00002554 break;
2555 }
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002556
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00002557 case ICK_TransparentUnionConversion: {
John Wiegley01296292011-04-08 18:41:53 +00002558 ExprResult FromRes = Owned(From);
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00002559 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00002560 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
2561 if (FromRes.isInvalid())
2562 return ExprError();
2563 From = FromRes.take();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00002564 assert ((ConvTy == Sema::Compatible) &&
2565 "Improper transparent union conversion");
2566 (void)ConvTy;
2567 break;
2568 }
2569
Douglas Gregor46188682010-05-18 22:42:18 +00002570 case ICK_Lvalue_To_Rvalue:
2571 case ICK_Array_To_Pointer:
2572 case ICK_Function_To_Pointer:
2573 case ICK_Qualification:
2574 case ICK_Num_Conversion_Kinds:
David Blaikie83d382b2011-09-23 05:06:16 +00002575 llvm_unreachable("Improper second standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00002576 }
2577
2578 switch (SCS.Third) {
2579 case ICK_Identity:
2580 // Nothing to do.
2581 break;
2582
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002583 case ICK_Qualification: {
2584 // The qualification keeps the category of the inner expression, unless the
2585 // target type isn't a reference.
John McCall2536c6d2010-08-25 10:28:54 +00002586 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanbe4b3632011-09-27 21:58:52 +00002587 From->getValueKind() : VK_RValue;
Richard Smith507840d2011-11-29 22:48:16 +00002588 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
2589 CK_NoOp, VK, /*BasePath=*/0, CCK).take();
Douglas Gregore489a7d2010-02-28 18:30:25 +00002590
Douglas Gregore981bb02011-03-14 16:13:32 +00002591 if (SCS.DeprecatedStringLiteralToCharPtr &&
2592 !getLangOptions().WritableStrings)
Douglas Gregore489a7d2010-02-28 18:30:25 +00002593 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2594 << ToType.getNonReferenceType();
2595
Douglas Gregor39c16d42008-10-24 04:54:22 +00002596 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002597 }
2598
Douglas Gregor39c16d42008-10-24 04:54:22 +00002599 default:
David Blaikie83d382b2011-09-23 05:06:16 +00002600 llvm_unreachable("Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00002601 }
2602
John Wiegley01296292011-04-08 18:41:53 +00002603 return Owned(From);
Douglas Gregor39c16d42008-10-24 04:54:22 +00002604}
2605
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002606ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor54e5b132010-09-09 16:14:44 +00002607 SourceLocation KWLoc,
2608 ParsedType Ty,
2609 SourceLocation RParen) {
2610 TypeSourceInfo *TSInfo;
2611 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump11289f42009-09-09 15:08:12 +00002612
Douglas Gregor54e5b132010-09-09 16:14:44 +00002613 if (!TSInfo)
2614 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002615 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor54e5b132010-09-09 16:14:44 +00002616}
2617
Chandler Carruth8e172c62011-05-01 06:51:22 +00002618/// \brief Check the completeness of a type in a unary type trait.
2619///
2620/// If the particular type trait requires a complete type, tries to complete
2621/// it. If completing the type fails, a diagnostic is emitted and false
2622/// returned. If completing the type succeeds or no completion was required,
2623/// returns true.
2624static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S,
2625 UnaryTypeTrait UTT,
2626 SourceLocation Loc,
2627 QualType ArgTy) {
2628 // C++0x [meta.unary.prop]p3:
2629 // For all of the class templates X declared in this Clause, instantiating
2630 // that template with a template argument that is a class template
2631 // specialization may result in the implicit instantiation of the template
2632 // argument if and only if the semantics of X require that the argument
2633 // must be a complete type.
2634 // We apply this rule to all the type trait expressions used to implement
2635 // these class templates. We also try to follow any GCC documented behavior
2636 // in these expressions to ensure portability of standard libraries.
2637 switch (UTT) {
Chandler Carruth8e172c62011-05-01 06:51:22 +00002638 // is_complete_type somewhat obviously cannot require a complete type.
2639 case UTT_IsCompleteType:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00002640 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00002641
2642 // These traits are modeled on the type predicates in C++0x
2643 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
2644 // requiring a complete type, as whether or not they return true cannot be
2645 // impacted by the completeness of the type.
2646 case UTT_IsVoid:
2647 case UTT_IsIntegral:
2648 case UTT_IsFloatingPoint:
2649 case UTT_IsArray:
2650 case UTT_IsPointer:
2651 case UTT_IsLvalueReference:
2652 case UTT_IsRvalueReference:
2653 case UTT_IsMemberFunctionPointer:
2654 case UTT_IsMemberObjectPointer:
2655 case UTT_IsEnum:
2656 case UTT_IsUnion:
2657 case UTT_IsClass:
2658 case UTT_IsFunction:
2659 case UTT_IsReference:
2660 case UTT_IsArithmetic:
2661 case UTT_IsFundamental:
2662 case UTT_IsObject:
2663 case UTT_IsScalar:
2664 case UTT_IsCompound:
2665 case UTT_IsMemberPointer:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00002666 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00002667
2668 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
2669 // which requires some of its traits to have the complete type. However,
2670 // the completeness of the type cannot impact these traits' semantics, and
2671 // so they don't require it. This matches the comments on these traits in
2672 // Table 49.
2673 case UTT_IsConst:
2674 case UTT_IsVolatile:
2675 case UTT_IsSigned:
2676 case UTT_IsUnsigned:
2677 return true;
2678
2679 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
Chandler Carrutha62d8a52011-05-01 19:18:02 +00002680 // applied to a complete type.
Chandler Carruth8e172c62011-05-01 06:51:22 +00002681 case UTT_IsTrivial:
Alexis Huntd9a5cc12011-05-13 00:31:07 +00002682 case UTT_IsTriviallyCopyable:
Chandler Carruth8e172c62011-05-01 06:51:22 +00002683 case UTT_IsStandardLayout:
2684 case UTT_IsPOD:
2685 case UTT_IsLiteral:
2686 case UTT_IsEmpty:
2687 case UTT_IsPolymorphic:
2688 case UTT_IsAbstract:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00002689 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00002690
Douglas Gregordca70af2011-12-03 18:14:24 +00002691 // These traits require a complete type.
2692 case UTT_IsFinal:
2693
Chandler Carrutha62d8a52011-05-01 19:18:02 +00002694 // These trait expressions are designed to help implement predicates in
Chandler Carruth8e172c62011-05-01 06:51:22 +00002695 // [meta.unary.prop] despite not being named the same. They are specified
2696 // by both GCC and the Embarcadero C++ compiler, and require the complete
2697 // type due to the overarching C++0x type predicates being implemented
2698 // requiring the complete type.
2699 case UTT_HasNothrowAssign:
2700 case UTT_HasNothrowConstructor:
2701 case UTT_HasNothrowCopy:
2702 case UTT_HasTrivialAssign:
Alexis Huntf479f1b2011-05-09 18:22:59 +00002703 case UTT_HasTrivialDefaultConstructor:
Chandler Carruth8e172c62011-05-01 06:51:22 +00002704 case UTT_HasTrivialCopy:
2705 case UTT_HasTrivialDestructor:
2706 case UTT_HasVirtualDestructor:
2707 // Arrays of unknown bound are expressly allowed.
2708 QualType ElTy = ArgTy;
2709 if (ArgTy->isIncompleteArrayType())
2710 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
2711
2712 // The void type is expressly allowed.
2713 if (ElTy->isVoidType())
2714 return true;
2715
2716 return !S.RequireCompleteType(
2717 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleyd3522222011-04-28 02:06:46 +00002718 }
Chandler Carruth8b0cf1d2011-05-01 07:23:17 +00002719 llvm_unreachable("Type trait not handled by switch");
Chandler Carruth8e172c62011-05-01 06:51:22 +00002720}
2721
2722static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT,
2723 SourceLocation KeyLoc, QualType T) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00002724 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleyd3522222011-04-28 02:06:46 +00002725
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002726 ASTContext &C = Self.Context;
2727 switch(UTT) {
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002728 // Type trait expressions corresponding to the primary type category
2729 // predicates in C++0x [meta.unary.cat].
2730 case UTT_IsVoid:
2731 return T->isVoidType();
2732 case UTT_IsIntegral:
2733 return T->isIntegralType(C);
2734 case UTT_IsFloatingPoint:
2735 return T->isFloatingType();
2736 case UTT_IsArray:
2737 return T->isArrayType();
2738 case UTT_IsPointer:
2739 return T->isPointerType();
2740 case UTT_IsLvalueReference:
2741 return T->isLValueReferenceType();
2742 case UTT_IsRvalueReference:
2743 return T->isRValueReferenceType();
2744 case UTT_IsMemberFunctionPointer:
2745 return T->isMemberFunctionPointerType();
2746 case UTT_IsMemberObjectPointer:
2747 return T->isMemberDataPointerType();
2748 case UTT_IsEnum:
2749 return T->isEnumeralType();
Chandler Carruth100f3a92011-05-01 06:11:03 +00002750 case UTT_IsUnion:
Chandler Carruthaf858862011-05-01 09:29:58 +00002751 return T->isUnionType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002752 case UTT_IsClass:
Chandler Carruthaf858862011-05-01 09:29:58 +00002753 return T->isClassType() || T->isStructureType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002754 case UTT_IsFunction:
2755 return T->isFunctionType();
2756
2757 // Type trait expressions which correspond to the convenient composition
2758 // predicates in C++0x [meta.unary.comp].
2759 case UTT_IsReference:
2760 return T->isReferenceType();
2761 case UTT_IsArithmetic:
Chandler Carruthaf858862011-05-01 09:29:58 +00002762 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002763 case UTT_IsFundamental:
Chandler Carruthaf858862011-05-01 09:29:58 +00002764 return T->isFundamentalType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002765 case UTT_IsObject:
Chandler Carruthaf858862011-05-01 09:29:58 +00002766 return T->isObjectType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002767 case UTT_IsScalar:
John McCall31168b02011-06-15 23:02:42 +00002768 // Note: semantic analysis depends on Objective-C lifetime types to be
2769 // considered scalar types. However, such types do not actually behave
2770 // like scalar types at run time (since they may require retain/release
2771 // operations), so we report them as non-scalar.
2772 if (T->isObjCLifetimeType()) {
2773 switch (T.getObjCLifetime()) {
2774 case Qualifiers::OCL_None:
2775 case Qualifiers::OCL_ExplicitNone:
2776 return true;
2777
2778 case Qualifiers::OCL_Strong:
2779 case Qualifiers::OCL_Weak:
2780 case Qualifiers::OCL_Autoreleasing:
2781 return false;
2782 }
2783 }
2784
Chandler Carruth7ba7bd32011-05-01 09:29:55 +00002785 return T->isScalarType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002786 case UTT_IsCompound:
Chandler Carruthaf858862011-05-01 09:29:58 +00002787 return T->isCompoundType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002788 case UTT_IsMemberPointer:
2789 return T->isMemberPointerType();
2790
2791 // Type trait expressions which correspond to the type property predicates
2792 // in C++0x [meta.unary.prop].
2793 case UTT_IsConst:
2794 return T.isConstQualified();
2795 case UTT_IsVolatile:
2796 return T.isVolatileQualified();
2797 case UTT_IsTrivial:
John McCall31168b02011-06-15 23:02:42 +00002798 return T.isTrivialType(Self.Context);
Alexis Huntd9a5cc12011-05-13 00:31:07 +00002799 case UTT_IsTriviallyCopyable:
John McCall31168b02011-06-15 23:02:42 +00002800 return T.isTriviallyCopyableType(Self.Context);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002801 case UTT_IsStandardLayout:
2802 return T->isStandardLayoutType();
2803 case UTT_IsPOD:
John McCall31168b02011-06-15 23:02:42 +00002804 return T.isPODType(Self.Context);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002805 case UTT_IsLiteral:
2806 return T->isLiteralType();
2807 case UTT_IsEmpty:
2808 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2809 return !RD->isUnion() && RD->isEmpty();
2810 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002811 case UTT_IsPolymorphic:
Chandler Carruth100f3a92011-05-01 06:11:03 +00002812 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2813 return RD->isPolymorphic();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002814 return false;
2815 case UTT_IsAbstract:
Chandler Carruth100f3a92011-05-01 06:11:03 +00002816 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2817 return RD->isAbstract();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002818 return false;
Douglas Gregordca70af2011-12-03 18:14:24 +00002819 case UTT_IsFinal:
2820 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2821 return RD->hasAttr<FinalAttr>();
2822 return false;
John Wiegley65497cc2011-04-27 23:09:49 +00002823 case UTT_IsSigned:
2824 return T->isSignedIntegerType();
John Wiegley65497cc2011-04-27 23:09:49 +00002825 case UTT_IsUnsigned:
2826 return T->isUnsignedIntegerType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002827
2828 // Type trait expressions which query classes regarding their construction,
2829 // destruction, and copying. Rather than being based directly on the
2830 // related type predicates in the standard, they are specified by both
2831 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
2832 // specifications.
2833 //
2834 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
2835 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Alexis Huntf479f1b2011-05-09 18:22:59 +00002836 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002837 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2838 // If __is_pod (type) is true then the trait is true, else if type is
2839 // a cv class or union type (or array thereof) with a trivial default
2840 // constructor ([class.ctor]) then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00002841 if (T.isPODType(Self.Context))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002842 return true;
2843 if (const RecordType *RT =
2844 C.getBaseElementType(T)->getAs<RecordType>())
Alexis Huntf479f1b2011-05-09 18:22:59 +00002845 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDefaultConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002846 return false;
2847 case UTT_HasTrivialCopy:
2848 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2849 // If __is_pod (type) is true or type is a reference type then
2850 // the trait is true, else if type is a cv class or union type
2851 // with a trivial copy constructor ([class.copy]) then the trait
2852 // is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00002853 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002854 return true;
2855 if (const RecordType *RT = T->getAs<RecordType>())
2856 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2857 return false;
2858 case UTT_HasTrivialAssign:
2859 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2860 // If type is const qualified or is a reference type then the
2861 // trait is false. Otherwise if __is_pod (type) is true then the
2862 // trait is true, else if type is a cv class or union type with
2863 // a trivial copy assignment ([class.copy]) then the trait is
2864 // true, else it is false.
2865 // Note: the const and reference restrictions are interesting,
2866 // given that const and reference members don't prevent a class
2867 // from having a trivial copy assignment operator (but do cause
2868 // errors if the copy assignment operator is actually used, q.v.
2869 // [class.copy]p12).
2870
2871 if (C.getBaseElementType(T).isConstQualified())
2872 return false;
John McCall31168b02011-06-15 23:02:42 +00002873 if (T.isPODType(Self.Context))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002874 return true;
2875 if (const RecordType *RT = T->getAs<RecordType>())
2876 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2877 return false;
2878 case UTT_HasTrivialDestructor:
2879 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2880 // If __is_pod (type) is true or type is a reference type
2881 // then the trait is true, else if type is a cv class or union
2882 // type (or array thereof) with a trivial destructor
2883 // ([class.dtor]) then the trait is true, else it is
2884 // false.
John McCall31168b02011-06-15 23:02:42 +00002885 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002886 return true;
John McCall31168b02011-06-15 23:02:42 +00002887
2888 // Objective-C++ ARC: autorelease types don't require destruction.
2889 if (T->isObjCLifetimeType() &&
2890 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
2891 return true;
2892
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002893 if (const RecordType *RT =
2894 C.getBaseElementType(T)->getAs<RecordType>())
2895 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2896 return false;
2897 // TODO: Propagate nothrowness for implicitly declared special members.
2898 case UTT_HasNothrowAssign:
2899 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2900 // If type is const qualified or is a reference type then the
2901 // trait is false. Otherwise if __has_trivial_assign (type)
2902 // is true then the trait is true, else if type is a cv class
2903 // or union type with copy assignment operators that are known
2904 // not to throw an exception then the trait is true, else it is
2905 // false.
2906 if (C.getBaseElementType(T).isConstQualified())
2907 return false;
2908 if (T->isReferenceType())
2909 return false;
John McCall31168b02011-06-15 23:02:42 +00002910 if (T.isPODType(Self.Context) || T->isObjCLifetimeType())
2911 return true;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002912 if (const RecordType *RT = T->getAs<RecordType>()) {
2913 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2914 if (RD->hasTrivialCopyAssignment())
2915 return true;
2916
2917 bool FoundAssign = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002918 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redl058fc822010-09-14 23:40:14 +00002919 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2920 Sema::LookupOrdinaryName);
2921 if (Self.LookupQualifiedName(Res, RD)) {
Douglas Gregor6a0e23f2011-10-12 15:40:49 +00002922 Res.suppressDiagnostics();
Sebastian Redl058fc822010-09-14 23:40:14 +00002923 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2924 Op != OpEnd; ++Op) {
Douglas Gregor6a0e23f2011-10-12 15:40:49 +00002925 if (isa<FunctionTemplateDecl>(*Op))
2926 continue;
2927
Sebastian Redl058fc822010-09-14 23:40:14 +00002928 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2929 if (Operator->isCopyAssignmentOperator()) {
2930 FoundAssign = true;
2931 const FunctionProtoType *CPT
2932 = Operator->getType()->getAs<FunctionProtoType>();
Richard Smith938f40b2011-06-11 17:19:42 +00002933 if (CPT->getExceptionSpecType() == EST_Delayed)
2934 return false;
2935 if (!CPT->isNothrow(Self.Context))
2936 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002937 }
2938 }
2939 }
Douglas Gregor6a0e23f2011-10-12 15:40:49 +00002940
Richard Smith938f40b2011-06-11 17:19:42 +00002941 return FoundAssign;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002942 }
2943 return false;
2944 case UTT_HasNothrowCopy:
2945 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2946 // If __has_trivial_copy (type) is true then the trait is true, else
2947 // if type is a cv class or union type with copy constructors that are
2948 // known not to throw an exception then the trait is true, else it is
2949 // false.
John McCall31168b02011-06-15 23:02:42 +00002950 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002951 return true;
2952 if (const RecordType *RT = T->getAs<RecordType>()) {
2953 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2954 if (RD->hasTrivialCopyConstructor())
2955 return true;
2956
2957 bool FoundConstructor = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002958 unsigned FoundTQs;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002959 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl951006f2010-09-13 21:10:20 +00002960 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002961 Con != ConEnd; ++Con) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00002962 // A template constructor is never a copy constructor.
2963 // FIXME: However, it may actually be selected at the actual overload
2964 // resolution point.
2965 if (isa<FunctionTemplateDecl>(*Con))
2966 continue;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002967 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2968 if (Constructor->isCopyConstructor(FoundTQs)) {
2969 FoundConstructor = true;
2970 const FunctionProtoType *CPT
2971 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smith938f40b2011-06-11 17:19:42 +00002972 if (CPT->getExceptionSpecType() == EST_Delayed)
2973 return false;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002974 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00002975 // For now, we'll be conservative and assume that they can throw.
Richard Smith938f40b2011-06-11 17:19:42 +00002976 if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1)
2977 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002978 }
2979 }
2980
Richard Smith938f40b2011-06-11 17:19:42 +00002981 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002982 }
2983 return false;
2984 case UTT_HasNothrowConstructor:
2985 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2986 // If __has_trivial_constructor (type) is true then the trait is
2987 // true, else if type is a cv class or union type (or array
2988 // thereof) with a default constructor that is known not to
2989 // throw an exception then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00002990 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002991 return true;
2992 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
2993 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntf479f1b2011-05-09 18:22:59 +00002994 if (RD->hasTrivialDefaultConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002995 return true;
2996
Sebastian Redlc15c3262010-09-13 22:02:47 +00002997 DeclContext::lookup_const_iterator Con, ConEnd;
2998 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2999 Con != ConEnd; ++Con) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00003000 // FIXME: In C++0x, a constructor template can be a default constructor.
3001 if (isa<FunctionTemplateDecl>(*Con))
3002 continue;
Sebastian Redlc15c3262010-09-13 22:02:47 +00003003 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3004 if (Constructor->isDefaultConstructor()) {
3005 const FunctionProtoType *CPT
3006 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smith938f40b2011-06-11 17:19:42 +00003007 if (CPT->getExceptionSpecType() == EST_Delayed)
3008 return false;
Sebastian Redlc15c3262010-09-13 22:02:47 +00003009 // TODO: check whether evaluating default arguments can throw.
3010 // For now, we'll be conservative and assume that they can throw.
Sebastian Redl31ad7542011-03-13 17:09:40 +00003011 return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
Sebastian Redlc15c3262010-09-13 22:02:47 +00003012 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003013 }
3014 }
3015 return false;
3016 case UTT_HasVirtualDestructor:
3017 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3018 // If type is a class type with a virtual destructor ([class.dtor])
3019 // then the trait is true, else it is false.
3020 if (const RecordType *Record = T->getAs<RecordType>()) {
3021 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redl058fc822010-09-14 23:40:14 +00003022 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003023 return Destructor->isVirtual();
3024 }
3025 return false;
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003026
3027 // These type trait expressions are modeled on the specifications for the
3028 // Embarcadero C++0x type trait functions:
3029 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
3030 case UTT_IsCompleteType:
3031 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
3032 // Returns True if and only if T is a complete type at the point of the
3033 // function call.
3034 return !T->isIncompleteType();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003035 }
Chandler Carruthb42fb192011-05-01 07:44:17 +00003036 llvm_unreachable("Type trait not covered by switch");
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003037}
3038
3039ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor54e5b132010-09-09 16:14:44 +00003040 SourceLocation KWLoc,
3041 TypeSourceInfo *TSInfo,
3042 SourceLocation RParen) {
3043 QualType T = TSInfo->getType();
Chandler Carruthb0776202011-04-30 10:07:32 +00003044 if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T))
3045 return ExprError();
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003046
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003047 bool Value = false;
3048 if (!T->isDependentType())
Chandler Carruth8e172c62011-05-01 06:51:22 +00003049 Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003050
3051 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson1f9648d2009-07-07 19:06:02 +00003052 RParen, Context.BoolTy));
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003053}
Sebastian Redl5822f082009-02-07 20:10:22 +00003054
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003055ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
3056 SourceLocation KWLoc,
3057 ParsedType LhsTy,
3058 ParsedType RhsTy,
3059 SourceLocation RParen) {
3060 TypeSourceInfo *LhsTSInfo;
3061 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
3062 if (!LhsTSInfo)
3063 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
3064
3065 TypeSourceInfo *RhsTSInfo;
3066 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
3067 if (!RhsTSInfo)
3068 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
3069
3070 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
3071}
3072
3073static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
3074 QualType LhsT, QualType RhsT,
3075 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00003076 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
3077 "Cannot evaluate traits of dependent types");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003078
3079 switch(BTT) {
John McCall388ef532011-01-28 22:02:36 +00003080 case BTT_IsBaseOf: {
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003081 // C++0x [meta.rel]p2
John McCall388ef532011-01-28 22:02:36 +00003082 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003083 // Base and Derived are not unions and name the same class type without
3084 // regard to cv-qualifiers.
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003085
John McCall388ef532011-01-28 22:02:36 +00003086 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
3087 if (!lhsRecord) return false;
3088
3089 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
3090 if (!rhsRecord) return false;
3091
3092 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
3093 == (lhsRecord == rhsRecord));
3094
3095 if (lhsRecord == rhsRecord)
3096 return !lhsRecord->getDecl()->isUnion();
3097
3098 // C++0x [meta.rel]p2:
3099 // If Base and Derived are class types and are different types
3100 // (ignoring possible cv-qualifiers) then Derived shall be a
3101 // complete type.
3102 if (Self.RequireCompleteType(KeyLoc, RhsT,
3103 diag::err_incomplete_type_used_in_type_trait_expr))
3104 return false;
3105
3106 return cast<CXXRecordDecl>(rhsRecord->getDecl())
3107 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
3108 }
John Wiegley65497cc2011-04-27 23:09:49 +00003109 case BTT_IsSame:
3110 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichet34b21132010-12-08 22:35:30 +00003111 case BTT_TypeCompatible:
3112 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
3113 RhsT.getUnqualifiedType());
John Wiegley65497cc2011-04-27 23:09:49 +00003114 case BTT_IsConvertible:
Douglas Gregor8006e762011-01-27 20:28:01 +00003115 case BTT_IsConvertibleTo: {
3116 // C++0x [meta.rel]p4:
3117 // Given the following function prototype:
3118 //
3119 // template <class T>
3120 // typename add_rvalue_reference<T>::type create();
3121 //
3122 // the predicate condition for a template specialization
3123 // is_convertible<From, To> shall be satisfied if and only if
3124 // the return expression in the following code would be
3125 // well-formed, including any implicit conversions to the return
3126 // type of the function:
3127 //
3128 // To test() {
3129 // return create<From>();
3130 // }
3131 //
3132 // Access checking is performed as if in a context unrelated to To and
3133 // From. Only the validity of the immediate context of the expression
3134 // of the return-statement (including conversions to the return type)
3135 // is considered.
3136 //
3137 // We model the initialization as a copy-initialization of a temporary
3138 // of the appropriate type, which for this expression is identical to the
3139 // return statement (since NRVO doesn't apply).
3140 if (LhsT->isObjectType() || LhsT->isFunctionType())
3141 LhsT = Self.Context.getRValueReferenceType(LhsT);
3142
3143 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorc03a1082011-01-28 02:26:04 +00003144 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor8006e762011-01-27 20:28:01 +00003145 Expr::getValueKindForType(LhsT));
3146 Expr *FromPtr = &From;
3147 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
3148 SourceLocation()));
3149
Douglas Gregoredb76852011-01-27 22:31:44 +00003150 // Perform the initialization within a SFINAE trap at translation unit
3151 // scope.
3152 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3153 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Douglas Gregor8006e762011-01-27 20:28:01 +00003154 InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00003155 if (Init.Failed())
Douglas Gregor8006e762011-01-27 20:28:01 +00003156 return false;
Douglas Gregoredb76852011-01-27 22:31:44 +00003157
Douglas Gregor8006e762011-01-27 20:28:01 +00003158 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
3159 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
3160 }
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003161 }
3162 llvm_unreachable("Unknown type trait or not implemented");
3163}
3164
3165ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
3166 SourceLocation KWLoc,
3167 TypeSourceInfo *LhsTSInfo,
3168 TypeSourceInfo *RhsTSInfo,
3169 SourceLocation RParen) {
3170 QualType LhsT = LhsTSInfo->getType();
3171 QualType RhsT = RhsTSInfo->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003172
John McCall388ef532011-01-28 22:02:36 +00003173 if (BTT == BTT_TypeCompatible) {
Francois Pichet34b21132010-12-08 22:35:30 +00003174 if (getLangOptions().CPlusPlus) {
3175 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
3176 << SourceRange(KWLoc, RParen);
3177 return ExprError();
3178 }
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003179 }
3180
3181 bool Value = false;
3182 if (!LhsT->isDependentType() && !RhsT->isDependentType())
3183 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
3184
Francois Pichet34b21132010-12-08 22:35:30 +00003185 // Select trait result type.
3186 QualType ResultType;
3187 switch (BTT) {
Francois Pichet34b21132010-12-08 22:35:30 +00003188 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
John Wiegley65497cc2011-04-27 23:09:49 +00003189 case BTT_IsConvertible: ResultType = Context.BoolTy; break;
3190 case BTT_IsSame: ResultType = Context.BoolTy; break;
Francois Pichet34b21132010-12-08 22:35:30 +00003191 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
Douglas Gregor8006e762011-01-27 20:28:01 +00003192 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
Francois Pichet34b21132010-12-08 22:35:30 +00003193 }
3194
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003195 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
3196 RhsTSInfo, Value, RParen,
Francois Pichet34b21132010-12-08 22:35:30 +00003197 ResultType));
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003198}
3199
John Wiegley6242b6a2011-04-28 00:16:57 +00003200ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3201 SourceLocation KWLoc,
3202 ParsedType Ty,
3203 Expr* DimExpr,
3204 SourceLocation RParen) {
3205 TypeSourceInfo *TSInfo;
3206 QualType T = GetTypeFromParser(Ty, &TSInfo);
3207 if (!TSInfo)
3208 TSInfo = Context.getTrivialTypeSourceInfo(T);
3209
3210 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
3211}
3212
3213static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
3214 QualType T, Expr *DimExpr,
3215 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00003216 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley6242b6a2011-04-28 00:16:57 +00003217
3218 switch(ATT) {
3219 case ATT_ArrayRank:
3220 if (T->isArrayType()) {
3221 unsigned Dim = 0;
3222 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3223 ++Dim;
3224 T = AT->getElementType();
3225 }
3226 return Dim;
John Wiegley6242b6a2011-04-28 00:16:57 +00003227 }
John Wiegleyd3522222011-04-28 02:06:46 +00003228 return 0;
3229
John Wiegley6242b6a2011-04-28 00:16:57 +00003230 case ATT_ArrayExtent: {
3231 llvm::APSInt Value;
3232 uint64_t Dim;
John Wiegleyd3522222011-04-28 02:06:46 +00003233 if (DimExpr->isIntegerConstantExpr(Value, Self.Context, 0, false)) {
3234 if (Value < llvm::APSInt(Value.getBitWidth(), Value.isUnsigned())) {
3235 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
3236 DimExpr->getSourceRange();
3237 return false;
3238 }
John Wiegley6242b6a2011-04-28 00:16:57 +00003239 Dim = Value.getLimitedValue();
John Wiegleyd3522222011-04-28 02:06:46 +00003240 } else {
3241 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
3242 DimExpr->getSourceRange();
3243 return false;
3244 }
John Wiegley6242b6a2011-04-28 00:16:57 +00003245
3246 if (T->isArrayType()) {
3247 unsigned D = 0;
3248 bool Matched = false;
3249 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3250 if (Dim == D) {
3251 Matched = true;
3252 break;
3253 }
3254 ++D;
3255 T = AT->getElementType();
3256 }
3257
John Wiegleyd3522222011-04-28 02:06:46 +00003258 if (Matched && T->isArrayType()) {
3259 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
3260 return CAT->getSize().getLimitedValue();
3261 }
John Wiegley6242b6a2011-04-28 00:16:57 +00003262 }
John Wiegleyd3522222011-04-28 02:06:46 +00003263 return 0;
John Wiegley6242b6a2011-04-28 00:16:57 +00003264 }
3265 }
3266 llvm_unreachable("Unknown type trait or not implemented");
3267}
3268
3269ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
3270 SourceLocation KWLoc,
3271 TypeSourceInfo *TSInfo,
3272 Expr* DimExpr,
3273 SourceLocation RParen) {
3274 QualType T = TSInfo->getType();
John Wiegley6242b6a2011-04-28 00:16:57 +00003275
Chandler Carruthc5276e52011-05-01 08:48:21 +00003276 // FIXME: This should likely be tracked as an APInt to remove any host
3277 // assumptions about the width of size_t on the target.
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00003278 uint64_t Value = 0;
3279 if (!T->isDependentType())
3280 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
3281
Chandler Carruthc5276e52011-05-01 08:48:21 +00003282 // While the specification for these traits from the Embarcadero C++
3283 // compiler's documentation says the return type is 'unsigned int', Clang
3284 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
3285 // compiler, there is no difference. On several other platforms this is an
3286 // important distinction.
John Wiegley6242b6a2011-04-28 00:16:57 +00003287 return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value,
Chandler Carruth9cf632c2011-05-01 07:49:26 +00003288 DimExpr, RParen,
Chandler Carruthc5276e52011-05-01 08:48:21 +00003289 Context.getSizeType()));
John Wiegley6242b6a2011-04-28 00:16:57 +00003290}
3291
John Wiegleyf9f65842011-04-25 06:54:41 +00003292ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003293 SourceLocation KWLoc,
3294 Expr *Queried,
3295 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00003296 // If error parsing the expression, ignore.
3297 if (!Queried)
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003298 return ExprError();
John Wiegleyf9f65842011-04-25 06:54:41 +00003299
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003300 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00003301
3302 return move(Result);
3303}
3304
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003305static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
3306 switch (ET) {
3307 case ET_IsLValueExpr: return E->isLValue();
3308 case ET_IsRValueExpr: return E->isRValue();
3309 }
3310 llvm_unreachable("Expression trait not covered by switch");
3311}
3312
John Wiegleyf9f65842011-04-25 06:54:41 +00003313ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003314 SourceLocation KWLoc,
3315 Expr *Queried,
3316 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00003317 if (Queried->isTypeDependent()) {
3318 // Delay type-checking for type-dependent expressions.
3319 } else if (Queried->getType()->isPlaceholderType()) {
3320 ExprResult PE = CheckPlaceholderExpr(Queried);
3321 if (PE.isInvalid()) return ExprError();
3322 return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen);
3323 }
3324
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003325 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf57eba32011-05-01 08:48:19 +00003326
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003327 return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value,
3328 RParen, Context.BoolTy));
John Wiegleyf9f65842011-04-25 06:54:41 +00003329}
3330
Richard Trieu82402a02011-09-15 21:56:47 +00003331QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCall7decc9e2010-11-18 06:31:45 +00003332 ExprValueKind &VK,
3333 SourceLocation Loc,
3334 bool isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00003335 assert(!LHS.get()->getType()->isPlaceholderType() &&
3336 !RHS.get()->getType()->isPlaceholderType() &&
John McCall0b645e92011-06-30 17:15:34 +00003337 "placeholders should have been weeded out by now");
3338
3339 // The LHS undergoes lvalue conversions if this is ->*.
3340 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00003341 LHS = DefaultLvalueConversion(LHS.take());
3342 if (LHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00003343 }
3344
3345 // The RHS always undergoes lvalue conversions.
Richard Trieu82402a02011-09-15 21:56:47 +00003346 RHS = DefaultLvalueConversion(RHS.take());
3347 if (RHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00003348
Sebastian Redl5822f082009-02-07 20:10:22 +00003349 const char *OpSpelling = isIndirect ? "->*" : ".*";
3350 // C++ 5.5p2
3351 // The binary operator .* [p3: ->*] binds its second operand, which shall
3352 // be of type "pointer to member of T" (where T is a completely-defined
3353 // class type) [...]
Richard Trieu82402a02011-09-15 21:56:47 +00003354 QualType RHSType = RHS.get()->getType();
3355 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00003356 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00003357 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieu82402a02011-09-15 21:56:47 +00003358 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl5822f082009-02-07 20:10:22 +00003359 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00003360 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00003361
Sebastian Redl5822f082009-02-07 20:10:22 +00003362 QualType Class(MemPtr->getClass(), 0);
3363
Douglas Gregord07ba342010-10-13 20:41:14 +00003364 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
3365 // member pointer points must be completely-defined. However, there is no
3366 // reason for this semantic distinction, and the rule is not enforced by
3367 // other compilers. Therefore, we do not check this property, as it is
3368 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00003369
Sebastian Redl5822f082009-02-07 20:10:22 +00003370 // C++ 5.5p2
3371 // [...] to its first operand, which shall be of class T or of a class of
3372 // which T is an unambiguous and accessible base class. [p3: a pointer to
3373 // such a class]
Richard Trieu82402a02011-09-15 21:56:47 +00003374 QualType LHSType = LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00003375 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00003376 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
3377 LHSType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00003378 else {
3379 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieu82402a02011-09-15 21:56:47 +00003380 << OpSpelling << 1 << LHSType
Douglas Gregora771f462010-03-31 17:46:05 +00003381 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00003382 return QualType();
3383 }
3384 }
3385
Richard Trieu82402a02011-09-15 21:56:47 +00003386 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00003387 // If we want to check the hierarchy, we need a complete type.
Richard Trieu82402a02011-09-15 21:56:47 +00003388 if (RequireCompleteType(Loc, LHSType, PDiag(diag::err_bad_memptr_lhs)
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00003389 << OpSpelling << (int)isIndirect)) {
3390 return QualType();
3391 }
Anders Carlssona70cff62010-04-24 19:06:50 +00003392 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00003393 /*DetectVirtual=*/false);
Mike Stump87c57ac2009-05-16 07:39:55 +00003394 // FIXME: Would it be useful to print full ambiguity paths, or is that
3395 // overkill?
Richard Trieu82402a02011-09-15 21:56:47 +00003396 if (!IsDerivedFrom(LHSType, Class, Paths) ||
Sebastian Redl5822f082009-02-07 20:10:22 +00003397 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
3398 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieu82402a02011-09-15 21:56:47 +00003399 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00003400 return QualType();
3401 }
Eli Friedman1fcf66b2010-01-16 00:00:48 +00003402 // Cast LHS to type of use.
3403 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Eli Friedmanbe4b3632011-09-27 21:58:52 +00003404 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003405
John McCallcf142162010-08-07 06:22:56 +00003406 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00003407 BuildBasePathArray(Paths, BasePath);
Richard Trieu82402a02011-09-15 21:56:47 +00003408 LHS = ImpCastExprToType(LHS.take(), UseType, CK_DerivedToBase, VK,
3409 &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00003410 }
3411
Richard Trieu82402a02011-09-15 21:56:47 +00003412 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00003413 // Diagnose use of pointer-to-member type which when used as
3414 // the functional cast in a pointer-to-member expression.
3415 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
3416 return QualType();
3417 }
John McCall7decc9e2010-11-18 06:31:45 +00003418
Sebastian Redl5822f082009-02-07 20:10:22 +00003419 // C++ 5.5p2
3420 // The result is an object or a function of the type specified by the
3421 // second operand.
3422 // The cv qualifiers are the union of those in the pointer and the left side,
3423 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl5822f082009-02-07 20:10:22 +00003424 QualType Result = MemPtr->getPointeeType();
Richard Trieu82402a02011-09-15 21:56:47 +00003425 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00003426
Douglas Gregor1d042092011-01-26 16:40:18 +00003427 // C++0x [expr.mptr.oper]p6:
3428 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003429 // ill-formed if the second operand is a pointer to member function with
3430 // ref-qualifier &. In a ->* expression or in a .* expression whose object
3431 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor1d042092011-01-26 16:40:18 +00003432 // is a pointer to member function with ref-qualifier &&.
3433 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
3434 switch (Proto->getRefQualifier()) {
3435 case RQ_None:
3436 // Do nothing
3437 break;
3438
3439 case RQ_LValue:
Richard Trieu82402a02011-09-15 21:56:47 +00003440 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00003441 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00003442 << RHSType << 1 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00003443 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003444
Douglas Gregor1d042092011-01-26 16:40:18 +00003445 case RQ_RValue:
Richard Trieu82402a02011-09-15 21:56:47 +00003446 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00003447 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00003448 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00003449 break;
3450 }
3451 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003452
John McCall7decc9e2010-11-18 06:31:45 +00003453 // C++ [expr.mptr.oper]p6:
3454 // The result of a .* expression whose second operand is a pointer
3455 // to a data member is of the same value category as its
3456 // first operand. The result of a .* expression whose second
3457 // operand is a pointer to a member function is a prvalue. The
3458 // result of an ->* expression is an lvalue if its second operand
3459 // is a pointer to data member and a prvalue otherwise.
John McCall0009fcc2011-04-26 20:42:42 +00003460 if (Result->isFunctionType()) {
John McCall7decc9e2010-11-18 06:31:45 +00003461 VK = VK_RValue;
John McCall0009fcc2011-04-26 20:42:42 +00003462 return Context.BoundMemberTy;
3463 } else if (isIndirect) {
John McCall7decc9e2010-11-18 06:31:45 +00003464 VK = VK_LValue;
John McCall0009fcc2011-04-26 20:42:42 +00003465 } else {
Richard Trieu82402a02011-09-15 21:56:47 +00003466 VK = LHS.get()->getValueKind();
John McCall0009fcc2011-04-26 20:42:42 +00003467 }
John McCall7decc9e2010-11-18 06:31:45 +00003468
Sebastian Redl5822f082009-02-07 20:10:22 +00003469 return Result;
3470}
Sebastian Redl1a99f442009-04-16 17:51:27 +00003471
Sebastian Redl1a99f442009-04-16 17:51:27 +00003472/// \brief Try to convert a type to another according to C++0x 5.16p3.
3473///
3474/// This is part of the parameter validation for the ? operator. If either
3475/// value operand is a class type, the two operands are attempted to be
3476/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00003477/// It returns true if the program is ill-formed and has already been diagnosed
3478/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003479static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
3480 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00003481 bool &HaveConversion,
3482 QualType &ToType) {
3483 HaveConversion = false;
3484 ToType = To->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003485
3486 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00003487 SourceLocation());
Sebastian Redl1a99f442009-04-16 17:51:27 +00003488 // C++0x 5.16p3
3489 // The process for determining whether an operand expression E1 of type T1
3490 // can be converted to match an operand expression E2 of type T2 is defined
3491 // as follows:
3492 // -- If E2 is an lvalue:
John McCall086a4642010-11-24 05:12:34 +00003493 bool ToIsLvalue = To->isLValue();
Douglas Gregorf9edf802010-03-26 20:59:55 +00003494 if (ToIsLvalue) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003495 // E1 can be converted to match E2 if E1 can be implicitly converted to
3496 // type "lvalue reference to T2", subject to the constraint that in the
3497 // conversion the reference must bind directly to E1.
Douglas Gregor838fcc32010-03-26 20:14:36 +00003498 QualType T = Self.Context.getLValueReferenceType(ToType);
3499 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003500
Douglas Gregor838fcc32010-03-26 20:14:36 +00003501 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3502 if (InitSeq.isDirectReferenceBinding()) {
3503 ToType = T;
3504 HaveConversion = true;
3505 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003506 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003507
Douglas Gregor838fcc32010-03-26 20:14:36 +00003508 if (InitSeq.isAmbiguous())
3509 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003510 }
John McCall65eb8792010-02-25 01:37:24 +00003511
Sebastian Redl1a99f442009-04-16 17:51:27 +00003512 // -- If E2 is an rvalue, or if the conversion above cannot be done:
3513 // -- if E1 and E2 have class type, and the underlying class types are
3514 // the same or one is a base class of the other:
3515 QualType FTy = From->getType();
3516 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003517 const RecordType *FRec = FTy->getAs<RecordType>();
3518 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003519 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Douglas Gregor838fcc32010-03-26 20:14:36 +00003520 Self.IsDerivedFrom(FTy, TTy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003521 if (FRec && TRec &&
Douglas Gregor838fcc32010-03-26 20:14:36 +00003522 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003523 // E1 can be converted to match E2 if the class of T2 is the
3524 // same type as, or a base class of, the class of T1, and
3525 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00003526 if (FRec == TRec || FDerivedFromT) {
3527 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00003528 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3529 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00003530 if (InitSeq) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00003531 HaveConversion = true;
3532 return false;
3533 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003534
Douglas Gregor838fcc32010-03-26 20:14:36 +00003535 if (InitSeq.isAmbiguous())
3536 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003537 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003538 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003539
Douglas Gregor838fcc32010-03-26 20:14:36 +00003540 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003541 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003542
Douglas Gregor838fcc32010-03-26 20:14:36 +00003543 // -- Otherwise: E1 can be converted to match E2 if E1 can be
3544 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003545 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregorf9edf802010-03-26 20:59:55 +00003546 // an rvalue).
3547 //
3548 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
3549 // to the array-to-pointer or function-to-pointer conversions.
3550 if (!TTy->getAs<TagType>())
3551 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003552
Douglas Gregor838fcc32010-03-26 20:14:36 +00003553 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3554 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00003555 HaveConversion = !InitSeq.Failed();
Douglas Gregor838fcc32010-03-26 20:14:36 +00003556 ToType = TTy;
3557 if (InitSeq.isAmbiguous())
3558 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3559
Sebastian Redl1a99f442009-04-16 17:51:27 +00003560 return false;
3561}
3562
3563/// \brief Try to find a common type for two according to C++0x 5.16p5.
3564///
3565/// This is part of the parameter validation for the ? operator. If either
3566/// value operand is a class type, overload resolution is used to find a
3567/// conversion to a common type.
John Wiegley01296292011-04-08 18:41:53 +00003568static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003569 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00003570 Expr *Args[2] = { LHS.get(), RHS.get() };
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003571 OverloadCandidateSet CandidateSet(QuestionLoc);
3572 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
3573 CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003574
3575 OverloadCandidateSet::iterator Best;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003576 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley01296292011-04-08 18:41:53 +00003577 case OR_Success: {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003578 // We found a match. Perform the conversions on the arguments and move on.
John Wiegley01296292011-04-08 18:41:53 +00003579 ExprResult LHSRes =
3580 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
3581 Best->Conversions[0], Sema::AA_Converting);
3582 if (LHSRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00003583 break;
John Wiegley01296292011-04-08 18:41:53 +00003584 LHS = move(LHSRes);
3585
3586 ExprResult RHSRes =
3587 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
3588 Best->Conversions[1], Sema::AA_Converting);
3589 if (RHSRes.isInvalid())
3590 break;
3591 RHS = move(RHSRes);
Chandler Carruth30141632011-02-25 19:41:05 +00003592 if (Best->Function)
3593 Self.MarkDeclarationReferenced(QuestionLoc, Best->Function);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003594 return false;
John Wiegley01296292011-04-08 18:41:53 +00003595 }
3596
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003597 case OR_No_Viable_Function:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003598
3599 // Emit a better diagnostic if one of the expressions is a null pointer
3600 // constant and the other is a pointer type. In this case, the user most
3601 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00003602 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003603 return true;
3604
3605 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00003606 << LHS.get()->getType() << RHS.get()->getType()
3607 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003608 return true;
3609
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003610 case OR_Ambiguous:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003611 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley01296292011-04-08 18:41:53 +00003612 << LHS.get()->getType() << RHS.get()->getType()
3613 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00003614 // FIXME: Print the possible common types by printing the return types of
3615 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003616 break;
3617
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003618 case OR_Deleted:
David Blaikie83d382b2011-09-23 05:06:16 +00003619 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl1a99f442009-04-16 17:51:27 +00003620 }
3621 return true;
3622}
3623
Sebastian Redl5775af1a2009-04-17 16:30:52 +00003624/// \brief Perform an "extended" implicit conversion as returned by
3625/// TryClassUnification.
John Wiegley01296292011-04-08 18:41:53 +00003626static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00003627 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley01296292011-04-08 18:41:53 +00003628 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00003629 SourceLocation());
John Wiegley01296292011-04-08 18:41:53 +00003630 Expr *Arg = E.take();
3631 InitializationSequence InitSeq(Self, Entity, Kind, &Arg, 1);
3632 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&Arg, 1));
Douglas Gregor838fcc32010-03-26 20:14:36 +00003633 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00003634 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003635
John Wiegley01296292011-04-08 18:41:53 +00003636 E = Result;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00003637 return false;
3638}
3639
Sebastian Redl1a99f442009-04-16 17:51:27 +00003640/// \brief Check the operands of ?: under C++ semantics.
3641///
3642/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
3643/// extension. In this case, LHS == Cond. (But they're not aliases.)
John Wiegley01296292011-04-08 18:41:53 +00003644QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCallc07a0c72011-02-17 10:25:35 +00003645 ExprValueKind &VK, ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00003646 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00003647 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
3648 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003649
3650 // C++0x 5.16p1
3651 // The first expression is contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00003652 if (!Cond.get()->isTypeDependent()) {
3653 ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
3654 if (CondRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00003655 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003656 Cond = move(CondRes);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003657 }
3658
John McCall7decc9e2010-11-18 06:31:45 +00003659 // Assume r-value.
3660 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00003661 OK = OK_Ordinary;
John McCall7decc9e2010-11-18 06:31:45 +00003662
Sebastian Redl1a99f442009-04-16 17:51:27 +00003663 // Either of the arguments dependent?
John Wiegley01296292011-04-08 18:41:53 +00003664 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl1a99f442009-04-16 17:51:27 +00003665 return Context.DependentTy;
3666
3667 // C++0x 5.16p2
3668 // If either the second or the third operand has type (cv) void, ...
John Wiegley01296292011-04-08 18:41:53 +00003669 QualType LTy = LHS.get()->getType();
3670 QualType RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003671 bool LVoid = LTy->isVoidType();
3672 bool RVoid = RTy->isVoidType();
3673 if (LVoid || RVoid) {
3674 // ... then the [l2r] conversions are performed on the second and third
3675 // operands ...
John Wiegley01296292011-04-08 18:41:53 +00003676 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3677 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3678 if (LHS.isInvalid() || RHS.isInvalid())
3679 return QualType();
3680 LTy = LHS.get()->getType();
3681 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003682
3683 // ... and one of the following shall hold:
3684 // -- The second or the third operand (but not both) is a throw-
3685 // expression; the result is of the type of the other and is an rvalue.
John Wiegley01296292011-04-08 18:41:53 +00003686 bool LThrow = isa<CXXThrowExpr>(LHS.get());
3687 bool RThrow = isa<CXXThrowExpr>(RHS.get());
Sebastian Redl1a99f442009-04-16 17:51:27 +00003688 if (LThrow && !RThrow)
3689 return RTy;
3690 if (RThrow && !LThrow)
3691 return LTy;
3692
3693 // -- Both the second and third operands have type void; the result is of
3694 // type void and is an rvalue.
3695 if (LVoid && RVoid)
3696 return Context.VoidTy;
3697
3698 // Neither holds, error.
3699 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
3700 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley01296292011-04-08 18:41:53 +00003701 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003702 return QualType();
3703 }
3704
3705 // Neither is void.
3706
3707 // C++0x 5.16p3
3708 // Otherwise, if the second and third operand have different types, and
3709 // either has (cv) class type, and attempt is made to convert each of those
3710 // operands to the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003711 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00003712 (LTy->isRecordType() || RTy->isRecordType())) {
3713 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
3714 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00003715 QualType L2RType, R2LType;
3716 bool HaveL2R, HaveR2L;
John Wiegley01296292011-04-08 18:41:53 +00003717 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00003718 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003719 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00003720 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003721
Sebastian Redl1a99f442009-04-16 17:51:27 +00003722 // If both can be converted, [...] the program is ill-formed.
3723 if (HaveL2R && HaveR2L) {
3724 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley01296292011-04-08 18:41:53 +00003725 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003726 return QualType();
3727 }
3728
3729 // If exactly one conversion is possible, that conversion is applied to
3730 // the chosen operand and the converted operands are used in place of the
3731 // original operands for the remainder of this section.
3732 if (HaveL2R) {
John Wiegley01296292011-04-08 18:41:53 +00003733 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00003734 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003735 LTy = LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003736 } else if (HaveR2L) {
John Wiegley01296292011-04-08 18:41:53 +00003737 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00003738 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003739 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003740 }
3741 }
3742
3743 // C++0x 5.16p4
John McCall7decc9e2010-11-18 06:31:45 +00003744 // If the second and third operands are glvalues of the same value
3745 // category and have the same type, the result is of that type and
3746 // value category and it is a bit-field if the second or the third
3747 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00003748 // We only extend this to bitfields, not to the crazy other kinds of
3749 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00003750 bool Same = Context.hasSameType(LTy, RTy);
John McCall7decc9e2010-11-18 06:31:45 +00003751 if (Same &&
John Wiegley01296292011-04-08 18:41:53 +00003752 LHS.get()->isGLValue() &&
3753 LHS.get()->getValueKind() == RHS.get()->getValueKind() &&
3754 LHS.get()->isOrdinaryOrBitFieldObject() &&
3755 RHS.get()->isOrdinaryOrBitFieldObject()) {
3756 VK = LHS.get()->getValueKind();
3757 if (LHS.get()->getObjectKind() == OK_BitField ||
3758 RHS.get()->getObjectKind() == OK_BitField)
John McCall4bc41ae2010-11-18 19:01:18 +00003759 OK = OK_BitField;
John McCall7decc9e2010-11-18 06:31:45 +00003760 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00003761 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003762
3763 // C++0x 5.16p5
3764 // Otherwise, the result is an rvalue. If the second and third operands
3765 // do not have the same type, and either has (cv) class type, ...
3766 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
3767 // ... overload resolution is used to determine the conversions (if any)
3768 // to be applied to the operands. If the overload resolution fails, the
3769 // program is ill-formed.
3770 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
3771 return QualType();
3772 }
3773
3774 // C++0x 5.16p6
3775 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
3776 // conversions are performed on the second and third operands.
John Wiegley01296292011-04-08 18:41:53 +00003777 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3778 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3779 if (LHS.isInvalid() || RHS.isInvalid())
3780 return QualType();
3781 LTy = LHS.get()->getType();
3782 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003783
3784 // After those conversions, one of the following shall hold:
3785 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00003786 // is of that type. If the operands have class type, the result
3787 // is a prvalue temporary of the result type, which is
3788 // copy-initialized from either the second operand or the third
3789 // operand depending on the value of the first operand.
3790 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
3791 if (LTy->isRecordType()) {
3792 // The operands have class type. Make a temporary copy.
3793 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003794 ExprResult LHSCopy = PerformCopyInitialization(Entity,
3795 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00003796 LHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00003797 if (LHSCopy.isInvalid())
3798 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003799
3800 ExprResult RHSCopy = PerformCopyInitialization(Entity,
3801 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00003802 RHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00003803 if (RHSCopy.isInvalid())
3804 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003805
John Wiegley01296292011-04-08 18:41:53 +00003806 LHS = LHSCopy;
3807 RHS = RHSCopy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00003808 }
3809
Sebastian Redl1a99f442009-04-16 17:51:27 +00003810 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00003811 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003812
Douglas Gregor46188682010-05-18 22:42:18 +00003813 // Extension: conditional operator involving vector types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003814 if (LTy->isVectorType() || RTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00003815 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor46188682010-05-18 22:42:18 +00003816
Sebastian Redl1a99f442009-04-16 17:51:27 +00003817 // -- The second and third operands have arithmetic or enumeration type;
3818 // the usual arithmetic conversions are performed to bring them to a
3819 // common type, and the result is of that type.
3820 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
3821 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00003822 if (LHS.isInvalid() || RHS.isInvalid())
3823 return QualType();
3824 return LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003825 }
3826
3827 // -- The second and third operands have pointer type, or one has pointer
3828 // type and the other is a null pointer constant; pointer conversions
3829 // and qualification conversions are performed to bring them to their
3830 // composite pointer type. The result is of the composite pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00003831 // -- The second and third operands have pointer to member type, or one has
3832 // pointer to member type and the other is a null pointer constant;
3833 // pointer to member conversions and qualification conversions are
3834 // performed to bring them to a common type, whose cv-qualification
3835 // shall match the cv-qualification of either the second or the third
3836 // operand. The result is of the common type.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003837 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00003838 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003839 isSFINAEContext()? 0 : &NonStandardCompositeType);
3840 if (!Composite.isNull()) {
3841 if (NonStandardCompositeType)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003842 Diag(QuestionLoc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003843 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
3844 << LTy << RTy << Composite
John Wiegley01296292011-04-08 18:41:53 +00003845 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003846
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003847 return Composite;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003848 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003849
Douglas Gregor697a3912010-04-01 22:47:07 +00003850 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00003851 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
3852 if (!Composite.isNull())
3853 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003854
Chandler Carruth9c9127e2011-02-19 00:13:59 +00003855 // Check if we are using a null with a non-pointer type.
John Wiegley01296292011-04-08 18:41:53 +00003856 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth9c9127e2011-02-19 00:13:59 +00003857 return QualType();
3858
Sebastian Redl1a99f442009-04-16 17:51:27 +00003859 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00003860 << LHS.get()->getType() << RHS.get()->getType()
3861 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003862 return QualType();
3863}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003864
3865/// \brief Find a merged pointer type and convert the two expressions to it.
3866///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003867/// This finds the composite pointer type (or member pointer type) for @p E1
3868/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
3869/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003870/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003871///
Douglas Gregor19175ff2010-04-16 23:20:25 +00003872/// \param Loc The location of the operator requiring these two expressions to
3873/// be converted to the composite pointer type.
3874///
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003875/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
3876/// a non-standard (but still sane) composite type to which both expressions
3877/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
3878/// will be set true.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003879QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor19175ff2010-04-16 23:20:25 +00003880 Expr *&E1, Expr *&E2,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003881 bool *NonStandardCompositeType) {
3882 if (NonStandardCompositeType)
3883 *NonStandardCompositeType = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003884
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003885 assert(getLangOptions().CPlusPlus && "This function assumes C++");
3886 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003887
Fariborz Jahanian33e148f2009-12-08 20:04:24 +00003888 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
3889 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003890 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003891
3892 // C++0x 5.9p2
3893 // Pointer conversions and qualification conversions are performed on
3894 // pointer operands to bring them to their composite pointer type. If
3895 // one operand is a null pointer constant, the composite pointer type is
3896 // the type of the other operand.
Douglas Gregor56751b52009-09-25 04:25:58 +00003897 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003898 if (T2->isMemberPointerType())
John Wiegley01296292011-04-08 18:41:53 +00003899 E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003900 else
John Wiegley01296292011-04-08 18:41:53 +00003901 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003902 return T2;
3903 }
Douglas Gregor56751b52009-09-25 04:25:58 +00003904 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003905 if (T1->isMemberPointerType())
John Wiegley01296292011-04-08 18:41:53 +00003906 E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003907 else
John Wiegley01296292011-04-08 18:41:53 +00003908 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003909 return T1;
3910 }
Mike Stump11289f42009-09-09 15:08:12 +00003911
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003912 // Now both have to be pointers or member pointers.
Sebastian Redl658262f2009-11-16 21:03:45 +00003913 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
3914 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003915 return QualType();
3916
3917 // Otherwise, of one of the operands has type "pointer to cv1 void," then
3918 // the other has type "pointer to cv2 T" and the composite pointer type is
3919 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
3920 // Otherwise, the composite pointer type is a pointer type similar to the
3921 // type of one of the operands, with a cv-qualification signature that is
3922 // the union of the cv-qualification signatures of the operand types.
3923 // In practice, the first part here is redundant; it's subsumed by the second.
3924 // What we do here is, we build the two possible composite types, and try the
3925 // conversions in both directions. If only one works, or if the two composite
3926 // types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00003927 // FIXME: extended qualifiers?
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003928 typedef SmallVector<unsigned, 4> QualifierVector;
Sebastian Redl658262f2009-11-16 21:03:45 +00003929 QualifierVector QualifierUnion;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003930 typedef SmallVector<std::pair<const Type *, const Type *>, 4>
Sebastian Redl658262f2009-11-16 21:03:45 +00003931 ContainingClassVector;
3932 ContainingClassVector MemberOfClass;
3933 QualType Composite1 = Context.getCanonicalType(T1),
3934 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003935 unsigned NeedConstBefore = 0;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003936 do {
3937 const PointerType *Ptr1, *Ptr2;
3938 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3939 (Ptr2 = Composite2->getAs<PointerType>())) {
3940 Composite1 = Ptr1->getPointeeType();
3941 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003942
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003943 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003944 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003945 if (NonStandardCompositeType &&
3946 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3947 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003948
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003949 QualifierUnion.push_back(
3950 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3951 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3952 continue;
3953 }
Mike Stump11289f42009-09-09 15:08:12 +00003954
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003955 const MemberPointerType *MemPtr1, *MemPtr2;
3956 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3957 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3958 Composite1 = MemPtr1->getPointeeType();
3959 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003960
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003961 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003962 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003963 if (NonStandardCompositeType &&
3964 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3965 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003966
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003967 QualifierUnion.push_back(
3968 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3969 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
3970 MemPtr2->getClass()));
3971 continue;
3972 }
Mike Stump11289f42009-09-09 15:08:12 +00003973
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003974 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00003975
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003976 // Cannot unwrap any more types.
3977 break;
3978 } while (true);
Mike Stump11289f42009-09-09 15:08:12 +00003979
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003980 if (NeedConstBefore && NonStandardCompositeType) {
3981 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003982 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003983 // requirements of C++ [conv.qual]p4 bullet 3.
3984 for (unsigned I = 0; I != NeedConstBefore; ++I) {
3985 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
3986 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
3987 *NonStandardCompositeType = true;
3988 }
3989 }
3990 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003991
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003992 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redl658262f2009-11-16 21:03:45 +00003993 ContainingClassVector::reverse_iterator MOC
3994 = MemberOfClass.rbegin();
3995 for (QualifierVector::reverse_iterator
3996 I = QualifierUnion.rbegin(),
3997 E = QualifierUnion.rend();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003998 I != E; (void)++I, ++MOC) {
John McCall8ccfcb52009-09-24 19:53:00 +00003999 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004000 if (MOC->first && MOC->second) {
4001 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00004002 Composite1 = Context.getMemberPointerType(
4003 Context.getQualifiedType(Composite1, Quals),
4004 MOC->first);
4005 Composite2 = Context.getMemberPointerType(
4006 Context.getQualifiedType(Composite2, Quals),
4007 MOC->second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004008 } else {
4009 // Rebuild pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00004010 Composite1
4011 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
4012 Composite2
4013 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004014 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004015 }
4016
Douglas Gregor19175ff2010-04-16 23:20:25 +00004017 // Try to convert to the first composite pointer type.
4018 InitializedEntity Entity1
4019 = InitializedEntity::InitializeTemporary(Composite1);
4020 InitializationKind Kind
4021 = InitializationKind::CreateCopy(Loc, SourceLocation());
4022 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
4023 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump11289f42009-09-09 15:08:12 +00004024
Douglas Gregor19175ff2010-04-16 23:20:25 +00004025 if (E1ToC1 && E2ToC1) {
4026 // Conversion to Composite1 is viable.
4027 if (!Context.hasSameType(Composite1, Composite2)) {
4028 // Composite2 is a different type from Composite1. Check whether
4029 // Composite2 is also viable.
4030 InitializedEntity Entity2
4031 = InitializedEntity::InitializeTemporary(Composite2);
4032 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4033 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4034 if (E1ToC2 && E2ToC2) {
4035 // Both Composite1 and Composite2 are viable and are different;
4036 // this is an ambiguity.
4037 return QualType();
4038 }
4039 }
4040
4041 // Convert E1 to Composite1
John McCalldadc5752010-08-24 06:29:42 +00004042 ExprResult E1Result
John McCall37ad5512010-08-23 06:44:23 +00004043 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00004044 if (E1Result.isInvalid())
4045 return QualType();
4046 E1 = E1Result.takeAs<Expr>();
4047
4048 // Convert E2 to Composite1
John McCalldadc5752010-08-24 06:29:42 +00004049 ExprResult E2Result
John McCall37ad5512010-08-23 06:44:23 +00004050 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00004051 if (E2Result.isInvalid())
4052 return QualType();
4053 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004054
Douglas Gregor19175ff2010-04-16 23:20:25 +00004055 return Composite1;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004056 }
4057
Douglas Gregor19175ff2010-04-16 23:20:25 +00004058 // Check whether Composite2 is viable.
4059 InitializedEntity Entity2
4060 = InitializedEntity::InitializeTemporary(Composite2);
4061 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4062 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4063 if (!E1ToC2 || !E2ToC2)
4064 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004065
Douglas Gregor19175ff2010-04-16 23:20:25 +00004066 // Convert E1 to Composite2
John McCalldadc5752010-08-24 06:29:42 +00004067 ExprResult E1Result
John McCall37ad5512010-08-23 06:44:23 +00004068 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00004069 if (E1Result.isInvalid())
4070 return QualType();
4071 E1 = E1Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004072
Douglas Gregor19175ff2010-04-16 23:20:25 +00004073 // Convert E2 to Composite2
John McCalldadc5752010-08-24 06:29:42 +00004074 ExprResult E2Result
John McCall37ad5512010-08-23 06:44:23 +00004075 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00004076 if (E2Result.isInvalid())
4077 return QualType();
4078 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004079
Douglas Gregor19175ff2010-04-16 23:20:25 +00004080 return Composite2;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004081}
Anders Carlsson85a307d2009-05-17 18:41:29 +00004082
John McCalldadc5752010-08-24 06:29:42 +00004083ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00004084 if (!E)
4085 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004086
John McCall31168b02011-06-15 23:02:42 +00004087 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
4088
4089 // If the result is a glvalue, we shouldn't bind it.
4090 if (!E->isRValue())
Anders Carlssonf86a8d12009-08-15 23:41:35 +00004091 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00004092
John McCall31168b02011-06-15 23:02:42 +00004093 // In ARC, calls that return a retainable type can return retained,
4094 // in which case we have to insert a consuming cast.
4095 if (getLangOptions().ObjCAutoRefCount &&
4096 E->getType()->isObjCRetainableType()) {
4097
4098 bool ReturnsRetained;
4099
4100 // For actual calls, we compute this by examining the type of the
4101 // called value.
4102 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
4103 Expr *Callee = Call->getCallee()->IgnoreParens();
4104 QualType T = Callee->getType();
4105
4106 if (T == Context.BoundMemberTy) {
4107 // Handle pointer-to-members.
4108 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
4109 T = BinOp->getRHS()->getType();
4110 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
4111 T = Mem->getMemberDecl()->getType();
4112 }
4113
4114 if (const PointerType *Ptr = T->getAs<PointerType>())
4115 T = Ptr->getPointeeType();
4116 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
4117 T = Ptr->getPointeeType();
4118 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
4119 T = MemPtr->getPointeeType();
4120
4121 const FunctionType *FTy = T->getAs<FunctionType>();
4122 assert(FTy && "call to value not of function type?");
4123 ReturnsRetained = FTy->getExtInfo().getProducesResult();
4124
4125 // ActOnStmtExpr arranges things so that StmtExprs of retainable
4126 // type always produce a +1 object.
4127 } else if (isa<StmtExpr>(E)) {
4128 ReturnsRetained = true;
4129
4130 // For message sends and property references, we try to find an
4131 // actual method. FIXME: we should infer retention by selector in
4132 // cases where we don't have an actual method.
4133 } else {
John McCall32a4da02011-08-03 07:02:44 +00004134 ObjCMethodDecl *D = 0;
John McCall31168b02011-06-15 23:02:42 +00004135 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
4136 D = Send->getMethodDecl();
John McCall31168b02011-06-15 23:02:42 +00004137 }
4138
4139 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCall32a4da02011-08-03 07:02:44 +00004140
4141 // Don't do reclaims on performSelector calls; despite their
4142 // return type, the invoked method doesn't necessarily actually
4143 // return an object.
4144 if (!ReturnsRetained &&
4145 D && D->getMethodFamily() == OMF_performSelector)
4146 return Owned(E);
John McCall31168b02011-06-15 23:02:42 +00004147 }
4148
John McCall16de4d22011-11-14 19:53:16 +00004149 // Don't reclaim an object of Class type.
4150 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
4151 return Owned(E);
4152
John McCall4db5c3c2011-07-07 06:58:02 +00004153 ExprNeedsCleanups = true;
4154
John McCall2d637d22011-09-10 06:18:15 +00004155 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
4156 : CK_ARCReclaimReturnedObject);
John McCall4db5c3c2011-07-07 06:58:02 +00004157 return Owned(ImplicitCastExpr::Create(Context, E->getType(), ck, E, 0,
4158 VK_RValue));
John McCall31168b02011-06-15 23:02:42 +00004159 }
4160
4161 if (!getLangOptions().CPlusPlus)
4162 return Owned(E);
Douglas Gregor363b1512009-12-24 18:51:59 +00004163
Peter Collingbournefbef4c82011-11-27 22:09:28 +00004164 QualType ET = Context.getBaseElementType(E->getType());
4165 const RecordType *RT = ET->getAs<RecordType>();
Anders Carlsson2d4cada2009-05-30 20:36:53 +00004166 if (!RT)
4167 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00004168
John McCall67da35c2010-02-04 22:26:26 +00004169 // That should be enough to guarantee that this type is complete.
4170 // If it has a trivial destructor, we can avoid the extra copy.
Jeffrey Yasskinbbc4eea2011-01-27 19:17:54 +00004171 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCallbdb989e2010-08-12 02:40:37 +00004172 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall67da35c2010-02-04 22:26:26 +00004173 return Owned(E);
4174
John McCall31168b02011-06-15 23:02:42 +00004175 CXXDestructorDecl *Destructor = LookupDestructor(RD);
4176
4177 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
4178 if (Destructor) {
Fariborz Jahanian67828442009-08-03 19:13:25 +00004179 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00004180 CheckDestructorAccess(E->getExprLoc(), Destructor,
4181 PDiag(diag::err_access_dtor_temp)
4182 << E->getType());
John McCall31168b02011-06-15 23:02:42 +00004183
John McCall28fc7092011-11-10 05:35:25 +00004184 // We need a cleanup, but we don't need to remember the temporary.
John McCall31168b02011-06-15 23:02:42 +00004185 ExprNeedsCleanups = true;
John McCall8e36d532010-04-07 00:41:46 +00004186 }
Anders Carlsson2d4cada2009-05-30 20:36:53 +00004187 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
4188}
4189
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004190ExprResult
John McCall5d413782010-12-06 08:20:24 +00004191Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004192 if (SubExpr.isInvalid())
4193 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004194
John McCall5d413782010-12-06 08:20:24 +00004195 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004196}
4197
John McCall28fc7092011-11-10 05:35:25 +00004198Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
4199 assert(SubExpr && "sub expression can't be null!");
4200
4201 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
4202 assert(ExprCleanupObjects.size() >= FirstCleanup);
4203 assert(ExprNeedsCleanups || ExprCleanupObjects.size() == FirstCleanup);
4204 if (!ExprNeedsCleanups)
4205 return SubExpr;
4206
4207 ArrayRef<ExprWithCleanups::CleanupObject> Cleanups
4208 = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
4209 ExprCleanupObjects.size() - FirstCleanup);
4210
4211 Expr *E = ExprWithCleanups::Create(Context, SubExpr, Cleanups);
4212 DiscardCleanupsInEvaluationContext();
4213
4214 return E;
4215}
4216
John McCall5d413782010-12-06 08:20:24 +00004217Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00004218 assert(SubStmt && "sub statement can't be null!");
4219
John McCall31168b02011-06-15 23:02:42 +00004220 if (!ExprNeedsCleanups)
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00004221 return SubStmt;
4222
4223 // FIXME: In order to attach the temporaries, wrap the statement into
4224 // a StmtExpr; currently this is only used for asm statements.
4225 // This is hacky, either create a new CXXStmtWithTemporaries statement or
4226 // a new AsmStmtWithTemporaries.
4227 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
4228 SourceLocation(),
4229 SourceLocation());
4230 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
4231 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00004232 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00004233}
4234
John McCalldadc5752010-08-24 06:29:42 +00004235ExprResult
John McCallb268a282010-08-23 23:25:46 +00004236Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallba7bf592010-08-24 05:47:05 +00004237 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregore610ada2010-02-24 18:44:31 +00004238 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004239 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004240 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00004241 if (Result.isInvalid()) return ExprError();
4242 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00004243
John McCall526ab472011-10-25 17:37:35 +00004244 Result = CheckPlaceholderExpr(Base);
4245 if (Result.isInvalid()) return ExprError();
4246 Base = Result.take();
4247
John McCallb268a282010-08-23 23:25:46 +00004248 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00004249 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004250 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00004251 // If we have a pointer to a dependent type and are using the -> operator,
4252 // the object type is the type that the pointer points to. We might still
4253 // have enough information about that type to do something useful.
4254 if (OpKind == tok::arrow)
4255 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4256 BaseType = Ptr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004257
John McCallba7bf592010-08-24 05:47:05 +00004258 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00004259 MayBePseudoDestructor = true;
John McCallb268a282010-08-23 23:25:46 +00004260 return Owned(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004261 }
Mike Stump11289f42009-09-09 15:08:12 +00004262
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004263 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00004264 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004265 // returned, with the original second operand.
4266 if (OpKind == tok::arrow) {
John McCallc1538c02009-09-30 01:01:30 +00004267 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00004268 llvm::SmallPtrSet<CanQualType,8> CTypes;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004269 SmallVector<SourceLocation, 8> Locations;
John McCallbd0465b2009-09-30 01:30:54 +00004270 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004271
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004272 while (BaseType->isRecordType()) {
John McCallb268a282010-08-23 23:25:46 +00004273 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
4274 if (Result.isInvalid())
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004275 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00004276 Base = Result.get();
4277 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonfbd2d492009-10-13 22:55:59 +00004278 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallb268a282010-08-23 23:25:46 +00004279 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00004280 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCallbd0465b2009-09-30 01:30:54 +00004281 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00004282 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00004283 for (unsigned i = 0; i < Locations.size(); i++)
4284 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00004285 return ExprError();
4286 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004287 }
Mike Stump11289f42009-09-09 15:08:12 +00004288
Douglas Gregorbf3a8262012-01-12 16:11:24 +00004289 if (BaseType->isPointerType() || BaseType->isObjCObjectPointerType())
Douglas Gregore4f764f2009-11-20 19:58:21 +00004290 BaseType = BaseType->getPointeeType();
4291 }
Mike Stump11289f42009-09-09 15:08:12 +00004292
Douglas Gregorbf3a8262012-01-12 16:11:24 +00004293 // Objective-C properties allow "." access on Objective-C pointer types,
4294 // so adjust the base type to the object type itself.
4295 if (BaseType->isObjCObjectPointerType())
4296 BaseType = BaseType->getPointeeType();
4297
4298 // C++ [basic.lookup.classref]p2:
4299 // [...] If the type of the object expression is of pointer to scalar
4300 // type, the unqualified-id is looked up in the context of the complete
4301 // postfix-expression.
4302 //
4303 // This also indicates that we could be parsing a pseudo-destructor-name.
4304 // Note that Objective-C class and object types can be pseudo-destructor
4305 // expressions or normal member (ivar or property) access expressions.
4306 if (BaseType->isObjCObjectOrInterfaceType()) {
4307 MayBePseudoDestructor = true;
4308 } else if (!BaseType->isRecordType()) {
John McCallba7bf592010-08-24 05:47:05 +00004309 ObjectType = ParsedType();
Douglas Gregore610ada2010-02-24 18:44:31 +00004310 MayBePseudoDestructor = true;
John McCallb268a282010-08-23 23:25:46 +00004311 return Owned(Base);
Douglas Gregor2b6ca462009-09-03 21:38:09 +00004312 }
Mike Stump11289f42009-09-09 15:08:12 +00004313
Douglas Gregor3fad6172009-11-17 05:17:33 +00004314 // The object type must be complete (or dependent).
4315 if (!BaseType->isDependentType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004316 RequireCompleteType(OpLoc, BaseType,
Douglas Gregor3fad6172009-11-17 05:17:33 +00004317 PDiag(diag::err_incomplete_member_access)))
4318 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004319
Douglas Gregor2b6ca462009-09-03 21:38:09 +00004320 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004321 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00004322 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00004323 // type C (or of pointer to a class type C), the unqualified-id is looked
4324 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00004325 ObjectType = ParsedType::make(BaseType);
Mike Stump11289f42009-09-09 15:08:12 +00004326 return move(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004327}
4328
John McCalldadc5752010-08-24 06:29:42 +00004329ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCallb268a282010-08-23 23:25:46 +00004330 Expr *MemExpr) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004331 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCallb268a282010-08-23 23:25:46 +00004332 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
4333 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregora771f462010-03-31 17:46:05 +00004334 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004335
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004336 return ActOnCallExpr(/*Scope*/ 0,
John McCallb268a282010-08-23 23:25:46 +00004337 MemExpr,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004338 /*LPLoc*/ ExpectedLParenLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00004339 MultiExprArg(),
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004340 /*RPLoc*/ ExpectedLParenLoc);
4341}
Douglas Gregore610ada2010-02-24 18:44:31 +00004342
David Blaikie1d578782011-12-16 16:03:09 +00004343static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *Base,
4344 tok::TokenKind& OpKind, SourceLocation OpLoc) {
4345 // C++ [expr.pseudo]p2:
4346 // The left-hand side of the dot operator shall be of scalar type. The
4347 // left-hand side of the arrow operator shall be of pointer to scalar type.
4348 // This scalar type is the object type.
4349 if (OpKind == tok::arrow) {
4350 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4351 ObjectType = Ptr->getPointeeType();
4352 } else if (!Base->isTypeDependent()) {
4353 // The user wrote "p->" when she probably meant "p."; fix it.
4354 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4355 << ObjectType << true
4356 << FixItHint::CreateReplacement(OpLoc, ".");
4357 if (S.isSFINAEContext())
4358 return true;
4359
4360 OpKind = tok::period;
4361 }
4362 }
4363
4364 return false;
4365}
4366
John McCalldadc5752010-08-24 06:29:42 +00004367ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00004368 SourceLocation OpLoc,
4369 tok::TokenKind OpKind,
4370 const CXXScopeSpec &SS,
4371 TypeSourceInfo *ScopeTypeInfo,
4372 SourceLocation CCLoc,
4373 SourceLocation TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00004374 PseudoDestructorTypeStorage Destructed,
John McCalla2c4e722011-02-25 05:21:17 +00004375 bool HasTrailingLParen) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00004376 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004377
John McCallb268a282010-08-23 23:25:46 +00004378 QualType ObjectType = Base->getType();
David Blaikie1d578782011-12-16 16:03:09 +00004379 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4380 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004381
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004382 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
Nico Weber58829272012-01-23 05:50:57 +00004383 if (getLangOptions().MicrosoftMode && ObjectType->isVoidType())
Nico Weber4bc64992012-01-23 06:08:16 +00004384 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Nico Weber58829272012-01-23 05:50:57 +00004385 else
4386 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
4387 << ObjectType << Base->getSourceRange();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004388 return ExprError();
4389 }
4390
4391 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004392 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004393 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00004394 if (DestructedTypeInfo) {
4395 QualType DestructedType = DestructedTypeInfo->getType();
4396 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00004397 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCall31168b02011-06-15 23:02:42 +00004398 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
4399 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
4400 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
4401 << ObjectType << DestructedType << Base->getSourceRange()
4402 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004403
John McCall31168b02011-06-15 23:02:42 +00004404 // Recover by setting the destructed type to the object type.
4405 DestructedType = ObjectType;
4406 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
Douglas Gregor678f90d2010-02-25 01:56:36 +00004407 DestructedTypeStart);
John McCall31168b02011-06-15 23:02:42 +00004408 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4409 } else if (DestructedType.getObjCLifetime() !=
4410 ObjectType.getObjCLifetime()) {
4411
4412 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
4413 // Okay: just pretend that the user provided the correctly-qualified
4414 // type.
4415 } else {
4416 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
4417 << ObjectType << DestructedType << Base->getSourceRange()
4418 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
4419 }
4420
4421 // Recover by setting the destructed type to the object type.
4422 DestructedType = ObjectType;
4423 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
4424 DestructedTypeStart);
4425 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4426 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00004427 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004428 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004429
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004430 // C++ [expr.pseudo]p2:
4431 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
4432 // form
4433 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004434 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004435 //
4436 // shall designate the same scalar type.
4437 if (ScopeTypeInfo) {
4438 QualType ScopeType = ScopeTypeInfo->getType();
4439 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00004440 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004441
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00004442 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004443 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00004444 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00004445 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004446
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004447 ScopeType = QualType();
4448 ScopeTypeInfo = 0;
4449 }
4450 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004451
John McCallb268a282010-08-23 23:25:46 +00004452 Expr *Result
4453 = new (Context) CXXPseudoDestructorExpr(Context, Base,
4454 OpKind == tok::arrow, OpLoc,
Douglas Gregora6ce6082011-02-25 18:19:59 +00004455 SS.getWithLocInContext(Context),
John McCallb268a282010-08-23 23:25:46 +00004456 ScopeTypeInfo,
4457 CCLoc,
4458 TildeLoc,
4459 Destructed);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004460
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004461 if (HasTrailingLParen)
John McCallb268a282010-08-23 23:25:46 +00004462 return Owned(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004463
John McCallb268a282010-08-23 23:25:46 +00004464 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004465}
4466
John McCalldadc5752010-08-24 06:29:42 +00004467ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00004468 SourceLocation OpLoc,
4469 tok::TokenKind OpKind,
4470 CXXScopeSpec &SS,
4471 UnqualifiedId &FirstTypeName,
4472 SourceLocation CCLoc,
4473 SourceLocation TildeLoc,
4474 UnqualifiedId &SecondTypeName,
4475 bool HasTrailingLParen) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004476 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4477 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4478 "Invalid first type name in pseudo-destructor");
4479 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4480 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4481 "Invalid second type name in pseudo-destructor");
4482
John McCallb268a282010-08-23 23:25:46 +00004483 QualType ObjectType = Base->getType();
David Blaikie1d578782011-12-16 16:03:09 +00004484 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4485 return ExprError();
Douglas Gregor678f90d2010-02-25 01:56:36 +00004486
4487 // Compute the object type that we should use for name lookup purposes. Only
4488 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00004489 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00004490 if (!SS.isSet()) {
John McCalla2c4e722011-02-25 05:21:17 +00004491 if (ObjectType->isRecordType())
4492 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallba7bf592010-08-24 05:47:05 +00004493 else if (ObjectType->isDependentType())
4494 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00004495 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004496
4497 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004498 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004499 QualType DestructedType;
4500 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregor678f90d2010-02-25 01:56:36 +00004501 PseudoDestructorTypeStorage Destructed;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004502 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004503 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00004504 SecondTypeName.StartLocation,
Fariborz Jahanian87967422011-02-08 18:05:59 +00004505 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004506 if (!T &&
Douglas Gregor678f90d2010-02-25 01:56:36 +00004507 ((SS.isSet() && !computeDeclContext(SS, false)) ||
4508 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004509 // The name of the type being destroyed is a dependent name, and we
Douglas Gregor678f90d2010-02-25 01:56:36 +00004510 // couldn't find anything useful in scope. Just store the identifier and
4511 // it's location, and we'll perform (qualified) name lookup again at
4512 // template instantiation time.
4513 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
4514 SecondTypeName.StartLocation);
4515 } else if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004516 Diag(SecondTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004517 diag::err_pseudo_dtor_destructor_non_type)
4518 << SecondTypeName.Identifier << ObjectType;
4519 if (isSFINAEContext())
4520 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004521
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004522 // Recover by assuming we had the right type all along.
4523 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004524 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004525 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004526 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004527 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004528 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004529 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4530 TemplateId->getTemplateArgs(),
4531 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00004532 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4533 TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004534 TemplateId->TemplateNameLoc,
4535 TemplateId->LAngleLoc,
4536 TemplateArgsPtr,
4537 TemplateId->RAngleLoc);
4538 if (T.isInvalid() || !T.get()) {
4539 // Recover by assuming we had the right type all along.
4540 DestructedType = ObjectType;
4541 } else
4542 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004543 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004544
4545 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004546 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00004547 if (!DestructedType.isNull()) {
4548 if (!DestructedTypeInfo)
4549 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004550 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00004551 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4552 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004553
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004554 // Convert the name of the scope type (the type prior to '::') into a type.
4555 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004556 QualType ScopeType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004557 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004558 FirstTypeName.Identifier) {
4559 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004560 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00004561 FirstTypeName.StartLocation,
Douglas Gregora6ce6082011-02-25 18:19:59 +00004562 S, &SS, true, false, ObjectTypePtrForLookup);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004563 if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004564 Diag(FirstTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004565 diag::err_pseudo_dtor_destructor_non_type)
4566 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004567
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004568 if (isSFINAEContext())
4569 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004570
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004571 // Just drop this type. It's unnecessary anyway.
4572 ScopeType = QualType();
4573 } else
4574 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004575 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004576 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004577 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004578 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4579 TemplateId->getTemplateArgs(),
4580 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00004581 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4582 TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004583 TemplateId->TemplateNameLoc,
4584 TemplateId->LAngleLoc,
4585 TemplateArgsPtr,
4586 TemplateId->RAngleLoc);
4587 if (T.isInvalid() || !T.get()) {
4588 // Recover by dropping this type.
4589 ScopeType = QualType();
4590 } else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004591 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004592 }
4593 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004594
Douglas Gregor90ad9222010-02-24 23:02:30 +00004595 if (!ScopeType.isNull() && !ScopeTypeInfo)
4596 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
4597 FirstTypeName.StartLocation);
4598
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004599
John McCallb268a282010-08-23 23:25:46 +00004600 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00004601 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00004602 Destructed, HasTrailingLParen);
Douglas Gregore610ada2010-02-24 18:44:31 +00004603}
4604
David Blaikie1d578782011-12-16 16:03:09 +00004605ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4606 SourceLocation OpLoc,
4607 tok::TokenKind OpKind,
4608 SourceLocation TildeLoc,
4609 const DeclSpec& DS,
4610 bool HasTrailingLParen) {
4611
4612 QualType ObjectType = Base->getType();
4613 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4614 return ExprError();
4615
4616 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
4617
4618 TypeLocBuilder TLB;
4619 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
4620 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
4621 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
4622 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
4623
4624 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
4625 0, SourceLocation(), TildeLoc,
4626 Destructed, HasTrailingLParen);
4627}
4628
John Wiegley01296292011-04-08 18:41:53 +00004629ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004630 CXXMethodDecl *Method,
4631 bool HadMultipleCandidates) {
John Wiegley01296292011-04-08 18:41:53 +00004632 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
4633 FoundDecl, Method);
4634 if (Exp.isInvalid())
Douglas Gregor668443e2011-01-20 00:18:04 +00004635 return true;
Eli Friedmanf7195532009-12-09 04:53:56 +00004636
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004637 MemberExpr *ME =
John Wiegley01296292011-04-08 18:41:53 +00004638 new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00004639 SourceLocation(), Context.BoundMemberTy,
John McCall7decc9e2010-11-18 06:31:45 +00004640 VK_RValue, OK_Ordinary);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004641 if (HadMultipleCandidates)
4642 ME->setHadMultipleCandidates(true);
4643
John McCall7decc9e2010-11-18 06:31:45 +00004644 QualType ResultType = Method->getResultType();
4645 ExprValueKind VK = Expr::getValueKindForType(ResultType);
4646 ResultType = ResultType.getNonLValueExprType(Context);
4647
John Wiegley01296292011-04-08 18:41:53 +00004648 MarkDeclarationReferenced(Exp.get()->getLocStart(), Method);
Douglas Gregor27381f32009-11-23 12:27:39 +00004649 CXXMemberCallExpr *CE =
John McCall7decc9e2010-11-18 06:31:45 +00004650 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
John Wiegley01296292011-04-08 18:41:53 +00004651 Exp.get()->getLocEnd());
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00004652 return CE;
4653}
4654
Sebastian Redl4202c0f2010-09-10 20:55:43 +00004655ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4656 SourceLocation RParen) {
Sebastian Redl4202c0f2010-09-10 20:55:43 +00004657 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
4658 Operand->CanThrow(Context),
4659 KeyLoc, RParen));
4660}
4661
4662ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
4663 Expr *Operand, SourceLocation RParen) {
4664 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00004665}
4666
John McCall34376a62010-12-04 03:47:34 +00004667/// Perform the conversions required for an expression used in a
4668/// context that ignores the result.
John Wiegley01296292011-04-08 18:41:53 +00004669ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall526ab472011-10-25 17:37:35 +00004670 if (E->hasPlaceholderType()) {
4671 ExprResult result = CheckPlaceholderExpr(E);
4672 if (result.isInvalid()) return Owned(E);
4673 E = result.take();
4674 }
4675
John McCallfee942d2010-12-02 02:07:15 +00004676 // C99 6.3.2.1:
4677 // [Except in specific positions,] an lvalue that does not have
4678 // array type is converted to the value stored in the
4679 // designated object (and is no longer an lvalue).
John McCalld68b2d02011-06-27 21:24:11 +00004680 if (E->isRValue()) {
4681 // In C, function designators (i.e. expressions of function type)
4682 // are r-values, but we still want to do function-to-pointer decay
4683 // on them. This is both technically correct and convenient for
4684 // some clients.
4685 if (!getLangOptions().CPlusPlus && E->getType()->isFunctionType())
4686 return DefaultFunctionArrayConversion(E);
4687
4688 return Owned(E);
4689 }
John McCallfee942d2010-12-02 02:07:15 +00004690
John McCall34376a62010-12-04 03:47:34 +00004691 // Otherwise, this rule does not apply in C++, at least not for the moment.
John Wiegley01296292011-04-08 18:41:53 +00004692 if (getLangOptions().CPlusPlus) return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00004693
4694 // GCC seems to also exclude expressions of incomplete enum type.
4695 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
4696 if (!T->getDecl()->isComplete()) {
4697 // FIXME: stupid workaround for a codegen bug!
John Wiegley01296292011-04-08 18:41:53 +00004698 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
4699 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00004700 }
4701 }
4702
John Wiegley01296292011-04-08 18:41:53 +00004703 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
4704 if (Res.isInvalid())
4705 return Owned(E);
4706 E = Res.take();
4707
John McCallca61b652010-12-04 12:29:11 +00004708 if (!E->getType()->isVoidType())
4709 RequireCompleteType(E->getExprLoc(), E->getType(),
4710 diag::err_incomplete_type);
John Wiegley01296292011-04-08 18:41:53 +00004711 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00004712}
4713
John Wiegley01296292011-04-08 18:41:53 +00004714ExprResult Sema::ActOnFinishFullExpr(Expr *FE) {
4715 ExprResult FullExpr = Owned(FE);
4716
4717 if (!FullExpr.get())
Douglas Gregora6e053e2010-12-15 01:34:56 +00004718 return ExprError();
John McCall34376a62010-12-04 03:47:34 +00004719
John Wiegley01296292011-04-08 18:41:53 +00004720 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregor506bd562010-12-13 22:49:22 +00004721 return ExprError();
4722
Douglas Gregor95715f92011-12-15 00:53:32 +00004723 // Top-level message sends default to 'id' when we're in a debugger.
4724 if (getLangOptions().DebuggerSupport &&
4725 FullExpr.get()->getType() == Context.UnknownAnyTy &&
4726 isa<ObjCMessageExpr>(FullExpr.get())) {
4727 FullExpr = forceUnknownAnyToType(FullExpr.take(), Context.getObjCIdType());
4728 if (FullExpr.isInvalid())
4729 return ExprError();
4730 }
4731
John McCall3aef3d82011-04-10 19:13:55 +00004732 FullExpr = CheckPlaceholderExpr(FullExpr.take());
4733 if (FullExpr.isInvalid())
4734 return ExprError();
Douglas Gregor0ec210b2011-03-07 02:05:23 +00004735
John Wiegley01296292011-04-08 18:41:53 +00004736 FullExpr = IgnoredValueConversions(FullExpr.take());
4737 if (FullExpr.isInvalid())
4738 return ExprError();
4739
Richard Trieu021baa32011-09-23 20:10:00 +00004740 CheckImplicitConversions(FullExpr.get(), FullExpr.get()->getExprLoc());
John McCall5d413782010-12-06 08:20:24 +00004741 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00004742}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00004743
4744StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
4745 if (!FullStmt) return StmtError();
4746
John McCall5d413782010-12-06 08:20:24 +00004747 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00004748}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00004749
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004750Sema::IfExistsResult
4751Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
4752 CXXScopeSpec &SS,
4753 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00004754 DeclarationName TargetName = TargetNameInfo.getName();
4755 if (!TargetName)
Douglas Gregor43edb322011-10-24 22:31:10 +00004756 return IER_DoesNotExist;
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004757
Douglas Gregor43edb322011-10-24 22:31:10 +00004758 // If the name itself is dependent, then the result is dependent.
4759 if (TargetName.isDependentName())
4760 return IER_Dependent;
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004761
Francois Pichet4a7de3e2011-05-06 20:48:22 +00004762 // Do the redeclaration lookup in the current scope.
4763 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
4764 Sema::NotForRedeclaration);
Douglas Gregor43edb322011-10-24 22:31:10 +00004765 LookupParsedName(R, S, &SS);
Francois Pichet4a7de3e2011-05-06 20:48:22 +00004766 R.suppressDiagnostics();
Douglas Gregor43edb322011-10-24 22:31:10 +00004767
4768 switch (R.getResultKind()) {
4769 case LookupResult::Found:
4770 case LookupResult::FoundOverloaded:
4771 case LookupResult::FoundUnresolvedValue:
4772 case LookupResult::Ambiguous:
4773 return IER_Exists;
4774
4775 case LookupResult::NotFound:
4776 return IER_DoesNotExist;
4777
4778 case LookupResult::NotFoundInCurrentInstantiation:
4779 return IER_Dependent;
4780 }
David Blaikie8a40f702012-01-17 06:56:22 +00004781
4782 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet4a7de3e2011-05-06 20:48:22 +00004783}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004784
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00004785Sema::IfExistsResult
4786Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4787 bool IsIfExists, CXXScopeSpec &SS,
4788 UnqualifiedId &Name) {
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004789 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00004790
4791 // Check for unexpanded parameter packs.
4792 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
4793 collectUnexpandedParameterPacks(SS, Unexpanded);
4794 collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
4795 if (!Unexpanded.empty()) {
4796 DiagnoseUnexpandedParameterPacks(KeywordLoc,
4797 IsIfExists? UPPC_IfExists
4798 : UPPC_IfNotExists,
4799 Unexpanded);
4800 return IER_Error;
4801 }
4802
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004803 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
4804}
4805
Eli Friedmanc7c97142012-01-04 02:40:39 +00004806//===----------------------------------------------------------------------===//
4807// Lambdas.
4808//===----------------------------------------------------------------------===//
4809
Eli Friedman71c80552012-01-05 03:35:19 +00004810void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
4811 Declarator &ParamInfo,
4812 Scope *CurScope) {
4813 DeclContext *DC = CurContext;
Eli Friedman4817cf72012-01-06 03:05:34 +00004814 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
Eli Friedman71c80552012-01-05 03:35:19 +00004815 DC = DC->getParent();
Eli Friedmanc7c97142012-01-04 02:40:39 +00004816
Eli Friedman71c80552012-01-05 03:35:19 +00004817 // Start constructing the lambda class.
4818 CXXRecordDecl *Class = CXXRecordDecl::Create(Context, TTK_Class, DC,
4819 Intro.Range.getBegin(),
4820 /*IdLoc=*/SourceLocation(),
4821 /*Id=*/0);
4822 Class->startDefinition();
Eli Friedman73a04092012-01-07 04:59:52 +00004823 Class->setLambda(true);
Eli Friedman71c80552012-01-05 03:35:19 +00004824 CurContext->addDecl(Class);
Eli Friedmanc7c97142012-01-04 02:40:39 +00004825
Eli Friedman44803322012-01-07 01:08:17 +00004826 QualType ThisCaptureType;
Eli Friedman20139d32012-01-11 02:36:31 +00004827 llvm::DenseMap<VarDecl*, unsigned> CaptureMap;
4828 unsigned CXXThisCaptureIndex = 0;
Eli Friedman73a04092012-01-07 04:59:52 +00004829 llvm::SmallVector<LambdaScopeInfo::Capture, 4> Captures;
Eli Friedman44803322012-01-07 01:08:17 +00004830 for (llvm::SmallVector<LambdaCapture, 4>::const_iterator
4831 C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E; ++C) {
4832 if (C->Kind == LCK_This) {
4833 if (!ThisCaptureType.isNull()) {
4834 Diag(C->Loc, diag::err_capture_more_than_once) << "'this'";
4835 continue;
4836 }
4837
4838 if (Intro.Default == LCD_ByCopy) {
4839 Diag(C->Loc, diag::err_this_capture_with_copy_default);
4840 continue;
4841 }
4842
4843 ThisCaptureType = getCurrentThisType();
Eli Friedman44803322012-01-07 01:08:17 +00004844 if (ThisCaptureType.isNull()) {
4845 Diag(C->Loc, diag::err_invalid_this_use);
4846 continue;
4847 }
Eli Friedman73a04092012-01-07 04:59:52 +00004848 CheckCXXThisCapture(C->Loc);
4849
Eli Friedman20139d32012-01-11 02:36:31 +00004850 // FIXME: Need getCurCapture().
4851 bool isNested = getCurBlock() || getCurLambda();
4852 CapturingScopeInfo::Capture Cap(CapturingScopeInfo::Capture::ThisCapture,
4853 isNested);
4854 Captures.push_back(Cap);
4855 CXXThisCaptureIndex = Captures.size();
Eli Friedman44803322012-01-07 01:08:17 +00004856 continue;
4857 }
4858
4859 assert(C->Id && "missing identifier for capture");
4860
4861 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
4862 Diag(C->Loc, diag::err_reference_capture_with_reference_default);
4863 continue;
4864 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
4865 Diag(C->Loc, diag::err_copy_capture_with_copy_default);
4866 continue;
4867 }
4868
Eli Friedman44803322012-01-07 01:08:17 +00004869 DeclarationNameInfo Name(C->Id, C->Loc);
4870 LookupResult R(*this, Name, LookupOrdinaryName);
4871 CXXScopeSpec ScopeSpec;
4872 LookupParsedName(R, CurScope, &ScopeSpec);
4873 if (R.isAmbiguous())
4874 continue;
Kaelyn Uhrain79d01c12012-01-18 05:58:54 +00004875 if (R.empty()) {
4876 DeclFilterCCC<VarDecl> Validator;
4877 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
Eli Friedman44803322012-01-07 01:08:17 +00004878 continue;
Kaelyn Uhrain79d01c12012-01-18 05:58:54 +00004879 }
Eli Friedman44803322012-01-07 01:08:17 +00004880
4881 VarDecl *Var = R.getAsSingle<VarDecl>();
4882 if (!Var) {
4883 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
4884 continue;
4885 }
4886
Eli Friedman20139d32012-01-11 02:36:31 +00004887 if (CaptureMap.count(Var)) {
4888 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
4889 continue;
4890 }
4891
Eli Friedman44803322012-01-07 01:08:17 +00004892 if (!Var->hasLocalStorage()) {
4893 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
4894 continue;
4895 }
4896
Eli Friedman20139d32012-01-11 02:36:31 +00004897 // FIXME: This is completely wrong for nested captures and variables
4898 // with a non-trivial constructor.
4899 // FIXME: We should refuse to capture __block variables.
4900 Captures.push_back(LambdaScopeInfo::Capture(Var, C->Kind == LCK_ByRef,
4901 /*isNested*/false, 0));
4902 CaptureMap[Var] = Captures.size();
Eli Friedman44803322012-01-07 01:08:17 +00004903 }
4904
Eli Friedman71c80552012-01-05 03:35:19 +00004905 // Build the call operator; we don't really have all the relevant information
4906 // at this point, but we need something to attach child declarations to.
Eli Friedman4817cf72012-01-06 03:05:34 +00004907 QualType MethodTy;
Eli Friedman36d12942012-01-04 04:41:38 +00004908 TypeSourceInfo *MethodTyInfo;
Eli Friedman4817cf72012-01-06 03:05:34 +00004909 if (ParamInfo.getNumTypeObjects() == 0) {
4910 FunctionProtoType::ExtProtoInfo EPI;
4911 EPI.TypeQuals |= DeclSpec::TQ_const;
4912 MethodTy = Context.getFunctionType(Context.DependentTy,
4913 /*Args=*/0, /*NumArgs=*/0, EPI);
4914 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
4915 } else {
4916 assert(ParamInfo.isFunctionDeclarator() &&
4917 "lambda-declarator is a function");
4918 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
4919 if (!FTI.hasMutableQualifier())
4920 FTI.TypeQuals |= DeclSpec::TQ_const;
4921 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
4922 // FIXME: Can these asserts actually fail?
4923 assert(MethodTyInfo && "no type from lambda-declarator");
4924 MethodTy = MethodTyInfo->getType();
4925 assert(!MethodTy.isNull() && "no type from lambda declarator");
4926 }
Eli Friedman36d12942012-01-04 04:41:38 +00004927
Eli Friedman71c80552012-01-05 03:35:19 +00004928 DeclarationName MethodName
4929 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
4930 CXXMethodDecl *Method
4931 = CXXMethodDecl::Create(Context,
4932 Class,
4933 ParamInfo.getSourceRange().getEnd(),
4934 DeclarationNameInfo(MethodName,
4935 /*NameLoc=*/SourceLocation()),
Eli Friedman4817cf72012-01-06 03:05:34 +00004936 MethodTy,
Eli Friedman71c80552012-01-05 03:35:19 +00004937 MethodTyInfo,
4938 /*isStatic=*/false,
4939 SC_None,
4940 /*isInline=*/true,
4941 /*isConstExpr=*/false,
4942 ParamInfo.getSourceRange().getEnd());
4943 Method->setAccess(AS_public);
4944 Class->addDecl(Method);
4945 Method->setLexicalDeclContext(DC); // FIXME: Is this really correct?
4946
Eli Friedman71c80552012-01-05 03:35:19 +00004947 ProcessDeclAttributes(CurScope, Method, ParamInfo);
4948
Eli Friedman71c80552012-01-05 03:35:19 +00004949 // Enter a new evaluation context to insulate the block from any
4950 // cleanups from the enclosing full-expression.
4951 PushExpressionEvaluationContext(PotentiallyEvaluated);
4952
4953 PushDeclContext(CurScope, Method);
Eli Friedman4817cf72012-01-06 03:05:34 +00004954
Eli Friedman4817cf72012-01-06 03:05:34 +00004955 // Set the parameters on the decl, if specified.
4956 if (isa<FunctionProtoTypeLoc>(MethodTyInfo->getTypeLoc())) {
4957 FunctionProtoTypeLoc Proto =
4958 cast<FunctionProtoTypeLoc>(MethodTyInfo->getTypeLoc());
4959 Method->setParams(Proto.getParams());
4960 CheckParmsForFunctionDef(Method->param_begin(),
4961 Method->param_end(),
4962 /*CheckParameterNames=*/false);
4963
4964 // Introduce our parameters into the function scope
4965 for (unsigned p = 0, NumParams = Method->getNumParams(); p < NumParams; ++p) {
4966 ParmVarDecl *Param = Method->getParamDecl(p);
4967 Param->setOwningFunction(Method);
4968
4969 // If this has an identifier, add it to the scope stack.
4970 if (Param->getIdentifier()) {
4971 CheckShadow(CurScope, Param);
4972
4973 PushOnScopeChains(Param, CurScope);
4974 }
4975 }
4976 }
4977
Eli Friedman73a04092012-01-07 04:59:52 +00004978 // Introduce the lambda scope.
4979 PushLambdaScope(Class);
4980
4981 LambdaScopeInfo *LSI = getCurLambda();
Eli Friedman20139d32012-01-11 02:36:31 +00004982 LSI->CXXThisCaptureIndex = CXXThisCaptureIndex;
4983 std::swap(LSI->CaptureMap, CaptureMap);
Eli Friedman73a04092012-01-07 04:59:52 +00004984 std::swap(LSI->Captures, Captures);
Eli Friedman20139d32012-01-11 02:36:31 +00004985 LSI->NumExplicitCaptures = Captures.size();
4986 if (Intro.Default == LCD_ByCopy)
4987 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
4988 else if (Intro.Default == LCD_ByRef)
4989 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
Eli Friedman73a04092012-01-07 04:59:52 +00004990
Eli Friedman4817cf72012-01-06 03:05:34 +00004991 const FunctionType *Fn = MethodTy->getAs<FunctionType>();
4992 QualType RetTy = Fn->getResultType();
4993 if (RetTy != Context.DependentTy) {
4994 LSI->ReturnType = RetTy;
Eli Friedman20139d32012-01-11 02:36:31 +00004995 } else {
Eli Friedman4817cf72012-01-06 03:05:34 +00004996 LSI->HasImplicitReturnType = true;
4997 }
4998
4999 // FIXME: Check return type is complete, !isObjCObjectType
5000
Eli Friedmanc7c97142012-01-04 02:40:39 +00005001}
5002
5003void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope) {
5004 // Leave the expression-evaluation context.
5005 DiscardCleanupsInEvaluationContext();
5006 PopExpressionEvaluationContext();
5007
5008 // Leave the context of the lambda.
Eli Friedman71c80552012-01-05 03:35:19 +00005009 PopDeclContext();
5010 PopFunctionScopeInfo();
Eli Friedmanc7c97142012-01-04 02:40:39 +00005011}
5012
5013ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc,
5014 Stmt *Body, Scope *CurScope) {
5015 // FIXME: Implement
5016 Diag(StartLoc, diag::err_lambda_unsupported);
5017 ActOnLambdaError(StartLoc, CurScope);
5018 return ExprError();
5019}