blob: fceb6398077b70109429b8fe490852dbedefa274 [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 bool isUnevaluatedOperand = true;
Douglas Gregor9da64192010-04-26 22:37:10 +0000314 if (E && !E->isTypeDependent()) {
John McCall50a2c2c2011-10-11 23:14:30 +0000315 if (E->getType()->isPlaceholderType()) {
316 ExprResult result = CheckPlaceholderExpr(E);
317 if (result.isInvalid()) return ExprError();
318 E = result.take();
319 }
320
Douglas Gregor9da64192010-04-26 22:37:10 +0000321 QualType T = E->getType();
322 if (const RecordType *RecordT = T->getAs<RecordType>()) {
323 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
324 // C++ [expr.typeid]p3:
325 // [...] If the type of the expression is a class type, the class
326 // shall be completely-defined.
327 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
328 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000329
Douglas Gregor9da64192010-04-26 22:37:10 +0000330 // C++ [expr.typeid]p3:
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000331 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor9da64192010-04-26 22:37:10 +0000332 // polymorphic class type [...] [the] expression is an unevaluated
333 // operand. [...]
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000334 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000335 isUnevaluatedOperand = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000336
337 // We require a vtable to query the type at run time.
338 MarkVTableUsed(TypeidLoc, RecordD);
339 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000340 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000341
Douglas Gregor9da64192010-04-26 22:37:10 +0000342 // C++ [expr.typeid]p4:
343 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000344 // cv-qualified type, the result of the typeid expression refers to a
345 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor9da64192010-04-26 22:37:10 +0000346 // type.
Douglas Gregor876cec22010-06-02 06:16:02 +0000347 Qualifiers Quals;
348 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
349 if (!Context.hasSameType(T, UnqualT)) {
350 T = UnqualT;
Eli Friedmanbe4b3632011-09-27 21:58:52 +0000351 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).take();
Douglas Gregor9da64192010-04-26 22:37:10 +0000352 }
353 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000354
Douglas Gregor9da64192010-04-26 22:37:10 +0000355 // If this is an unevaluated operand, clear out the set of
356 // declaration references we have been computing and eliminate any
357 // temporaries introduced in its computation.
358 if (isUnevaluatedOperand)
359 ExprEvalContexts.back().Context = Unevaluated;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000360
Douglas Gregor9da64192010-04-26 22:37:10 +0000361 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCallb268a282010-08-23 23:25:46 +0000362 E,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000363 SourceRange(TypeidLoc, RParenLoc)));
Douglas Gregor9da64192010-04-26 22:37:10 +0000364}
365
366/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCalldadc5752010-08-24 06:29:42 +0000367ExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000368Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
369 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000370 // Find the std::type_info type.
Sebastian Redl7ac97412011-03-31 19:29:24 +0000371 if (!getStdNamespace())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000372 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000373
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000374 if (!CXXTypeInfoDecl) {
375 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
376 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
377 LookupQualifiedName(R, getStdNamespace());
378 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
379 if (!CXXTypeInfoDecl)
380 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
381 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000382
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000383 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000384
Douglas Gregor9da64192010-04-26 22:37:10 +0000385 if (isType) {
386 // The operand is a type; handle it as such.
387 TypeSourceInfo *TInfo = 0;
John McCallba7bf592010-08-24 05:47:05 +0000388 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
389 &TInfo);
Douglas Gregor9da64192010-04-26 22:37:10 +0000390 if (T.isNull())
391 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000392
Douglas Gregor9da64192010-04-26 22:37:10 +0000393 if (!TInfo)
394 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000395
Douglas Gregor9da64192010-04-26 22:37:10 +0000396 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000397 }
Mike Stump11289f42009-09-09 15:08:12 +0000398
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000399 // The operand is an expression.
John McCallb268a282010-08-23 23:25:46 +0000400 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000401}
402
Francois Pichetb7577652010-12-27 01:32:00 +0000403/// Retrieve the UuidAttr associated with QT.
404static UuidAttr *GetUuidAttrOfType(QualType QT) {
405 // Optionally remove one level of pointer, reference or array indirection.
John McCall424cec92011-01-19 06:33:43 +0000406 const Type *Ty = QT.getTypePtr();;
Francois Pichet9dddd402010-12-20 03:51:03 +0000407 if (QT->isPointerType() || QT->isReferenceType())
408 Ty = QT->getPointeeType().getTypePtr();
409 else if (QT->isArrayType())
410 Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
411
Francois Pichet59d2b012011-05-08 10:02:20 +0000412 // Loop all record redeclaration looking for an uuid attribute.
Francois Pichetb7577652010-12-27 01:32:00 +0000413 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Francois Pichet59d2b012011-05-08 10:02:20 +0000414 for (CXXRecordDecl::redecl_iterator I = RD->redecls_begin(),
415 E = RD->redecls_end(); I != E; ++I) {
416 if (UuidAttr *Uuid = I->getAttr<UuidAttr>())
Francois Pichetb7577652010-12-27 01:32:00 +0000417 return Uuid;
Francois Pichetb7577652010-12-27 01:32:00 +0000418 }
Francois Pichet59d2b012011-05-08 10:02:20 +0000419
Francois Pichetb7577652010-12-27 01:32:00 +0000420 return 0;
Francois Pichet9dddd402010-12-20 03:51:03 +0000421}
422
Francois Pichet9f4f2072010-09-08 12:20:18 +0000423/// \brief Build a Microsoft __uuidof expression with a type operand.
424ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
425 SourceLocation TypeidLoc,
426 TypeSourceInfo *Operand,
427 SourceLocation RParenLoc) {
Francois Pichetb7577652010-12-27 01:32:00 +0000428 if (!Operand->getType()->isDependentType()) {
429 if (!GetUuidAttrOfType(Operand->getType()))
430 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
431 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000432
Francois Pichet9f4f2072010-09-08 12:20:18 +0000433 // FIXME: add __uuidof semantic analysis for type operand.
434 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
435 Operand,
436 SourceRange(TypeidLoc, RParenLoc)));
437}
438
439/// \brief Build a Microsoft __uuidof expression with an expression operand.
440ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
441 SourceLocation TypeidLoc,
442 Expr *E,
443 SourceLocation RParenLoc) {
Francois Pichetb7577652010-12-27 01:32:00 +0000444 if (!E->getType()->isDependentType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000445 if (!GetUuidAttrOfType(E->getType()) &&
Francois Pichetb7577652010-12-27 01:32:00 +0000446 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
447 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
448 }
449 // FIXME: add __uuidof semantic analysis for type operand.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000450 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
451 E,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000452 SourceRange(TypeidLoc, RParenLoc)));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000453}
454
455/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
456ExprResult
457Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
458 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000459 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000460 if (!MSVCGuidDecl) {
461 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
462 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
463 LookupQualifiedName(R, Context.getTranslationUnitDecl());
464 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
465 if (!MSVCGuidDecl)
466 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000467 }
468
Francois Pichet9f4f2072010-09-08 12:20:18 +0000469 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000470
Francois Pichet9f4f2072010-09-08 12:20:18 +0000471 if (isType) {
472 // The operand is a type; handle it as such.
473 TypeSourceInfo *TInfo = 0;
474 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
475 &TInfo);
476 if (T.isNull())
477 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000478
Francois Pichet9f4f2072010-09-08 12:20:18 +0000479 if (!TInfo)
480 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
481
482 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
483 }
484
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000485 // The operand is an expression.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000486 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
487}
488
Steve Naroff66356bd2007-09-16 14:56:35 +0000489/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCalldadc5752010-08-24 06:29:42 +0000490ExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000491Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000492 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000493 "Unknown C++ Boolean value!");
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000494 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
495 Context.BoolTy, OpLoc));
Bill Wendling4073ed52007-02-13 01:51:42 +0000496}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000497
Sebastian Redl576fd422009-05-10 18:38:11 +0000498/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCalldadc5752010-08-24 06:29:42 +0000499ExprResult
Sebastian Redl576fd422009-05-10 18:38:11 +0000500Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
501 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
502}
503
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000504/// ActOnCXXThrow - Parse throw expressions.
John McCalldadc5752010-08-24 06:29:42 +0000505ExprResult
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000506Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
507 bool IsThrownVarInScope = false;
508 if (Ex) {
509 // C++0x [class.copymove]p31:
510 // When certain criteria are met, an implementation is allowed to omit the
511 // copy/move construction of a class object [...]
512 //
513 // - in a throw-expression, when the operand is the name of a
514 // non-volatile automatic object (other than a function or catch-
515 // clause parameter) whose scope does not extend beyond the end of the
516 // innermost enclosing try-block (if there is one), the copy/move
517 // operation from the operand to the exception object (15.1) can be
518 // omitted by constructing the automatic object directly into the
519 // exception object
520 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
521 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
522 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
523 for( ; S; S = S->getParent()) {
524 if (S->isDeclScope(Var)) {
525 IsThrownVarInScope = true;
526 break;
527 }
528
529 if (S->getFlags() &
530 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
531 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
532 Scope::TryScope))
533 break;
534 }
535 }
536 }
537 }
538
539 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
540}
541
542ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
543 bool IsThrownVarInScope) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000544 // Don't report an error if 'throw' is used in system headers.
Anders Carlssone96ab552011-02-28 02:27:16 +0000545 if (!getLangOptions().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000546 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb94ad3e2011-02-19 21:53:09 +0000547 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000548
John Wiegley01296292011-04-08 18:41:53 +0000549 if (Ex && !Ex->isTypeDependent()) {
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000550 ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex, IsThrownVarInScope);
John Wiegley01296292011-04-08 18:41:53 +0000551 if (ExRes.isInvalid())
552 return ExprError();
553 Ex = ExRes.take();
554 }
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000555
556 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc,
557 IsThrownVarInScope));
Sebastian Redl4de47b42009-04-27 20:27:31 +0000558}
559
560/// CheckCXXThrowOperand - Validate the operand of a throw.
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000561ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
562 bool IsThrownVarInScope) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000563 // C++ [except.throw]p3:
Douglas Gregor247894b2009-12-23 22:04:40 +0000564 // A throw-expression initializes a temporary object, called the exception
565 // object, the type of which is determined by removing any top-level
566 // cv-qualifiers from the static type of the operand of throw and adjusting
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000567 // the type from "array of T" or "function returning T" to "pointer to T"
Douglas Gregor247894b2009-12-23 22:04:40 +0000568 // or "pointer to function returning T", [...]
569 if (E->getType().hasQualifiers())
John Wiegley01296292011-04-08 18:41:53 +0000570 E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
Eli Friedmanbe4b3632011-09-27 21:58:52 +0000571 E->getValueKind()).take();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000572
John Wiegley01296292011-04-08 18:41:53 +0000573 ExprResult Res = DefaultFunctionArrayConversion(E);
574 if (Res.isInvalid())
575 return ExprError();
576 E = Res.take();
Sebastian Redl4de47b42009-04-27 20:27:31 +0000577
578 // If the type of the exception would be an incomplete type or a pointer
579 // to an incomplete type other than (cv) void the program is ill-formed.
580 QualType Ty = E->getType();
John McCall2e6567a2010-04-22 01:10:34 +0000581 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000582 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000583 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000584 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000585 }
586 if (!isPointer || !Ty->isVoidType()) {
587 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlsson029fc692009-08-26 22:59:12 +0000588 PDiag(isPointer ? diag::err_throw_incomplete_ptr
589 : diag::err_throw_incomplete)
590 << E->getSourceRange()))
John Wiegley01296292011-04-08 18:41:53 +0000591 return ExprError();
Rafael Espindola70e040d2010-03-02 21:28:26 +0000592
Douglas Gregore8154332010-04-15 18:05:39 +0000593 if (RequireNonAbstractType(ThrowLoc, E->getType(),
594 PDiag(diag::err_throw_abstract_type)
595 << E->getSourceRange()))
John Wiegley01296292011-04-08 18:41:53 +0000596 return ExprError();
Sebastian Redl4de47b42009-04-27 20:27:31 +0000597 }
598
John McCall2e6567a2010-04-22 01:10:34 +0000599 // Initialize the exception result. This implicitly weeds out
600 // abstract types or types with inaccessible copy constructors.
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000601
602 // C++0x [class.copymove]p31:
603 // When certain criteria are met, an implementation is allowed to omit the
604 // copy/move construction of a class object [...]
605 //
606 // - in a throw-expression, when the operand is the name of a
607 // non-volatile automatic object (other than a function or catch-clause
608 // parameter) whose scope does not extend beyond the end of the
609 // innermost enclosing try-block (if there is one), the copy/move
610 // operation from the operand to the exception object (15.1) can be
611 // omitted by constructing the automatic object directly into the
612 // exception object
613 const VarDecl *NRVOVariable = 0;
614 if (IsThrownVarInScope)
615 NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
616
John McCall2e6567a2010-04-22 01:10:34 +0000617 InitializedEntity Entity =
Douglas Gregorc74edc22011-01-21 22:46:35 +0000618 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000619 /*NRVO=*/NRVOVariable != 0);
John Wiegley01296292011-04-08 18:41:53 +0000620 Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000621 QualType(), E,
622 IsThrownVarInScope);
John McCall2e6567a2010-04-22 01:10:34 +0000623 if (Res.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000624 return ExprError();
625 E = Res.take();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000626
Eli Friedman91a3d272010-06-03 20:39:03 +0000627 // If the exception has class type, we need additional handling.
628 const RecordType *RecordTy = Ty->getAs<RecordType>();
629 if (!RecordTy)
John Wiegley01296292011-04-08 18:41:53 +0000630 return Owned(E);
Eli Friedman91a3d272010-06-03 20:39:03 +0000631 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
632
Douglas Gregor88d292c2010-05-13 16:44:06 +0000633 // If we are throwing a polymorphic class type or pointer thereof,
634 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000635 MarkVTableUsed(ThrowLoc, RD);
636
Eli Friedman36ebbec2010-10-12 20:32:36 +0000637 // If a pointer is thrown, the referenced object will not be destroyed.
638 if (isPointer)
John Wiegley01296292011-04-08 18:41:53 +0000639 return Owned(E);
Eli Friedman36ebbec2010-10-12 20:32:36 +0000640
Eli Friedman91a3d272010-06-03 20:39:03 +0000641 // If the class has a non-trivial destructor, we must be able to call it.
642 if (RD->hasTrivialDestructor())
John Wiegley01296292011-04-08 18:41:53 +0000643 return Owned(E);
Eli Friedman91a3d272010-06-03 20:39:03 +0000644
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000645 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +0000646 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman91a3d272010-06-03 20:39:03 +0000647 if (!Destructor)
John Wiegley01296292011-04-08 18:41:53 +0000648 return Owned(E);
Eli Friedman91a3d272010-06-03 20:39:03 +0000649
650 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
651 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregor747eb782010-07-08 06:14:04 +0000652 PDiag(diag::err_access_dtor_exception) << Ty);
John Wiegley01296292011-04-08 18:41:53 +0000653 return Owned(E);
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000654}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000655
Eli Friedman73a04092012-01-07 04:59:52 +0000656QualType Sema::getCurrentThisType() {
657 DeclContext *DC = getFunctionLevelDeclContext();
Richard Smith938f40b2011-06-11 17:19:42 +0000658 QualType ThisTy;
659 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
660 if (method && method->isInstance())
661 ThisTy = method->getThisType(Context);
662 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
663 // C++0x [expr.prim]p4:
664 // Otherwise, if a member-declarator declares a non-static data member
665 // of a class X, the expression this is a prvalue of type "pointer to X"
666 // within the optional brace-or-equal-initializer.
667 Scope *S = getScopeForContext(DC);
668 if (!S || S->getFlags() & Scope::ThisScope)
669 ThisTy = Context.getPointerType(Context.getRecordType(RD));
670 }
John McCallc63de662011-02-02 13:00:07 +0000671
Richard Smith938f40b2011-06-11 17:19:42 +0000672 return ThisTy;
John McCallf3a88602011-02-03 08:15:49 +0000673}
674
Eli Friedman73a04092012-01-07 04:59:52 +0000675void Sema::CheckCXXThisCapture(SourceLocation Loc) {
676 // We don't need to capture this in an unevaluated context.
677 if (ExprEvalContexts.back().Context == Unevaluated)
678 return;
679
680 // Otherwise, check that we can capture 'this'.
681 unsigned NumClosures = 0;
682 for (unsigned idx = FunctionScopes.size() - 1; idx != 0; idx--) {
Eli Friedman20139d32012-01-11 02:36:31 +0000683 if (CapturingScopeInfo *CSI =
684 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
685 if (CSI->CXXThisCaptureIndex != 0) {
686 // 'this' is already being captured; there isn't anything more to do.
Eli Friedman73a04092012-01-07 04:59:52 +0000687 break;
688 }
Eli Friedman20139d32012-01-11 02:36:31 +0000689 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
690 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block) {
691 // This closure can implicitly capture 'this'; continue looking upwards.
Eli Friedman73a04092012-01-07 04:59:52 +0000692 // FIXME: Is this check correct? The rules in the standard are a bit
693 // unclear.
694 NumClosures++;
695 continue;
696 }
Eli Friedman20139d32012-01-11 02:36:31 +0000697 // This context can't implicitly capture 'this'; fail out.
Eli Friedman73a04092012-01-07 04:59:52 +0000698 // (We need to delay the diagnostic in the
699 // PotentiallyPotentiallyEvaluated case because it doesn't apply to
700 // unevaluated contexts.)
701 if (ExprEvalContexts.back().Context == PotentiallyPotentiallyEvaluated)
702 ExprEvalContexts.back()
703 .addDiagnostic(Loc, PDiag(diag::err_implicit_this_capture));
704 else
705 Diag(Loc, diag::err_implicit_this_capture);
706 return;
707 }
Eli Friedman73a04092012-01-07 04:59:52 +0000708 break;
709 }
710
711 // Mark that we're implicitly capturing 'this' in all the scopes we skipped.
712 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
713 // contexts.
714 for (unsigned idx = FunctionScopes.size() - 1;
715 NumClosures; --idx, --NumClosures) {
Eli Friedman20139d32012-01-11 02:36:31 +0000716 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
717 bool isNested = NumClosures > 1;
718 CSI->AddThisCapture(isNested);
Eli Friedman73a04092012-01-07 04:59:52 +0000719 }
720}
721
Richard Smith938f40b2011-06-11 17:19:42 +0000722ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCallf3a88602011-02-03 08:15:49 +0000723 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
724 /// is a non-lvalue expression whose value is the address of the object for
725 /// which the function is called.
726
Douglas Gregor09deffa2011-10-18 16:47:30 +0000727 QualType ThisTy = getCurrentThisType();
Richard Smith938f40b2011-06-11 17:19:42 +0000728 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCallf3a88602011-02-03 08:15:49 +0000729
Eli Friedman73a04092012-01-07 04:59:52 +0000730 CheckCXXThisCapture(Loc);
Richard Smith938f40b2011-06-11 17:19:42 +0000731 return Owned(new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000732}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000733
John McCalldadc5752010-08-24 06:29:42 +0000734ExprResult
Douglas Gregor2b88c112010-09-08 00:15:04 +0000735Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000736 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000737 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000738 SourceLocation RParenLoc) {
Douglas Gregor7df89f52010-02-05 19:11:37 +0000739 if (!TypeRep)
740 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000741
John McCall97513962010-01-15 18:39:57 +0000742 TypeSourceInfo *TInfo;
743 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
744 if (!TInfo)
745 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregor2b88c112010-09-08 00:15:04 +0000746
747 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
748}
749
750/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
751/// Can be interpreted either as function-style casting ("int(x)")
752/// or class type construction ("ClassType(x,y,z)")
753/// or creation of a value-initialized type ("int()").
754ExprResult
755Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
756 SourceLocation LParenLoc,
757 MultiExprArg exprs,
758 SourceLocation RParenLoc) {
759 QualType Ty = TInfo->getType();
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000760 unsigned NumExprs = exprs.size();
761 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregor2b88c112010-09-08 00:15:04 +0000762 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000763 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
764
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000765 if (Ty->isDependentType() ||
Douglas Gregor0950e412009-03-13 21:01:28 +0000766 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000767 exprs.release();
Mike Stump11289f42009-09-09 15:08:12 +0000768
Douglas Gregor2b88c112010-09-08 00:15:04 +0000769 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregorce934142009-05-20 18:46:25 +0000770 LParenLoc,
771 Exprs, NumExprs,
772 RParenLoc));
Douglas Gregor0950e412009-03-13 21:01:28 +0000773 }
774
Anders Carlsson55243162009-08-27 03:53:50 +0000775 if (Ty->isArrayType())
776 return ExprError(Diag(TyBeginLoc,
777 diag::err_value_init_for_array_type) << FullRange);
778 if (!Ty->isVoidType() &&
779 RequireCompleteType(TyBeginLoc, Ty,
780 PDiag(diag::err_invalid_incomplete_type_use)
781 << FullRange))
782 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000783
Anders Carlsson55243162009-08-27 03:53:50 +0000784 if (RequireNonAbstractType(TyBeginLoc, Ty,
785 diag::err_allocation_of_abstract_type))
786 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000787
788
Douglas Gregordd04d332009-01-16 18:33:17 +0000789 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000790 // If the expression list is a single expression, the type conversion
791 // expression is equivalent (in definedness, and if defined in meaning) to the
792 // corresponding cast expression.
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000793 if (NumExprs == 1) {
John McCallb50451a2011-10-05 07:41:44 +0000794 Expr *Arg = Exprs[0];
Anders Carlssone9766d52009-09-09 21:33:21 +0000795 exprs.release();
John McCallb50451a2011-10-05 07:41:44 +0000796 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000797 }
798
Douglas Gregor8ec51732010-09-08 21:40:08 +0000799 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
800 InitializationKind Kind
801 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
802 LParenLoc, RParenLoc)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000803 : InitializationKind::CreateValue(TyBeginLoc,
Douglas Gregor8ec51732010-09-08 21:40:08 +0000804 LParenLoc, RParenLoc);
805 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
806 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000807
Douglas Gregor8ec51732010-09-08 21:40:08 +0000808 // FIXME: Improve AST representation?
809 return move(Result);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000810}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000811
John McCall284c48f2011-01-27 09:37:56 +0000812/// doesUsualArrayDeleteWantSize - Answers whether the usual
813/// operator delete[] for the given type has a size_t parameter.
814static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
815 QualType allocType) {
816 const RecordType *record =
817 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
818 if (!record) return false;
819
820 // Try to find an operator delete[] in class scope.
821
822 DeclarationName deleteName =
823 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
824 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
825 S.LookupQualifiedName(ops, record->getDecl());
826
827 // We're just doing this for information.
828 ops.suppressDiagnostics();
829
830 // Very likely: there's no operator delete[].
831 if (ops.empty()) return false;
832
833 // If it's ambiguous, it should be illegal to call operator delete[]
834 // on this thing, so it doesn't matter if we allocate extra space or not.
835 if (ops.isAmbiguous()) return false;
836
837 LookupResult::Filter filter = ops.makeFilter();
838 while (filter.hasNext()) {
839 NamedDecl *del = filter.next()->getUnderlyingDecl();
840
841 // C++0x [basic.stc.dynamic.deallocation]p2:
842 // A template instance is never a usual deallocation function,
843 // regardless of its signature.
844 if (isa<FunctionTemplateDecl>(del)) {
845 filter.erase();
846 continue;
847 }
848
849 // C++0x [basic.stc.dynamic.deallocation]p2:
850 // If class T does not declare [an operator delete[] with one
851 // parameter] but does declare a member deallocation function
852 // named operator delete[] with exactly two parameters, the
853 // second of which has type std::size_t, then this function
854 // is a usual deallocation function.
855 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
856 filter.erase();
857 continue;
858 }
859 }
860 filter.done();
861
862 if (!ops.isSingleResult()) return false;
863
864 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
865 return (del->getNumParams() == 2);
866}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000867
Sebastian Redlbd150f42008-11-21 19:14:01 +0000868/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
869/// @code new (memory) int[size][4] @endcode
870/// or
871/// @code ::new Foo(23, "hello") @endcode
872/// For the interpretation of this heap of arguments, consult the base version.
John McCalldadc5752010-08-24 06:29:42 +0000873ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +0000874Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000875 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000876 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl351bb782008-12-02 14:43:59 +0000877 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000878 MultiExprArg ConstructorArgs,
Mike Stump11289f42009-09-09 15:08:12 +0000879 SourceLocation ConstructorRParen) {
Richard Smith30482bc2011-02-20 03:19:35 +0000880 bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
881
Sebastian Redl351bb782008-12-02 14:43:59 +0000882 Expr *ArraySize = 0;
Sebastian Redl351bb782008-12-02 14:43:59 +0000883 // If the specified type is an array, unwrap it and save the expression.
884 if (D.getNumTypeObjects() > 0 &&
885 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
886 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smith30482bc2011-02-20 03:19:35 +0000887 if (TypeContainsAuto)
888 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
889 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000890 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000891 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
892 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000893 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000894 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
895 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000896
Sebastian Redl351bb782008-12-02 14:43:59 +0000897 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000898 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +0000899 }
900
Douglas Gregor73341c42009-09-11 00:18:58 +0000901 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000902 if (ArraySize) {
903 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +0000904 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
905 break;
906
907 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
908 if (Expr *NumElts = (Expr *)Array.NumElts) {
909 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
910 !NumElts->isIntegerConstantExpr(Context)) {
911 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
912 << NumElts->getSourceRange();
913 return ExprError();
914 }
915 }
916 }
917 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000918
Argyrios Kyrtzidis3ff13572011-06-28 03:01:23 +0000919 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
John McCall8cb7bdf2010-06-04 23:28:52 +0000920 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000921 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000922 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000923
Mike Stump11289f42009-09-09 15:08:12 +0000924 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000925 PlacementLParen,
Mike Stump11289f42009-09-09 15:08:12 +0000926 move(PlacementArgs),
Douglas Gregord0fefba2009-05-21 00:00:09 +0000927 PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +0000928 TypeIdParens,
Mike Stump11289f42009-09-09 15:08:12 +0000929 AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +0000930 TInfo,
John McCallb268a282010-08-23 23:25:46 +0000931 ArraySize,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000932 ConstructorLParen,
933 move(ConstructorArgs),
Richard Smith30482bc2011-02-20 03:19:35 +0000934 ConstructorRParen,
935 TypeContainsAuto);
Douglas Gregord0fefba2009-05-21 00:00:09 +0000936}
937
John McCalldadc5752010-08-24 06:29:42 +0000938ExprResult
Douglas Gregord0fefba2009-05-21 00:00:09 +0000939Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
940 SourceLocation PlacementLParen,
941 MultiExprArg PlacementArgs,
942 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +0000943 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000944 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +0000945 TypeSourceInfo *AllocTypeInfo,
John McCallb268a282010-08-23 23:25:46 +0000946 Expr *ArraySize,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000947 SourceLocation ConstructorLParen,
948 MultiExprArg ConstructorArgs,
Richard Smith30482bc2011-02-20 03:19:35 +0000949 SourceLocation ConstructorRParen,
950 bool TypeMayContainAuto) {
Douglas Gregor0744ef62010-09-07 21:49:58 +0000951 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
Sebastian Redl351bb782008-12-02 14:43:59 +0000952
Richard Smith30482bc2011-02-20 03:19:35 +0000953 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
954 if (TypeMayContainAuto && AllocType->getContainedAutoType()) {
955 if (ConstructorArgs.size() == 0)
956 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
957 << AllocType << TypeRange);
958 if (ConstructorArgs.size() != 1) {
959 Expr *FirstBad = ConstructorArgs.get()[1];
960 return ExprError(Diag(FirstBad->getSourceRange().getBegin(),
961 diag::err_auto_new_ctor_multiple_expressions)
962 << AllocType << TypeRange);
963 }
Richard Smith9647d3c2011-03-17 16:11:59 +0000964 TypeSourceInfo *DeducedType = 0;
965 if (!DeduceAutoType(AllocTypeInfo, ConstructorArgs.get()[0], DeducedType))
Richard Smith30482bc2011-02-20 03:19:35 +0000966 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
967 << AllocType
968 << ConstructorArgs.get()[0]->getType()
969 << TypeRange
970 << ConstructorArgs.get()[0]->getSourceRange());
Richard Smith9647d3c2011-03-17 16:11:59 +0000971 if (!DeducedType)
972 return ExprError();
Richard Smith30482bc2011-02-20 03:19:35 +0000973
Richard Smith9647d3c2011-03-17 16:11:59 +0000974 AllocTypeInfo = DeducedType;
975 AllocType = AllocTypeInfo->getType();
Richard Smith30482bc2011-02-20 03:19:35 +0000976 }
977
Douglas Gregorcda95f42010-05-16 16:01:03 +0000978 // Per C++0x [expr.new]p5, the type being constructed may be a
979 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +0000980 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +0000981 if (const ConstantArrayType *Array
982 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000983 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
984 Context.getSizeType(),
985 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +0000986 AllocType = Array->getElementType();
987 }
988 }
Sebastian Redlbd150f42008-11-21 19:14:01 +0000989
Douglas Gregor3999e152010-10-06 16:00:31 +0000990 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
991 return ExprError();
992
John McCall31168b02011-06-15 23:02:42 +0000993 // In ARC, infer 'retaining' for the allocated
994 if (getLangOptions().ObjCAutoRefCount &&
995 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
996 AllocType->isObjCLifetimeType()) {
997 AllocType = Context.getLifetimeQualifiedType(AllocType,
998 AllocType->getObjCARCImplicitLifetime());
999 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001000
John McCall31168b02011-06-15 23:02:42 +00001001 QualType ResultType = Context.getPointerType(AllocType);
1002
Sebastian Redlbd150f42008-11-21 19:14:01 +00001003 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
1004 // or enumeration type with a non-negative value."
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001005 if (ArraySize && !ArraySize->isTypeDependent()) {
John McCall9b80c212012-01-11 00:14:46 +00001006 // Eliminate placeholders.
1007 ExprResult ConvertedSize = CheckPlaceholderExpr(ArraySize);
1008 if (ConvertedSize.isInvalid())
1009 return ExprError();
1010 ArraySize = ConvertedSize.take();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001011
John McCall9b80c212012-01-11 00:14:46 +00001012 ConvertedSize = ConvertToIntegralOrEnumerationType(
Richard Smith0bf8a4922011-10-18 20:49:44 +00001013 StartLoc, ArraySize,
1014 PDiag(diag::err_array_size_not_integral),
1015 PDiag(diag::err_array_size_incomplete_type)
1016 << ArraySize->getSourceRange(),
1017 PDiag(diag::err_array_size_explicit_conversion),
1018 PDiag(diag::note_array_size_conversion),
1019 PDiag(diag::err_array_size_ambiguous_conversion),
1020 PDiag(diag::note_array_size_conversion),
1021 PDiag(getLangOptions().CPlusPlus0x ?
1022 diag::warn_cxx98_compat_array_size_conversion :
1023 diag::ext_array_size_conversion));
Douglas Gregor4799d032010-06-30 00:20:43 +00001024 if (ConvertedSize.isInvalid())
1025 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001026
John McCallb268a282010-08-23 23:25:46 +00001027 ArraySize = ConvertedSize.take();
John McCall9b80c212012-01-11 00:14:46 +00001028 QualType SizeType = ArraySize->getType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00001029 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +00001030 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001031
Sebastian Redl351bb782008-12-02 14:43:59 +00001032 // Let's see if this is a constant < 0. If so, we reject it out of hand.
1033 // We don't care about special rules, so we tell the machinery it's not
1034 // evaluated - it gives us a result in more cases.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001035 if (!ArraySize->isValueDependent()) {
1036 llvm::APSInt Value;
1037 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
1038 if (Value < llvm::APSInt(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001039 llvm::APInt::getNullValue(Value.getBitWidth()),
Anders Carlsson8ab20bb2009-09-23 00:37:25 +00001040 Value.isUnsigned()))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001041 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00001042 diag::err_typecheck_negative_array_size)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001043 << ArraySize->getSourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001044
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00001045 if (!AllocType->isDependentType()) {
1046 unsigned ActiveSizeBits
1047 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1048 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001049 Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00001050 diag::err_array_too_large)
1051 << Value.toString(10)
1052 << ArraySize->getSourceRange();
1053 return ExprError();
1054 }
1055 }
Douglas Gregorf2753b32010-07-13 15:54:32 +00001056 } else if (TypeIdParens.isValid()) {
1057 // Can't have dynamic array size when the type-id is in parentheses.
1058 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1059 << ArraySize->getSourceRange()
1060 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1061 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001062
Douglas Gregorf2753b32010-07-13 15:54:32 +00001063 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001064 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001065 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001066
John McCall31168b02011-06-15 23:02:42 +00001067 // ARC: warn about ABI issues.
1068 if (getLangOptions().ObjCAutoRefCount) {
1069 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1070 if (BaseAllocType.hasStrongOrWeakObjCLifetime())
1071 Diag(StartLoc, diag::warn_err_new_delete_object_array)
1072 << 0 << BaseAllocType;
1073 }
1074
John McCall036f2f62011-05-15 07:14:44 +00001075 // Note that we do *not* convert the argument in any way. It can
1076 // be signed, larger than size_t, whatever.
Sebastian Redl351bb782008-12-02 14:43:59 +00001077 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001078
Sebastian Redlbd150f42008-11-21 19:14:01 +00001079 FunctionDecl *OperatorNew = 0;
1080 FunctionDecl *OperatorDelete = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001081 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
1082 unsigned NumPlaceArgs = PlacementArgs.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001083
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001084 if (!AllocType->isDependentType() &&
1085 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
1086 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001087 SourceRange(PlacementLParen, PlacementRParen),
1088 UseGlobal, AllocType, ArraySize, PlaceArgs,
1089 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001090 return ExprError();
John McCall284c48f2011-01-27 09:37:56 +00001091
1092 // If this is an array allocation, compute whether the usual array
1093 // deallocation function for the type has a size_t parameter.
1094 bool UsualArrayDeleteWantsSize = false;
1095 if (ArraySize && !AllocType->isDependentType())
1096 UsualArrayDeleteWantsSize
1097 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1098
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001099 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001100 if (OperatorNew) {
1101 // Add default arguments, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001102 const FunctionProtoType *Proto =
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001103 OperatorNew->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001104 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00001105 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001106
Anders Carlssonc144bc22010-05-03 02:07:56 +00001107 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001108 Proto, 1, PlaceArgs, NumPlaceArgs,
Anders Carlssonc144bc22010-05-03 02:07:56 +00001109 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001110 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001111
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001112 NumPlaceArgs = AllPlaceArgs.size();
1113 if (NumPlaceArgs > 0)
1114 PlaceArgs = &AllPlaceArgs[0];
1115 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001116
Sebastian Redlbd150f42008-11-21 19:14:01 +00001117 bool Init = ConstructorLParen.isValid();
1118 // --- Choosing a constructor ---
Sebastian Redlbd150f42008-11-21 19:14:01 +00001119 CXXConstructorDecl *Constructor = 0;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00001120 bool HadMultipleCandidates = false;
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001121 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
1122 unsigned NumConsArgs = ConstructorArgs.size();
John McCall37ad5512010-08-23 06:44:23 +00001123 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmanfd8d4e12009-11-08 22:15:39 +00001124
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00001125 // Array 'new' can't have any initializers.
Anders Carlssone6ae81b2010-05-16 16:24:20 +00001126 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00001127 SourceRange InitRange(ConsArgs[0]->getLocStart(),
1128 ConsArgs[NumConsArgs - 1]->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001129
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00001130 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1131 return ExprError();
1132 }
1133
Douglas Gregor85dabae2009-12-16 01:38:02 +00001134 if (!AllocType->isDependentType() &&
1135 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
1136 // C++0x [expr.new]p15:
1137 // A new-expression that creates an object of type T initializes that
1138 // object as follows:
1139 InitializationKind Kind
1140 // - If the new-initializer is omitted, the object is default-
1141 // initialized (8.5); if no initialization is performed,
1142 // the object has indeterminate value
Douglas Gregor0744ef62010-09-07 21:49:58 +00001143 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001144 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor85dabae2009-12-16 01:38:02 +00001145 // initialization rules of 8.5 for direct-initialization.
Douglas Gregor0744ef62010-09-07 21:49:58 +00001146 : InitializationKind::CreateDirect(TypeRange.getBegin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001147 ConstructorLParen,
Douglas Gregor85dabae2009-12-16 01:38:02 +00001148 ConstructorRParen);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001149
Douglas Gregor85dabae2009-12-16 01:38:02 +00001150 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00001151 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00001152 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001153 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor85dabae2009-12-16 01:38:02 +00001154 move(ConstructorArgs));
1155 if (FullInit.isInvalid())
1156 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001157
1158 // FullInit is our initializer; walk through it to determine if it's a
Douglas Gregor85dabae2009-12-16 01:38:02 +00001159 // constructor call, which CXXNewExpr handles directly.
1160 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
1161 if (CXXBindTemporaryExpr *Binder
1162 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
1163 FullInitExpr = Binder->getSubExpr();
1164 if (CXXConstructExpr *Construct
1165 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
1166 Constructor = Construct->getConstructor();
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00001167 HadMultipleCandidates = Construct->hadMultipleCandidates();
Douglas Gregor85dabae2009-12-16 01:38:02 +00001168 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
1169 AEnd = Construct->arg_end();
1170 A != AEnd; ++A)
John McCallc3007a22010-10-26 07:05:15 +00001171 ConvertedConstructorArgs.push_back(*A);
Douglas Gregor85dabae2009-12-16 01:38:02 +00001172 } else {
1173 // Take the converted initializer.
1174 ConvertedConstructorArgs.push_back(FullInit.release());
1175 }
1176 } else {
1177 // No initialization required.
1178 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001179
Douglas Gregor85dabae2009-12-16 01:38:02 +00001180 // Take the converted arguments and use them for the new expression.
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001181 NumConsArgs = ConvertedConstructorArgs.size();
1182 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redlbd150f42008-11-21 19:14:01 +00001183 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001184
Douglas Gregor6642ca22010-02-26 05:06:18 +00001185 // Mark the new and delete operators as referenced.
1186 if (OperatorNew)
1187 MarkDeclarationReferenced(StartLoc, OperatorNew);
1188 if (OperatorDelete)
1189 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1190
John McCall928a2572011-07-13 20:12:57 +00001191 // C++0x [expr.new]p17:
1192 // If the new expression creates an array of objects of class type,
1193 // access and ambiguity control are done for the destructor.
1194 if (ArraySize && Constructor) {
1195 if (CXXDestructorDecl *dtor = LookupDestructor(Constructor->getParent())) {
1196 MarkDeclarationReferenced(StartLoc, dtor);
1197 CheckDestructorAccess(StartLoc, dtor,
1198 PDiag(diag::err_access_dtor)
1199 << Context.getBaseElementType(AllocType));
1200 }
1201 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001202
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001203 PlacementArgs.release();
1204 ConstructorArgs.release();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001205
Ted Kremenek9d6eb402010-02-11 22:51:03 +00001206 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001207 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenek9d6eb402010-02-11 22:51:03 +00001208 ArraySize, Constructor, Init,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00001209 ConsArgs, NumConsArgs,
1210 HadMultipleCandidates,
1211 OperatorDelete,
John McCall284c48f2011-01-27 09:37:56 +00001212 UsualArrayDeleteWantsSize,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001213 ResultType, AllocTypeInfo,
1214 StartLoc,
Ted Kremenek9d6eb402010-02-11 22:51:03 +00001215 Init ? ConstructorRParen :
Chandler Carruth01718152010-10-25 08:47:36 +00001216 TypeRange.getEnd(),
1217 ConstructorLParen, ConstructorRParen));
Sebastian Redlbd150f42008-11-21 19:14:01 +00001218}
1219
1220/// CheckAllocatedType - Checks that a type is suitable as the allocated type
1221/// in a new-expression.
1222/// dimension off and stores the size expression in ArraySize.
Douglas Gregord0fefba2009-05-21 00:00:09 +00001223bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00001224 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00001225 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1226 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +00001227 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00001228 return Diag(Loc, diag::err_bad_new_type)
1229 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00001230 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00001231 return Diag(Loc, diag::err_bad_new_type)
1232 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00001233 else if (!AllocType->isDependentType() &&
Douglas Gregord0fefba2009-05-21 00:00:09 +00001234 RequireCompleteType(Loc, AllocType,
Anders Carlssond624e162009-08-26 23:45:07 +00001235 PDiag(diag::err_new_incomplete_type)
1236 << R))
Sebastian Redlbd150f42008-11-21 19:14:01 +00001237 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +00001238 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +00001239 diag::err_allocation_of_abstract_type))
1240 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +00001241 else if (AllocType->isVariablyModifiedType())
1242 return Diag(Loc, diag::err_variably_modified_new_type)
1243 << AllocType;
Douglas Gregor39d1a092011-04-15 19:46:20 +00001244 else if (unsigned AddressSpace = AllocType.getAddressSpace())
1245 return Diag(Loc, diag::err_address_space_qualified_new)
1246 << AllocType.getUnqualifiedType() << AddressSpace;
John McCall31168b02011-06-15 23:02:42 +00001247 else if (getLangOptions().ObjCAutoRefCount) {
1248 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
1249 QualType BaseAllocType = Context.getBaseElementType(AT);
1250 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1251 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001252 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCall31168b02011-06-15 23:02:42 +00001253 << BaseAllocType;
1254 }
1255 }
Douglas Gregor39d1a092011-04-15 19:46:20 +00001256
Sebastian Redlbd150f42008-11-21 19:14:01 +00001257 return false;
1258}
1259
Douglas Gregor6642ca22010-02-26 05:06:18 +00001260/// \brief Determine whether the given function is a non-placement
1261/// deallocation function.
1262static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1263 if (FD->isInvalidDecl())
1264 return false;
1265
1266 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1267 return Method->isUsualDeallocationFunction();
1268
1269 return ((FD->getOverloadedOperator() == OO_Delete ||
1270 FD->getOverloadedOperator() == OO_Array_Delete) &&
1271 FD->getNumParams() == 1);
1272}
1273
Sebastian Redlfaf68082008-12-03 20:26:15 +00001274/// FindAllocationFunctions - Finds the overloads of operator new and delete
1275/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001276bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1277 bool UseGlobal, QualType AllocType,
1278 bool IsArray, Expr **PlaceArgs,
1279 unsigned NumPlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +00001280 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +00001281 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001282 // --- Choosing an allocation function ---
1283 // C++ 5.3.4p8 - 14 & 18
1284 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1285 // in the scope of the allocated class.
1286 // 2) If an array size is given, look for operator new[], else look for
1287 // operator new.
1288 // 3) The first argument is always size_t. Append the arguments from the
1289 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +00001290
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001291 SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001292 // We don't care about the actual value of this argument.
1293 // FIXME: Should the Sema create the expression and embed it in the syntax
1294 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001295 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregore8bbc122011-09-02 00:18:52 +00001296 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssona471db02009-08-16 20:29:29 +00001297 Context.getSizeType(),
1298 SourceLocation());
1299 AllocArgs[0] = &Size;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001300 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1301
Douglas Gregor6642ca22010-02-26 05:06:18 +00001302 // C++ [expr.new]p8:
1303 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001304 // function's name is operator new and the deallocation function's
Douglas Gregor6642ca22010-02-26 05:06:18 +00001305 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001306 // type, the allocation function's name is operator new[] and the
1307 // deallocation function's name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +00001308 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1309 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001310 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1311 IsArray ? OO_Array_Delete : OO_Delete);
1312
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001313 QualType AllocElemType = Context.getBaseElementType(AllocType);
1314
1315 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump11289f42009-09-09 15:08:12 +00001316 CXXRecordDecl *Record
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001317 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001318 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +00001319 AllocArgs.size(), Record, /*AllowMissing=*/true,
1320 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +00001321 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001322 }
1323 if (!OperatorNew) {
1324 // Didn't find a member overload. Look for a global one.
1325 DeclareGlobalNewDelete();
Sebastian Redl33a31012008-12-04 22:20:51 +00001326 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001327 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +00001328 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1329 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +00001330 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001331 }
1332
John McCall0f55a032010-04-20 02:18:25 +00001333 // We don't need an operator delete if we're running under
1334 // -fno-exceptions.
1335 if (!getLangOptions().Exceptions) {
1336 OperatorDelete = 0;
1337 return false;
1338 }
1339
Anders Carlsson6f9dabf2009-05-31 20:26:12 +00001340 // FindAllocationOverload can change the passed in arguments, so we need to
1341 // copy them back.
1342 if (NumPlaceArgs > 0)
1343 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001344
Douglas Gregor6642ca22010-02-26 05:06:18 +00001345 // C++ [expr.new]p19:
1346 //
1347 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001348 // deallocation function's name is looked up in the global
Douglas Gregor6642ca22010-02-26 05:06:18 +00001349 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001350 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6642ca22010-02-26 05:06:18 +00001351 // the scope of T. If this lookup fails to find the name, or if
1352 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001353 // deallocation function's name is looked up in the global scope.
Douglas Gregor6642ca22010-02-26 05:06:18 +00001354 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001355 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00001356 CXXRecordDecl *RD
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001357 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00001358 LookupQualifiedName(FoundDelete, RD);
1359 }
John McCallfb6f5262010-03-18 08:19:33 +00001360 if (FoundDelete.isAmbiguous())
1361 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00001362
1363 if (FoundDelete.empty()) {
1364 DeclareGlobalNewDelete();
1365 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1366 }
1367
1368 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00001369
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001370 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCalla0296f72010-03-19 07:35:19 +00001371
John McCalld3be2c82010-09-14 21:34:24 +00001372 // Whether we're looking for a placement operator delete is dictated
1373 // by whether we selected a placement operator new, not by whether
1374 // we had explicit placement arguments. This matters for things like
1375 // struct A { void *operator new(size_t, int = 0); ... };
1376 // A *a = new A()
1377 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1378
1379 if (isPlacementNew) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00001380 // C++ [expr.new]p20:
1381 // A declaration of a placement deallocation function matches the
1382 // declaration of a placement allocation function if it has the
1383 // same number of parameters and, after parameter transformations
1384 // (8.3.5), all parameter types except the first are
1385 // identical. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001386 //
Douglas Gregor6642ca22010-02-26 05:06:18 +00001387 // To perform this comparison, we compute the function type that
1388 // the deallocation function should have, and use that type both
1389 // for template argument deduction and for comparison purposes.
John McCalldb40c7f2010-12-14 08:05:40 +00001390 //
1391 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6642ca22010-02-26 05:06:18 +00001392 QualType ExpectedFunctionType;
1393 {
1394 const FunctionProtoType *Proto
1395 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00001396
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001397 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001398 ArgTypes.push_back(Context.VoidPtrTy);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001399 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1400 ArgTypes.push_back(Proto->getArgType(I));
1401
John McCalldb40c7f2010-12-14 08:05:40 +00001402 FunctionProtoType::ExtProtoInfo EPI;
1403 EPI.Variadic = Proto->isVariadic();
1404
Douglas Gregor6642ca22010-02-26 05:06:18 +00001405 ExpectedFunctionType
1406 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
John McCalldb40c7f2010-12-14 08:05:40 +00001407 ArgTypes.size(), EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001408 }
1409
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001410 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00001411 DEnd = FoundDelete.end();
1412 D != DEnd; ++D) {
1413 FunctionDecl *Fn = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001414 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6642ca22010-02-26 05:06:18 +00001415 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1416 // Perform template argument deduction to try to match the
1417 // expected function type.
1418 TemplateDeductionInfo Info(Context, StartLoc);
1419 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1420 continue;
1421 } else
1422 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1423
1424 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
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 } else {
1428 // C++ [expr.new]p20:
1429 // [...] Any non-placement deallocation function matches a
1430 // non-placement allocation function. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001431 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00001432 DEnd = FoundDelete.end();
1433 D != DEnd; ++D) {
1434 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1435 if (isNonPlacementDeallocationFunction(Fn))
John McCalla0296f72010-03-19 07:35:19 +00001436 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001437 }
1438 }
1439
1440 // C++ [expr.new]p20:
1441 // [...] If the lookup finds a single matching deallocation
1442 // function, that function will be called; otherwise, no
1443 // deallocation function will be called.
1444 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00001445 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00001446
1447 // C++0x [expr.new]p20:
1448 // If the lookup finds the two-parameter form of a usual
1449 // deallocation function (3.7.4.2) and that function, considered
1450 // as a placement deallocation function, would have been
1451 // selected as a match for the allocation function, the program
1452 // is ill-formed.
1453 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1454 isNonPlacementDeallocationFunction(OperatorDelete)) {
1455 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001456 << SourceRange(PlaceArgs[0]->getLocStart(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00001457 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1458 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1459 << DeleteName;
John McCallfb6f5262010-03-18 08:19:33 +00001460 } else {
1461 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCalla0296f72010-03-19 07:35:19 +00001462 Matches[0].first);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001463 }
1464 }
1465
Sebastian Redlfaf68082008-12-03 20:26:15 +00001466 return false;
1467}
1468
Sebastian Redl33a31012008-12-04 22:20:51 +00001469/// FindAllocationOverload - Find an fitting overload for the allocation
1470/// function in the specified scope.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001471bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1472 DeclarationName Name, Expr** Args,
1473 unsigned NumArgs, DeclContext *Ctx,
Alexis Hunt1f69a022011-05-12 22:46:29 +00001474 bool AllowMissing, FunctionDecl *&Operator,
1475 bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00001476 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1477 LookupQualifiedName(R, Ctx);
John McCall9f3059a2009-10-09 21:13:30 +00001478 if (R.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001479 if (AllowMissing || !Diagnose)
Sebastian Redl33a31012008-12-04 22:20:51 +00001480 return false;
Sebastian Redl33a31012008-12-04 22:20:51 +00001481 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00001482 << Name << Range;
Sebastian Redl33a31012008-12-04 22:20:51 +00001483 }
1484
John McCallfb6f5262010-03-18 08:19:33 +00001485 if (R.isAmbiguous())
1486 return true;
1487
1488 R.suppressDiagnostics();
John McCall9f3059a2009-10-09 21:13:30 +00001489
John McCallbc077cf2010-02-08 23:07:23 +00001490 OverloadCandidateSet Candidates(StartLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001491 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor80a6cc52009-09-30 00:03:47 +00001492 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor55297ac2008-12-23 00:26:44 +00001493 // Even member operator new/delete are implicitly treated as
1494 // static, so don't use AddMemberCandidate.
John McCalla0296f72010-03-19 07:35:19 +00001495 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth93538422010-02-03 11:02:14 +00001496
John McCalla0296f72010-03-19 07:35:19 +00001497 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1498 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth93538422010-02-03 11:02:14 +00001499 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1500 Candidates,
1501 /*SuppressUserConversions=*/false);
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001502 continue;
Chandler Carruth93538422010-02-03 11:02:14 +00001503 }
1504
John McCalla0296f72010-03-19 07:35:19 +00001505 FunctionDecl *Fn = cast<FunctionDecl>(D);
1506 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth93538422010-02-03 11:02:14 +00001507 /*SuppressUserConversions=*/false);
Sebastian Redl33a31012008-12-04 22:20:51 +00001508 }
1509
1510 // Do the resolution.
1511 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00001512 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl33a31012008-12-04 22:20:51 +00001513 case OR_Success: {
1514 // Got one!
1515 FunctionDecl *FnDecl = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00001516 MarkDeclarationReferenced(StartLoc, FnDecl);
Sebastian Redl33a31012008-12-04 22:20:51 +00001517 // The first argument is size_t, and the first parameter must be size_t,
1518 // too. This is checked on declaration and can be assumed. (It can't be
1519 // asserted on, though, since invalid decls are left in there.)
John McCallfb6f5262010-03-18 08:19:33 +00001520 // Watch out for variadic allocator function.
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001521 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1522 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001523 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1524 FnDecl->getParamDecl(i));
1525
1526 if (!Diagnose && !CanPerformCopyInitialization(Entity, Owned(Args[i])))
1527 return true;
1528
John McCalldadc5752010-08-24 06:29:42 +00001529 ExprResult Result
Alexis Hunt1f69a022011-05-12 22:46:29 +00001530 = PerformCopyInitialization(Entity, SourceLocation(), Owned(Args[i]));
Douglas Gregor34147272010-03-26 20:35:59 +00001531 if (Result.isInvalid())
Sebastian Redl33a31012008-12-04 22:20:51 +00001532 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001533
Douglas Gregor34147272010-03-26 20:35:59 +00001534 Args[i] = Result.takeAs<Expr>();
Sebastian Redl33a31012008-12-04 22:20:51 +00001535 }
1536 Operator = FnDecl;
Alexis Hunt1f69a022011-05-12 22:46:29 +00001537 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl,
1538 Diagnose);
Sebastian Redl33a31012008-12-04 22:20:51 +00001539 return false;
1540 }
1541
1542 case OR_No_Viable_Function:
Chandler Carruthe6c88182011-06-08 10:26:03 +00001543 if (Diagnose) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001544 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1545 << Name << Range;
Chandler Carruthe6c88182011-06-08 10:26:03 +00001546 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1547 }
Sebastian Redl33a31012008-12-04 22:20:51 +00001548 return true;
1549
1550 case OR_Ambiguous:
Chandler Carruthe6c88182011-06-08 10:26:03 +00001551 if (Diagnose) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001552 Diag(StartLoc, diag::err_ovl_ambiguous_call)
1553 << Name << Range;
Chandler Carruthe6c88182011-06-08 10:26:03 +00001554 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
1555 }
Sebastian Redl33a31012008-12-04 22:20:51 +00001556 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001557
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001558 case OR_Deleted: {
Chandler Carruthe6c88182011-06-08 10:26:03 +00001559 if (Diagnose) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001560 Diag(StartLoc, diag::err_ovl_deleted_call)
1561 << Best->Function->isDeleted()
1562 << Name
1563 << getDeletedOrUnavailableSuffix(Best->Function)
1564 << Range;
Chandler Carruthe6c88182011-06-08 10:26:03 +00001565 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1566 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00001567 return true;
Sebastian Redl33a31012008-12-04 22:20:51 +00001568 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001569 }
David Blaikie83d382b2011-09-23 05:06:16 +00001570 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Sebastian Redl33a31012008-12-04 22:20:51 +00001571}
1572
1573
Sebastian Redlfaf68082008-12-03 20:26:15 +00001574/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1575/// delete. These are:
1576/// @code
Sebastian Redl37588092011-03-14 18:08:30 +00001577/// // C++03:
Sebastian Redlfaf68082008-12-03 20:26:15 +00001578/// void* operator new(std::size_t) throw(std::bad_alloc);
1579/// void* operator new[](std::size_t) throw(std::bad_alloc);
1580/// void operator delete(void *) throw();
1581/// void operator delete[](void *) throw();
Sebastian Redl37588092011-03-14 18:08:30 +00001582/// // C++0x:
1583/// void* operator new(std::size_t);
1584/// void* operator new[](std::size_t);
1585/// void operator delete(void *);
1586/// void operator delete[](void *);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001587/// @endcode
Sebastian Redl37588092011-03-14 18:08:30 +00001588/// C++0x operator delete is implicitly noexcept.
Sebastian Redlfaf68082008-12-03 20:26:15 +00001589/// Note that the placement and nothrow forms of new are *not* implicitly
1590/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00001591void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001592 if (GlobalNewDeleteDeclared)
1593 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001594
Douglas Gregor87f54062009-09-15 22:30:29 +00001595 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001596 // [...] The following allocation and deallocation functions (18.4) are
1597 // implicitly declared in global scope in each translation unit of a
Douglas Gregor87f54062009-09-15 22:30:29 +00001598 // program
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001599 //
Sebastian Redl37588092011-03-14 18:08:30 +00001600 // C++03:
Douglas Gregor87f54062009-09-15 22:30:29 +00001601 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001602 // void* operator new[](std::size_t) throw(std::bad_alloc);
1603 // void operator delete(void*) throw();
Douglas Gregor87f54062009-09-15 22:30:29 +00001604 // void operator delete[](void*) throw();
Sebastian Redl37588092011-03-14 18:08:30 +00001605 // C++0x:
1606 // void* operator new(std::size_t);
1607 // void* operator new[](std::size_t);
1608 // void operator delete(void*);
1609 // void operator delete[](void*);
Douglas Gregor87f54062009-09-15 22:30:29 +00001610 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001611 // These implicit declarations introduce only the function names operator
Douglas Gregor87f54062009-09-15 22:30:29 +00001612 // new, operator new[], operator delete, operator delete[].
1613 //
1614 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1615 // "std" or "bad_alloc" as necessary to form the exception specification.
1616 // However, we do not make these implicit declarations visible to name
1617 // lookup.
Sebastian Redl37588092011-03-14 18:08:30 +00001618 // Note that the C++0x versions of operator delete are deallocation functions,
1619 // and thus are implicitly noexcept.
1620 if (!StdBadAlloc && !getLangOptions().CPlusPlus0x) {
Douglas Gregor87f54062009-09-15 22:30:29 +00001621 // The "std::bad_alloc" class has not yet been declared, so build it
1622 // implicitly.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001623 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1624 getOrCreateStdNamespace(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001625 SourceLocation(), SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001626 &PP.getIdentifierTable().get("bad_alloc"),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001627 0);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00001628 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00001629 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001630
Sebastian Redlfaf68082008-12-03 20:26:15 +00001631 GlobalNewDeleteDeclared = true;
1632
1633 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1634 QualType SizeT = Context.getSizeType();
Nuno Lopes13c88c72009-12-16 16:59:22 +00001635 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001636
Sebastian Redlfaf68082008-12-03 20:26:15 +00001637 DeclareGlobalAllocationFunction(
1638 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001639 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001640 DeclareGlobalAllocationFunction(
1641 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001642 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001643 DeclareGlobalAllocationFunction(
1644 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1645 Context.VoidTy, VoidPtr);
1646 DeclareGlobalAllocationFunction(
1647 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1648 Context.VoidTy, VoidPtr);
1649}
1650
1651/// DeclareGlobalAllocationFunction - Declares a single implicit global
1652/// allocation function if it doesn't already exist.
1653void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopes13c88c72009-12-16 16:59:22 +00001654 QualType Return, QualType Argument,
1655 bool AddMallocAttr) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001656 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1657
1658 // Check if this function is already declared.
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001659 {
Douglas Gregor17eb26b2008-12-23 22:05:29 +00001660 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001661 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001662 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth93538422010-02-03 11:02:14 +00001663 // Only look at non-template functions, as it is the predefined,
1664 // non-templated allocation function we are trying to declare here.
1665 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1666 QualType InitialParamType =
Douglas Gregor684d7bd2009-12-22 23:42:49 +00001667 Context.getCanonicalType(
Chandler Carruth93538422010-02-03 11:02:14 +00001668 Func->getParamDecl(0)->getType().getUnqualifiedType());
1669 // FIXME: Do we need to check for default arguments here?
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00001670 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1671 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001672 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth93538422010-02-03 11:02:14 +00001673 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00001674 }
Chandler Carruth93538422010-02-03 11:02:14 +00001675 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00001676 }
1677 }
1678
Douglas Gregor87f54062009-09-15 22:30:29 +00001679 QualType BadAllocType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001680 bool HasBadAllocExceptionSpec
Douglas Gregor87f54062009-09-15 22:30:29 +00001681 = (Name.getCXXOverloadedOperator() == OO_New ||
1682 Name.getCXXOverloadedOperator() == OO_Array_New);
Sebastian Redl37588092011-03-14 18:08:30 +00001683 if (HasBadAllocExceptionSpec && !getLangOptions().CPlusPlus0x) {
Douglas Gregor87f54062009-09-15 22:30:29 +00001684 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00001685 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor87f54062009-09-15 22:30:29 +00001686 }
John McCalldb40c7f2010-12-14 08:05:40 +00001687
1688 FunctionProtoType::ExtProtoInfo EPI;
John McCalldb40c7f2010-12-14 08:05:40 +00001689 if (HasBadAllocExceptionSpec) {
Sebastian Redl37588092011-03-14 18:08:30 +00001690 if (!getLangOptions().CPlusPlus0x) {
1691 EPI.ExceptionSpecType = EST_Dynamic;
1692 EPI.NumExceptions = 1;
1693 EPI.Exceptions = &BadAllocType;
1694 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001695 } else {
Sebastian Redl37588092011-03-14 18:08:30 +00001696 EPI.ExceptionSpecType = getLangOptions().CPlusPlus0x ?
1697 EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00001698 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001699
John McCalldb40c7f2010-12-14 08:05:40 +00001700 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001701 FunctionDecl *Alloc =
Abramo Bagnaradff19302011-03-08 08:55:46 +00001702 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
1703 SourceLocation(), Name,
John McCall8e7d6562010-08-26 03:08:43 +00001704 FnType, /*TInfo=*/0, SC_None,
1705 SC_None, false, true);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001706 Alloc->setImplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001707
Nuno Lopes13c88c72009-12-16 16:59:22 +00001708 if (AddMallocAttr)
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001709 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001710
Sebastian Redlfaf68082008-12-03 20:26:15 +00001711 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001712 SourceLocation(), 0,
1713 Argument, /*TInfo=*/0,
1714 SC_None, SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00001715 Alloc->setParams(Param);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001716
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001717 // FIXME: Also add this declaration to the IdentifierResolver, but
1718 // make sure it is at the end of the chain to coincide with the
1719 // global scope.
John McCallcc14d1f2010-08-24 08:50:51 +00001720 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001721}
1722
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001723bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1724 DeclarationName Name,
Alexis Hunt1f69a022011-05-12 22:46:29 +00001725 FunctionDecl* &Operator, bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00001726 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001727 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00001728 LookupQualifiedName(Found, RD);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001729
John McCall27b18f82009-11-17 02:14:36 +00001730 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001731 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001732
Chandler Carruthb6f99172010-06-28 00:30:51 +00001733 Found.suppressDiagnostics();
1734
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001735 SmallVector<DeclAccessPair,4> Matches;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001736 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1737 F != FEnd; ++F) {
Chandler Carruth9b418232010-08-08 07:04:00 +00001738 NamedDecl *ND = (*F)->getUnderlyingDecl();
1739
1740 // Ignore template operator delete members from the check for a usual
1741 // deallocation function.
1742 if (isa<FunctionTemplateDecl>(ND))
1743 continue;
1744
1745 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall66a87592010-08-04 00:31:26 +00001746 Matches.push_back(F.getPair());
1747 }
1748
1749 // There's exactly one suitable operator; pick it.
1750 if (Matches.size() == 1) {
1751 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
Alexis Hunt1f69a022011-05-12 22:46:29 +00001752
1753 if (Operator->isDeleted()) {
1754 if (Diagnose) {
1755 Diag(StartLoc, diag::err_deleted_function_use);
1756 Diag(Operator->getLocation(), diag::note_unavailable_here) << true;
1757 }
1758 return true;
1759 }
1760
John McCall66a87592010-08-04 00:31:26 +00001761 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Alexis Hunt1f69a022011-05-12 22:46:29 +00001762 Matches[0], Diagnose);
John McCall66a87592010-08-04 00:31:26 +00001763 return false;
1764
1765 // We found multiple suitable operators; complain about the ambiguity.
1766 } else if (!Matches.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001767 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00001768 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1769 << Name << RD;
John McCall66a87592010-08-04 00:31:26 +00001770
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001771 for (SmallVectorImpl<DeclAccessPair>::iterator
Alexis Huntf91729462011-05-12 22:46:25 +00001772 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1773 Diag((*F)->getUnderlyingDecl()->getLocation(),
1774 diag::note_member_declared_here) << Name;
1775 }
John McCall66a87592010-08-04 00:31:26 +00001776 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001777 }
1778
1779 // We did find operator delete/operator delete[] declarations, but
1780 // none of them were suitable.
1781 if (!Found.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001782 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00001783 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1784 << Name << RD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001785
Alexis Huntf91729462011-05-12 22:46:25 +00001786 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1787 F != FEnd; ++F)
1788 Diag((*F)->getUnderlyingDecl()->getLocation(),
1789 diag::note_member_declared_here) << Name;
1790 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001791 return true;
1792 }
1793
1794 // Look for a global declaration.
1795 DeclareGlobalNewDelete();
1796 DeclContext *TUDecl = Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001797
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001798 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1799 Expr* DeallocArgs[1];
1800 DeallocArgs[0] = &Null;
1801 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
Alexis Hunt1f69a022011-05-12 22:46:29 +00001802 DeallocArgs, 1, TUDecl, !Diagnose,
1803 Operator, Diagnose))
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001804 return true;
1805
1806 assert(Operator && "Did not find a deallocation function!");
1807 return false;
1808}
1809
Sebastian Redlbd150f42008-11-21 19:14:01 +00001810/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1811/// @code ::delete ptr; @endcode
1812/// or
1813/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00001814ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001815Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley01296292011-04-08 18:41:53 +00001816 bool ArrayForm, Expr *ExE) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001817 // C++ [expr.delete]p1:
1818 // The operand shall have a pointer type, or a class type having a single
1819 // conversion function to a pointer type. The result has type void.
1820 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00001821 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1822
John Wiegley01296292011-04-08 18:41:53 +00001823 ExprResult Ex = Owned(ExE);
Anders Carlssona471db02009-08-16 20:29:29 +00001824 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00001825 bool ArrayFormAsWritten = ArrayForm;
John McCall284c48f2011-01-27 09:37:56 +00001826 bool UsualArrayDeleteWantsSize = false;
Mike Stump11289f42009-09-09 15:08:12 +00001827
John Wiegley01296292011-04-08 18:41:53 +00001828 if (!Ex.get()->isTypeDependent()) {
1829 QualType Type = Ex.get()->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00001830
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001831 if (const RecordType *Record = Type->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001832 if (RequireCompleteType(StartLoc, Type,
Douglas Gregorf65f4902010-07-29 14:44:35 +00001833 PDiag(diag::err_delete_incomplete_class_type)))
1834 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001835
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001836 SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
John McCallda4458e2010-03-31 01:36:47 +00001837
Fariborz Jahanianb54ccb22009-09-11 21:44:33 +00001838 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001839 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001840 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001841 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00001842 NamedDecl *D = I.getDecl();
1843 if (isa<UsingShadowDecl>(D))
1844 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1845
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001846 // Skip over templated conversion functions; they aren't considered.
John McCallda4458e2010-03-31 01:36:47 +00001847 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001848 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001849
John McCallda4458e2010-03-31 01:36:47 +00001850 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001851
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001852 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1853 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00001854 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001855 ObjectPtrConversions.push_back(Conv);
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001856 }
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001857 if (ObjectPtrConversions.size() == 1) {
1858 // We have a single conversion to a pointer-to-object type. Perform
1859 // that conversion.
John McCallda4458e2010-03-31 01:36:47 +00001860 // TODO: don't redo the conversion calculation.
John Wiegley01296292011-04-08 18:41:53 +00001861 ExprResult Res =
1862 PerformImplicitConversion(Ex.get(),
John McCallda4458e2010-03-31 01:36:47 +00001863 ObjectPtrConversions.front()->getConversionType(),
John Wiegley01296292011-04-08 18:41:53 +00001864 AA_Converting);
1865 if (Res.isUsable()) {
1866 Ex = move(Res);
1867 Type = Ex.get()->getType();
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001868 }
1869 }
1870 else if (ObjectPtrConversions.size() > 1) {
1871 Diag(StartLoc, diag::err_ambiguous_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00001872 << Type << Ex.get()->getSourceRange();
John McCallda4458e2010-03-31 01:36:47 +00001873 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1874 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001875 return ExprError();
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001876 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001877 }
1878
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001879 if (!Type->isPointerType())
1880 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00001881 << Type << Ex.get()->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001882
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001883 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmanae4280f2011-07-26 22:25:31 +00001884 QualType PointeeElem = Context.getBaseElementType(Pointee);
1885
1886 if (unsigned AddressSpace = Pointee.getAddressSpace())
1887 return Diag(Ex.get()->getLocStart(),
1888 diag::err_address_space_qualified_delete)
1889 << Pointee.getUnqualifiedType() << AddressSpace;
1890
1891 CXXRecordDecl *PointeeRD = 0;
Douglas Gregorbb3348e2010-05-24 17:01:56 +00001892 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001893 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregorbb3348e2010-05-24 17:01:56 +00001894 // effectively bans deletion of "void*". However, most compilers support
1895 // this, so we treat it as a warning unless we're in a SFINAE context.
1896 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley01296292011-04-08 18:41:53 +00001897 << Type << Ex.get()->getSourceRange();
Eli Friedmanae4280f2011-07-26 22:25:31 +00001898 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001899 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00001900 << Type << Ex.get()->getSourceRange());
Eli Friedmanae4280f2011-07-26 22:25:31 +00001901 } else if (!Pointee->isDependentType()) {
1902 if (!RequireCompleteType(StartLoc, Pointee,
1903 PDiag(diag::warn_delete_incomplete)
1904 << Ex.get()->getSourceRange())) {
1905 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
1906 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
1907 }
1908 }
1909
Abramo Bagnarad4756b92011-11-16 15:42:13 +00001910 // Perform lvalue-to-rvalue cast, if needed.
1911 Ex = DefaultLvalueConversion(Ex.take());
1912
Douglas Gregor98496dc2009-09-29 21:38:53 +00001913 // C++ [expr.delete]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001914 // [Note: a pointer to a const type can be the operand of a
1915 // delete-expression; it is not necessary to cast away the constness
1916 // (5.2.11) of the pointer expression before it is used as the operand
Douglas Gregor98496dc2009-09-29 21:38:53 +00001917 // of the delete-expression. ]
John McCall31168b02011-06-15 23:02:42 +00001918 if (!Context.hasSameType(Ex.get()->getType(), Context.VoidPtrTy))
Abramo Bagnarad4756b92011-11-16 15:42:13 +00001919 Ex = Owned(ImplicitCastExpr::Create(Context, Context.VoidPtrTy,
1920 CK_BitCast, Ex.take(), 0, VK_RValue));
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00001921
1922 if (Pointee->isArrayType() && !ArrayForm) {
1923 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley01296292011-04-08 18:41:53 +00001924 << Type << Ex.get()->getSourceRange()
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00001925 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1926 ArrayForm = true;
1927 }
1928
Anders Carlssona471db02009-08-16 20:29:29 +00001929 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1930 ArrayForm ? OO_Array_Delete : OO_Delete);
1931
Eli Friedmanae4280f2011-07-26 22:25:31 +00001932 if (PointeeRD) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001933 if (!UseGlobal &&
Eli Friedmanae4280f2011-07-26 22:25:31 +00001934 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
1935 OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00001936 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001937
John McCall284c48f2011-01-27 09:37:56 +00001938 // If we're allocating an array of records, check whether the
1939 // usual operator delete[] has a size_t parameter.
1940 if (ArrayForm) {
1941 // If the user specifically asked to use the global allocator,
1942 // we'll need to do the lookup into the class.
1943 if (UseGlobal)
1944 UsualArrayDeleteWantsSize =
1945 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
1946
1947 // Otherwise, the usual operator delete[] should be the
1948 // function we just found.
1949 else if (isa<CXXMethodDecl>(OperatorDelete))
1950 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
1951 }
1952
Eli Friedmanae4280f2011-07-26 22:25:31 +00001953 if (!PointeeRD->hasTrivialDestructor())
1954 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Mike Stump11289f42009-09-09 15:08:12 +00001955 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001956 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001957 DiagnoseUseOfDecl(Dtor, StartLoc);
1958 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00001959
1960 // C++ [expr.delete]p3:
1961 // In the first alternative (delete object), if the static type of the
1962 // object to be deleted is different from its dynamic type, the static
1963 // type shall be a base class of the dynamic type of the object to be
1964 // deleted and the static type shall have a virtual destructor or the
1965 // behavior is undefined.
1966 //
1967 // Note: a final class cannot be derived from, no issue there
Eli Friedman1b71a222011-07-26 23:27:24 +00001968 if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) {
Eli Friedmanae4280f2011-07-26 22:25:31 +00001969 CXXDestructorDecl *dtor = PointeeRD->getDestructor();
Eli Friedman1b71a222011-07-26 23:27:24 +00001970 if (dtor && !dtor->isVirtual()) {
1971 if (PointeeRD->isAbstract()) {
1972 // If the class is abstract, we warn by default, because we're
1973 // sure the code has undefined behavior.
1974 Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor)
1975 << PointeeElem;
1976 } else if (!ArrayForm) {
1977 // Otherwise, if this is not an array delete, it's a bit suspect,
1978 // but not necessarily wrong.
1979 Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
1980 }
1981 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00001982 }
John McCall31168b02011-06-15 23:02:42 +00001983
1984 } else if (getLangOptions().ObjCAutoRefCount &&
1985 PointeeElem->isObjCLifetimeType() &&
1986 (PointeeElem.getObjCLifetime() == Qualifiers::OCL_Strong ||
1987 PointeeElem.getObjCLifetime() == Qualifiers::OCL_Weak) &&
1988 ArrayForm) {
1989 Diag(StartLoc, diag::warn_err_new_delete_object_array)
1990 << 1 << PointeeElem;
Anders Carlssona471db02009-08-16 20:29:29 +00001991 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001992
Anders Carlssona471db02009-08-16 20:29:29 +00001993 if (!OperatorDelete) {
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001994 // Look for a global declaration.
Anders Carlssona471db02009-08-16 20:29:29 +00001995 DeclareGlobalNewDelete();
1996 DeclContext *TUDecl = Context.getTranslationUnitDecl();
John Wiegley01296292011-04-08 18:41:53 +00001997 Expr *Arg = Ex.get();
Mike Stump11289f42009-09-09 15:08:12 +00001998 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
John Wiegley01296292011-04-08 18:41:53 +00001999 &Arg, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssona471db02009-08-16 20:29:29 +00002000 OperatorDelete))
2001 return ExprError();
2002 }
Mike Stump11289f42009-09-09 15:08:12 +00002003
John McCall0f55a032010-04-20 02:18:25 +00002004 MarkDeclarationReferenced(StartLoc, OperatorDelete);
John McCall284c48f2011-01-27 09:37:56 +00002005
Douglas Gregorfa778132011-02-01 15:50:11 +00002006 // Check access and ambiguity of operator delete and destructor.
Eli Friedmanae4280f2011-07-26 22:25:31 +00002007 if (PointeeRD) {
2008 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
John Wiegley01296292011-04-08 18:41:53 +00002009 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregorfa778132011-02-01 15:50:11 +00002010 PDiag(diag::err_access_dtor) << PointeeElem);
2011 }
2012 }
2013
Sebastian Redlbd150f42008-11-21 19:14:01 +00002014 }
2015
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002016 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
John McCall284c48f2011-01-27 09:37:56 +00002017 ArrayFormAsWritten,
2018 UsualArrayDeleteWantsSize,
John Wiegley01296292011-04-08 18:41:53 +00002019 OperatorDelete, Ex.take(), StartLoc));
Sebastian Redlbd150f42008-11-21 19:14:01 +00002020}
2021
Douglas Gregor633caca2009-11-23 23:44:04 +00002022/// \brief Check the use of the given variable as a C++ condition in an if,
2023/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00002024ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00002025 SourceLocation StmtLoc,
2026 bool ConvertToBoolean) {
Douglas Gregor633caca2009-11-23 23:44:04 +00002027 QualType T = ConditionVar->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002028
Douglas Gregor633caca2009-11-23 23:44:04 +00002029 // C++ [stmt.select]p2:
2030 // The declarator shall not specify a function or an array.
2031 if (T->isFunctionType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002032 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00002033 diag::err_invalid_use_of_function_type)
2034 << ConditionVar->getSourceRange());
2035 else if (T->isArrayType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002036 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00002037 diag::err_invalid_use_of_array_type)
2038 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00002039
John Wiegley01296292011-04-08 18:41:53 +00002040 ExprResult Condition =
2041 Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
Douglas Gregorea972d32011-02-28 21:54:11 +00002042 ConditionVar,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002043 ConditionVar->getLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00002044 ConditionVar->getType().getNonReferenceType(),
John Wiegley01296292011-04-08 18:41:53 +00002045 VK_LValue));
Eli Friedman2dfa7932012-01-16 21:00:51 +00002046
2047 MarkDeclarationReferenced(ConditionVar->getLocation(), ConditionVar);
2048
John Wiegley01296292011-04-08 18:41:53 +00002049 if (ConvertToBoolean) {
2050 Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
2051 if (Condition.isInvalid())
2052 return ExprError();
2053 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002054
John Wiegley01296292011-04-08 18:41:53 +00002055 return move(Condition);
Douglas Gregor633caca2009-11-23 23:44:04 +00002056}
2057
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00002058/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
John Wiegley01296292011-04-08 18:41:53 +00002059ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00002060 // C++ 6.4p4:
2061 // The value of a condition that is an initialized declaration in a statement
2062 // other than a switch statement is the value of the declared variable
2063 // implicitly converted to type bool. If that conversion is ill-formed, the
2064 // program is ill-formed.
2065 // The value of a condition that is an expression is the value of the
2066 // expression, implicitly converted to bool.
2067 //
Douglas Gregor5fb53972009-01-14 15:45:31 +00002068 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00002069}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00002070
2071/// Helper function to determine whether this is the (deprecated) C++
2072/// conversion from a string literal to a pointer to non-const char or
2073/// non-const wchar_t (for narrow and wide string literals,
2074/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00002075bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00002076Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
2077 // Look inside the implicit cast, if it exists.
2078 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
2079 From = Cast->getSubExpr();
2080
2081 // A string literal (2.13.4) that is not a wide string literal can
2082 // be converted to an rvalue of type "pointer to char"; a wide
2083 // string literal can be converted to an rvalue of type "pointer
2084 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00002085 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002086 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00002087 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00002088 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00002089 // This conversion is considered only when there is an
2090 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregorfb65e592011-07-27 05:40:30 +00002091 if (!ToPtrType->getPointeeType().hasQualifiers()) {
2092 switch (StrLit->getKind()) {
2093 case StringLiteral::UTF8:
2094 case StringLiteral::UTF16:
2095 case StringLiteral::UTF32:
2096 // We don't allow UTF literals to be implicitly converted
2097 break;
2098 case StringLiteral::Ascii:
2099 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
2100 ToPointeeType->getKind() == BuiltinType::Char_S);
2101 case StringLiteral::Wide:
2102 return ToPointeeType->isWideCharType();
2103 }
2104 }
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00002105 }
2106
2107 return false;
2108}
Douglas Gregor39c16d42008-10-24 04:54:22 +00002109
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002110static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00002111 SourceLocation CastLoc,
2112 QualType Ty,
2113 CastKind Kind,
2114 CXXMethodDecl *Method,
John McCall30909032011-09-21 08:36:56 +00002115 DeclAccessPair FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002116 bool HadMultipleCandidates,
John McCalle3027922010-08-25 11:45:40 +00002117 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00002118 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002119 default: llvm_unreachable("Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00002120 case CK_ConstructorConversion: {
Douglas Gregorc7a31072011-10-10 22:41:00 +00002121 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
John McCall37ad5512010-08-23 06:44:23 +00002122 ASTOwningVector<Expr*> ConstructorArgs(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002123
Douglas Gregorc7a31072011-10-10 22:41:00 +00002124 if (S.CompleteConstructorCall(Constructor,
John McCallfaf5fb42010-08-26 23:41:50 +00002125 MultiExprArg(&From, 1),
Douglas Gregora4253922010-04-16 22:17:36 +00002126 CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00002127 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002128
Douglas Gregorc7a31072011-10-10 22:41:00 +00002129 S.CheckConstructorAccess(CastLoc, Constructor, Constructor->getAccess(),
2130 S.PDiag(diag::err_access_ctor));
2131
2132 ExprResult Result
2133 = S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2134 move_arg(ConstructorArgs),
2135 HadMultipleCandidates, /*ZeroInit*/ false,
2136 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00002137 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00002138 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002139
Douglas Gregora4253922010-04-16 22:17:36 +00002140 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
2141 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002142
John McCalle3027922010-08-25 11:45:40 +00002143 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00002144 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002145
Douglas Gregora4253922010-04-16 22:17:36 +00002146 // Create an implicit call expr that calls it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002147 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method,
2148 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00002149 if (Result.isInvalid())
2150 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00002151 // Record usage of conversion in an implicit cast.
2152 Result = S.Owned(ImplicitCastExpr::Create(S.Context,
2153 Result.get()->getType(),
2154 CK_UserDefinedConversion,
2155 Result.get(), 0,
2156 Result.get()->getValueKind()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002157
John McCall30909032011-09-21 08:36:56 +00002158 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ 0, FoundDecl);
2159
Douglas Gregor668443e2011-01-20 00:18:04 +00002160 return S.MaybeBindToTemporary(Result.get());
Douglas Gregora4253922010-04-16 22:17:36 +00002161 }
2162 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002163}
Douglas Gregora4253922010-04-16 22:17:36 +00002164
Douglas Gregor5fb53972009-01-14 15:45:31 +00002165/// PerformImplicitConversion - Perform an implicit conversion of the
2166/// expression From to the type ToType using the pre-computed implicit
John Wiegley01296292011-04-08 18:41:53 +00002167/// conversion sequence ICS. Returns the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002168/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002169/// used in the error message.
John Wiegley01296292011-04-08 18:41:53 +00002170ExprResult
2171Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002172 const ImplicitConversionSequence &ICS,
John McCall31168b02011-06-15 23:02:42 +00002173 AssignmentAction Action,
2174 CheckedConversionKind CCK) {
John McCall0d1da222010-01-12 00:44:57 +00002175 switch (ICS.getKind()) {
John Wiegley01296292011-04-08 18:41:53 +00002176 case ImplicitConversionSequence::StandardConversion: {
Richard Smith507840d2011-11-29 22:48:16 +00002177 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
2178 Action, CCK);
John Wiegley01296292011-04-08 18:41:53 +00002179 if (Res.isInvalid())
2180 return ExprError();
2181 From = Res.take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002182 break;
John Wiegley01296292011-04-08 18:41:53 +00002183 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00002184
Anders Carlsson110b07b2009-09-15 06:28:28 +00002185 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002186
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00002187 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00002188 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00002189 QualType BeforeToType;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00002190 assert(FD && "FIXME: aggregate initialization from init list");
Anders Carlsson110b07b2009-09-15 06:28:28 +00002191 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00002192 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002193
Anders Carlsson110b07b2009-09-15 06:28:28 +00002194 // If the user-defined conversion is specified by a conversion function,
2195 // the initial standard conversion sequence converts the source type to
2196 // the implicit object parameter of the conversion function.
2197 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00002198 } else {
2199 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00002200 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002201 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00002202 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002203 // If the user-defined conversion is specified by a constructor, the
Fariborz Jahanian55824512009-11-06 00:23:08 +00002204 // initial standard conversion sequence converts the source type to the
2205 // type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00002206 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
2207 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002208 }
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00002209 // Watch out for elipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00002210 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley01296292011-04-08 18:41:53 +00002211 ExprResult Res =
Richard Smith507840d2011-11-29 22:48:16 +00002212 PerformImplicitConversion(From, BeforeToType,
2213 ICS.UserDefined.Before, AA_Converting,
2214 CCK);
John Wiegley01296292011-04-08 18:41:53 +00002215 if (Res.isInvalid())
2216 return ExprError();
2217 From = Res.take();
Fariborz Jahanian55824512009-11-06 00:23:08 +00002218 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002219
2220 ExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00002221 = BuildCXXCastArgument(*this,
2222 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00002223 ToType.getNonReferenceType(),
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002224 CastKind, cast<CXXMethodDecl>(FD),
2225 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002226 ICS.UserDefined.HadMultipleCandidates,
John McCallb268a282010-08-23 23:25:46 +00002227 From);
Anders Carlssone9766d52009-09-09 21:33:21 +00002228
2229 if (CastArg.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00002230 return ExprError();
Eli Friedmane96f1d32009-11-27 04:41:50 +00002231
John Wiegley01296292011-04-08 18:41:53 +00002232 From = CastArg.take();
Eli Friedmane96f1d32009-11-27 04:41:50 +00002233
Richard Smith507840d2011-11-29 22:48:16 +00002234 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
2235 AA_Converting, CCK);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00002236 }
John McCall0d1da222010-01-12 00:44:57 +00002237
2238 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00002239 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00002240 PDiag(diag::err_typecheck_ambiguous_condition)
2241 << From->getSourceRange());
John Wiegley01296292011-04-08 18:41:53 +00002242 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002243
Douglas Gregor39c16d42008-10-24 04:54:22 +00002244 case ImplicitConversionSequence::EllipsisConversion:
David Blaikie83d382b2011-09-23 05:06:16 +00002245 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00002246
2247 case ImplicitConversionSequence::BadConversion:
John Wiegley01296292011-04-08 18:41:53 +00002248 return ExprError();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002249 }
2250
2251 // Everything went well.
John Wiegley01296292011-04-08 18:41:53 +00002252 return Owned(From);
Douglas Gregor39c16d42008-10-24 04:54:22 +00002253}
2254
Richard Smith507840d2011-11-29 22:48:16 +00002255/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor39c16d42008-10-24 04:54:22 +00002256/// expression From to the type ToType by following the standard
John Wiegley01296292011-04-08 18:41:53 +00002257/// conversion sequence SCS. Returns the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00002258/// expression. Flavor is the context in which we're performing this
2259/// conversion, for use in error messages.
John Wiegley01296292011-04-08 18:41:53 +00002260ExprResult
Richard Smith507840d2011-11-29 22:48:16 +00002261Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002262 const StandardConversionSequence& SCS,
John McCall31168b02011-06-15 23:02:42 +00002263 AssignmentAction Action,
2264 CheckedConversionKind CCK) {
2265 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
2266
Mike Stump87c57ac2009-05-16 07:39:55 +00002267 // Overall FIXME: we are recomputing too many types here and doing far too
2268 // much extra work. What this means is that we need to keep track of more
2269 // information that is computed when we try the implicit conversion initially,
2270 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00002271 QualType FromType = From->getType();
John McCall31168b02011-06-15 23:02:42 +00002272
Douglas Gregor2fe98832008-11-03 19:09:14 +00002273 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00002274 // FIXME: When can ToType be a reference type?
2275 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00002276 if (SCS.Second == ICK_Derived_To_Base) {
John McCall37ad5512010-08-23 06:44:23 +00002277 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanian49850df2009-09-25 18:59:21 +00002278 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCall37ad5512010-08-23 06:44:23 +00002279 MultiExprArg(*this, &From, 1),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002280 /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00002281 ConstructorArgs))
John Wiegley01296292011-04-08 18:41:53 +00002282 return ExprError();
2283 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2284 ToType, SCS.CopyConstructor,
2285 move_arg(ConstructorArgs),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002286 /*HadMultipleCandidates*/ false,
John Wiegley01296292011-04-08 18:41:53 +00002287 /*ZeroInit*/ false,
2288 CXXConstructExpr::CK_Complete,
2289 SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00002290 }
John Wiegley01296292011-04-08 18:41:53 +00002291 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2292 ToType, SCS.CopyConstructor,
2293 MultiExprArg(*this, &From, 1),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002294 /*HadMultipleCandidates*/ false,
John Wiegley01296292011-04-08 18:41:53 +00002295 /*ZeroInit*/ false,
2296 CXXConstructExpr::CK_Complete,
2297 SourceRange());
Douglas Gregor2fe98832008-11-03 19:09:14 +00002298 }
2299
Douglas Gregor980fb162010-04-29 18:24:40 +00002300 // Resolve overloaded function references.
2301 if (Context.hasSameType(FromType, Context.OverloadTy)) {
2302 DeclAccessPair Found;
2303 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2304 true, Found);
2305 if (!Fn)
John Wiegley01296292011-04-08 18:41:53 +00002306 return ExprError();
Douglas Gregor980fb162010-04-29 18:24:40 +00002307
2308 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
John Wiegley01296292011-04-08 18:41:53 +00002309 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002310
Douglas Gregor980fb162010-04-29 18:24:40 +00002311 From = FixOverloadedFunctionReference(From, Found, Fn);
2312 FromType = From->getType();
2313 }
2314
Richard Smith507840d2011-11-29 22:48:16 +00002315 // Perform the first implicit conversion.
Douglas Gregor39c16d42008-10-24 04:54:22 +00002316 switch (SCS.First) {
2317 case ICK_Identity:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002318 // Nothing to do.
2319 break;
2320
John McCall34376a62010-12-04 03:47:34 +00002321 case ICK_Lvalue_To_Rvalue:
John McCall526ab472011-10-25 17:37:35 +00002322 assert(From->getObjectKind() != OK_ObjCProperty);
John McCall34376a62010-12-04 03:47:34 +00002323 FromType = FromType.getUnqualifiedType();
2324 From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
2325 From, 0, VK_RValue);
2326 break;
2327
Douglas Gregor39c16d42008-10-24 04:54:22 +00002328 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00002329 FromType = Context.getArrayDecayedType(FromType);
Richard Smith507840d2011-11-29 22:48:16 +00002330 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
2331 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor171c45a2009-02-18 21:56:37 +00002332 break;
2333
2334 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002335 FromType = Context.getPointerType(FromType);
Richard Smith507840d2011-11-29 22:48:16 +00002336 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
2337 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002338 break;
2339
2340 default:
David Blaikie83d382b2011-09-23 05:06:16 +00002341 llvm_unreachable("Improper first standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00002342 }
2343
Richard Smith507840d2011-11-29 22:48:16 +00002344 // Perform the second implicit conversion
Douglas Gregor39c16d42008-10-24 04:54:22 +00002345 switch (SCS.Second) {
2346 case ICK_Identity:
Sebastian Redl5d431642009-10-10 12:04:10 +00002347 // If both sides are functions (or pointers/references to them), there could
2348 // be incompatible exception declarations.
2349 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00002350 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00002351 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00002352 break;
2353
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00002354 case ICK_NoReturn_Adjustment:
2355 // If both sides are functions (or pointers/references to them), there could
2356 // be incompatible exception declarations.
2357 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00002358 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002359
Richard Smith507840d2011-11-29 22:48:16 +00002360 From = ImpCastExprToType(From, ToType, CK_NoOp,
2361 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00002362 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002363
Douglas Gregor39c16d42008-10-24 04:54:22 +00002364 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002365 case ICK_Integral_Conversion:
Richard Smith507840d2011-11-29 22:48:16 +00002366 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
2367 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002368 break;
2369
2370 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002371 case ICK_Floating_Conversion:
Richard Smith507840d2011-11-29 22:48:16 +00002372 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
2373 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002374 break;
2375
2376 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00002377 case ICK_Complex_Conversion: {
2378 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2379 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2380 CastKind CK;
2381 if (FromEl->isRealFloatingType()) {
2382 if (ToEl->isRealFloatingType())
2383 CK = CK_FloatingComplexCast;
2384 else
2385 CK = CK_FloatingComplexToIntegralComplex;
2386 } else if (ToEl->isRealFloatingType()) {
2387 CK = CK_IntegralComplexToFloatingComplex;
2388 } else {
2389 CK = CK_IntegralComplexCast;
2390 }
Richard Smith507840d2011-11-29 22:48:16 +00002391 From = ImpCastExprToType(From, ToType, CK,
2392 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002393 break;
John McCall8cb679e2010-11-15 09:13:47 +00002394 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00002395
Douglas Gregor39c16d42008-10-24 04:54:22 +00002396 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00002397 if (ToType->isRealFloatingType())
Richard Smith507840d2011-11-29 22:48:16 +00002398 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
2399 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002400 else
Richard Smith507840d2011-11-29 22:48:16 +00002401 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
2402 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002403 break;
2404
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002405 case ICK_Compatible_Conversion:
Richard Smith507840d2011-11-29 22:48:16 +00002406 From = ImpCastExprToType(From, ToType, CK_NoOp,
2407 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002408 break;
2409
John McCall31168b02011-06-15 23:02:42 +00002410 case ICK_Writeback_Conversion:
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002411 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00002412 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002413 // Diagnose incompatible Objective-C conversions
Douglas Gregor2720dc62011-06-11 04:42:12 +00002414 if (Action == AA_Initializing || Action == AA_Assigning)
Fariborz Jahanian413e0642011-03-21 19:08:42 +00002415 Diag(From->getSourceRange().getBegin(),
2416 diag::ext_typecheck_convert_incompatible_pointer)
2417 << ToType << From->getType() << Action
Anna Zaks3b402712011-07-28 19:51:27 +00002418 << From->getSourceRange() << 0;
Fariborz Jahanian413e0642011-03-21 19:08:42 +00002419 else
2420 Diag(From->getSourceRange().getBegin(),
2421 diag::ext_typecheck_convert_incompatible_pointer)
2422 << From->getType() << ToType << Action
Anna Zaks3b402712011-07-28 19:51:27 +00002423 << From->getSourceRange() << 0;
John McCall31168b02011-06-15 23:02:42 +00002424
Douglas Gregor33823722011-06-11 01:09:30 +00002425 if (From->getType()->isObjCObjectPointerType() &&
2426 ToType->isObjCObjectPointerType())
2427 EmitRelatedResultTypeNote(From);
Fariborz Jahanianf2913402011-07-08 17:41:42 +00002428 }
2429 else if (getLangOptions().ObjCAutoRefCount &&
2430 !CheckObjCARCUnavailableWeakConversion(ToType,
2431 From->getType())) {
John McCall9c3467e2011-09-09 06:12:06 +00002432 if (Action == AA_Initializing)
2433 Diag(From->getSourceRange().getBegin(),
2434 diag::err_arc_weak_unavailable_assign);
2435 else
2436 Diag(From->getSourceRange().getBegin(),
2437 diag::err_arc_convesion_of_weak_unavailable)
2438 << (Action == AA_Casting) << From->getType() << ToType
2439 << From->getSourceRange();
2440 }
Fariborz Jahanianf2913402011-07-08 17:41:42 +00002441
John McCall8cb679e2010-11-15 09:13:47 +00002442 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00002443 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00002444 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00002445 return ExprError();
John McCallcd78e802011-09-10 01:16:55 +00002446
2447 // Make sure we extend blocks if necessary.
2448 // FIXME: doing this here is really ugly.
2449 if (Kind == CK_BlockPointerToObjCPointerCast) {
2450 ExprResult E = From;
2451 (void) PrepareCastToObjCObjectPointer(E);
2452 From = E.take();
2453 }
2454
Richard Smith507840d2011-11-29 22:48:16 +00002455 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2456 .take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002457 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002458 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002459
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002460 case ICK_Pointer_Member: {
John McCall8cb679e2010-11-15 09:13:47 +00002461 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00002462 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00002463 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00002464 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00002465 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00002466 return ExprError();
Richard Smith507840d2011-11-29 22:48:16 +00002467 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2468 .take();
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002469 break;
2470 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002471
Abramo Bagnara7ccce982011-04-07 09:26:19 +00002472 case ICK_Boolean_Conversion:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002473 // Perform half-to-boolean conversion via float.
2474 if (From->getType()->isHalfType()) {
2475 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).take();
2476 FromType = Context.FloatTy;
2477 }
2478
Richard Smith507840d2011-11-29 22:48:16 +00002479 From = ImpCastExprToType(From, Context.BoolTy,
2480 ScalarTypeToBooleanCastKind(FromType),
2481 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002482 break;
2483
Douglas Gregor88d292c2010-05-13 16:44:06 +00002484 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00002485 CXXCastPath BasePath;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002486 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00002487 ToType.getNonReferenceType(),
2488 From->getLocStart(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002489 From->getSourceRange(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00002490 &BasePath,
Douglas Gregor58281352011-01-27 00:58:17 +00002491 CStyle))
John Wiegley01296292011-04-08 18:41:53 +00002492 return ExprError();
Douglas Gregor88d292c2010-05-13 16:44:06 +00002493
Richard Smith507840d2011-11-29 22:48:16 +00002494 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
2495 CK_DerivedToBase, From->getValueKind(),
2496 &BasePath, CCK).take();
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00002497 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00002498 }
2499
Douglas Gregor46188682010-05-18 22:42:18 +00002500 case ICK_Vector_Conversion:
Richard Smith507840d2011-11-29 22:48:16 +00002501 From = ImpCastExprToType(From, ToType, CK_BitCast,
2502 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor46188682010-05-18 22:42:18 +00002503 break;
2504
2505 case ICK_Vector_Splat:
Richard Smith507840d2011-11-29 22:48:16 +00002506 From = ImpCastExprToType(From, ToType, CK_VectorSplat,
2507 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor46188682010-05-18 22:42:18 +00002508 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002509
Douglas Gregor46188682010-05-18 22:42:18 +00002510 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00002511 // Case 1. x -> _Complex y
2512 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2513 QualType ElType = ToComplex->getElementType();
2514 bool isFloatingComplex = ElType->isRealFloatingType();
2515
2516 // x -> y
2517 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2518 // do nothing
2519 } else if (From->getType()->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00002520 From = ImpCastExprToType(From, ElType,
2521 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
John McCall8cb679e2010-11-15 09:13:47 +00002522 } else {
2523 assert(From->getType()->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00002524 From = ImpCastExprToType(From, ElType,
2525 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
John McCall8cb679e2010-11-15 09:13:47 +00002526 }
2527 // y -> _Complex y
Richard Smith507840d2011-11-29 22:48:16 +00002528 From = ImpCastExprToType(From, ToType,
2529 isFloatingComplex ? CK_FloatingRealToComplex
2530 : CK_IntegralRealToComplex).take();
John McCall8cb679e2010-11-15 09:13:47 +00002531
2532 // Case 2. _Complex x -> y
2533 } else {
2534 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2535 assert(FromComplex);
2536
2537 QualType ElType = FromComplex->getElementType();
2538 bool isFloatingComplex = ElType->isRealFloatingType();
2539
2540 // _Complex x -> x
Richard Smith507840d2011-11-29 22:48:16 +00002541 From = ImpCastExprToType(From, ElType,
2542 isFloatingComplex ? CK_FloatingComplexToReal
2543 : CK_IntegralComplexToReal,
2544 VK_RValue, /*BasePath=*/0, CCK).take();
John McCall8cb679e2010-11-15 09:13:47 +00002545
2546 // x -> y
2547 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2548 // do nothing
2549 } else if (ToType->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00002550 From = ImpCastExprToType(From, ToType,
2551 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
2552 VK_RValue, /*BasePath=*/0, CCK).take();
John McCall8cb679e2010-11-15 09:13:47 +00002553 } else {
2554 assert(ToType->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00002555 From = ImpCastExprToType(From, ToType,
2556 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
2557 VK_RValue, /*BasePath=*/0, CCK).take();
John McCall8cb679e2010-11-15 09:13:47 +00002558 }
2559 }
Douglas Gregor46188682010-05-18 22:42:18 +00002560 break;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002561
2562 case ICK_Block_Pointer_Conversion: {
Richard Smith507840d2011-11-29 22:48:16 +00002563 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
2564 VK_RValue, /*BasePath=*/0, CCK).take();
John McCall31168b02011-06-15 23:02:42 +00002565 break;
2566 }
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002567
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00002568 case ICK_TransparentUnionConversion: {
John Wiegley01296292011-04-08 18:41:53 +00002569 ExprResult FromRes = Owned(From);
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00002570 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00002571 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
2572 if (FromRes.isInvalid())
2573 return ExprError();
2574 From = FromRes.take();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00002575 assert ((ConvTy == Sema::Compatible) &&
2576 "Improper transparent union conversion");
2577 (void)ConvTy;
2578 break;
2579 }
2580
Douglas Gregor46188682010-05-18 22:42:18 +00002581 case ICK_Lvalue_To_Rvalue:
2582 case ICK_Array_To_Pointer:
2583 case ICK_Function_To_Pointer:
2584 case ICK_Qualification:
2585 case ICK_Num_Conversion_Kinds:
David Blaikie83d382b2011-09-23 05:06:16 +00002586 llvm_unreachable("Improper second standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00002587 }
2588
2589 switch (SCS.Third) {
2590 case ICK_Identity:
2591 // Nothing to do.
2592 break;
2593
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002594 case ICK_Qualification: {
2595 // The qualification keeps the category of the inner expression, unless the
2596 // target type isn't a reference.
John McCall2536c6d2010-08-25 10:28:54 +00002597 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanbe4b3632011-09-27 21:58:52 +00002598 From->getValueKind() : VK_RValue;
Richard Smith507840d2011-11-29 22:48:16 +00002599 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
2600 CK_NoOp, VK, /*BasePath=*/0, CCK).take();
Douglas Gregore489a7d2010-02-28 18:30:25 +00002601
Douglas Gregore981bb02011-03-14 16:13:32 +00002602 if (SCS.DeprecatedStringLiteralToCharPtr &&
2603 !getLangOptions().WritableStrings)
Douglas Gregore489a7d2010-02-28 18:30:25 +00002604 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2605 << ToType.getNonReferenceType();
2606
Douglas Gregor39c16d42008-10-24 04:54:22 +00002607 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002608 }
2609
Douglas Gregor39c16d42008-10-24 04:54:22 +00002610 default:
David Blaikie83d382b2011-09-23 05:06:16 +00002611 llvm_unreachable("Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00002612 }
2613
John Wiegley01296292011-04-08 18:41:53 +00002614 return Owned(From);
Douglas Gregor39c16d42008-10-24 04:54:22 +00002615}
2616
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002617ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor54e5b132010-09-09 16:14:44 +00002618 SourceLocation KWLoc,
2619 ParsedType Ty,
2620 SourceLocation RParen) {
2621 TypeSourceInfo *TSInfo;
2622 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump11289f42009-09-09 15:08:12 +00002623
Douglas Gregor54e5b132010-09-09 16:14:44 +00002624 if (!TSInfo)
2625 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002626 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor54e5b132010-09-09 16:14:44 +00002627}
2628
Chandler Carruth8e172c62011-05-01 06:51:22 +00002629/// \brief Check the completeness of a type in a unary type trait.
2630///
2631/// If the particular type trait requires a complete type, tries to complete
2632/// it. If completing the type fails, a diagnostic is emitted and false
2633/// returned. If completing the type succeeds or no completion was required,
2634/// returns true.
2635static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S,
2636 UnaryTypeTrait UTT,
2637 SourceLocation Loc,
2638 QualType ArgTy) {
2639 // C++0x [meta.unary.prop]p3:
2640 // For all of the class templates X declared in this Clause, instantiating
2641 // that template with a template argument that is a class template
2642 // specialization may result in the implicit instantiation of the template
2643 // argument if and only if the semantics of X require that the argument
2644 // must be a complete type.
2645 // We apply this rule to all the type trait expressions used to implement
2646 // these class templates. We also try to follow any GCC documented behavior
2647 // in these expressions to ensure portability of standard libraries.
2648 switch (UTT) {
Chandler Carruth8e172c62011-05-01 06:51:22 +00002649 // is_complete_type somewhat obviously cannot require a complete type.
2650 case UTT_IsCompleteType:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00002651 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00002652
2653 // These traits are modeled on the type predicates in C++0x
2654 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
2655 // requiring a complete type, as whether or not they return true cannot be
2656 // impacted by the completeness of the type.
2657 case UTT_IsVoid:
2658 case UTT_IsIntegral:
2659 case UTT_IsFloatingPoint:
2660 case UTT_IsArray:
2661 case UTT_IsPointer:
2662 case UTT_IsLvalueReference:
2663 case UTT_IsRvalueReference:
2664 case UTT_IsMemberFunctionPointer:
2665 case UTT_IsMemberObjectPointer:
2666 case UTT_IsEnum:
2667 case UTT_IsUnion:
2668 case UTT_IsClass:
2669 case UTT_IsFunction:
2670 case UTT_IsReference:
2671 case UTT_IsArithmetic:
2672 case UTT_IsFundamental:
2673 case UTT_IsObject:
2674 case UTT_IsScalar:
2675 case UTT_IsCompound:
2676 case UTT_IsMemberPointer:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00002677 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00002678
2679 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
2680 // which requires some of its traits to have the complete type. However,
2681 // the completeness of the type cannot impact these traits' semantics, and
2682 // so they don't require it. This matches the comments on these traits in
2683 // Table 49.
2684 case UTT_IsConst:
2685 case UTT_IsVolatile:
2686 case UTT_IsSigned:
2687 case UTT_IsUnsigned:
2688 return true;
2689
2690 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
Chandler Carrutha62d8a52011-05-01 19:18:02 +00002691 // applied to a complete type.
Chandler Carruth8e172c62011-05-01 06:51:22 +00002692 case UTT_IsTrivial:
Alexis Huntd9a5cc12011-05-13 00:31:07 +00002693 case UTT_IsTriviallyCopyable:
Chandler Carruth8e172c62011-05-01 06:51:22 +00002694 case UTT_IsStandardLayout:
2695 case UTT_IsPOD:
2696 case UTT_IsLiteral:
2697 case UTT_IsEmpty:
2698 case UTT_IsPolymorphic:
2699 case UTT_IsAbstract:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00002700 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00002701
Douglas Gregordca70af2011-12-03 18:14:24 +00002702 // These traits require a complete type.
2703 case UTT_IsFinal:
2704
Chandler Carrutha62d8a52011-05-01 19:18:02 +00002705 // These trait expressions are designed to help implement predicates in
Chandler Carruth8e172c62011-05-01 06:51:22 +00002706 // [meta.unary.prop] despite not being named the same. They are specified
2707 // by both GCC and the Embarcadero C++ compiler, and require the complete
2708 // type due to the overarching C++0x type predicates being implemented
2709 // requiring the complete type.
2710 case UTT_HasNothrowAssign:
2711 case UTT_HasNothrowConstructor:
2712 case UTT_HasNothrowCopy:
2713 case UTT_HasTrivialAssign:
Alexis Huntf479f1b2011-05-09 18:22:59 +00002714 case UTT_HasTrivialDefaultConstructor:
Chandler Carruth8e172c62011-05-01 06:51:22 +00002715 case UTT_HasTrivialCopy:
2716 case UTT_HasTrivialDestructor:
2717 case UTT_HasVirtualDestructor:
2718 // Arrays of unknown bound are expressly allowed.
2719 QualType ElTy = ArgTy;
2720 if (ArgTy->isIncompleteArrayType())
2721 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
2722
2723 // The void type is expressly allowed.
2724 if (ElTy->isVoidType())
2725 return true;
2726
2727 return !S.RequireCompleteType(
2728 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleyd3522222011-04-28 02:06:46 +00002729 }
Chandler Carruth8b0cf1d2011-05-01 07:23:17 +00002730 llvm_unreachable("Type trait not handled by switch");
Chandler Carruth8e172c62011-05-01 06:51:22 +00002731}
2732
2733static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT,
2734 SourceLocation KeyLoc, QualType T) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00002735 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleyd3522222011-04-28 02:06:46 +00002736
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002737 ASTContext &C = Self.Context;
2738 switch(UTT) {
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002739 // Type trait expressions corresponding to the primary type category
2740 // predicates in C++0x [meta.unary.cat].
2741 case UTT_IsVoid:
2742 return T->isVoidType();
2743 case UTT_IsIntegral:
2744 return T->isIntegralType(C);
2745 case UTT_IsFloatingPoint:
2746 return T->isFloatingType();
2747 case UTT_IsArray:
2748 return T->isArrayType();
2749 case UTT_IsPointer:
2750 return T->isPointerType();
2751 case UTT_IsLvalueReference:
2752 return T->isLValueReferenceType();
2753 case UTT_IsRvalueReference:
2754 return T->isRValueReferenceType();
2755 case UTT_IsMemberFunctionPointer:
2756 return T->isMemberFunctionPointerType();
2757 case UTT_IsMemberObjectPointer:
2758 return T->isMemberDataPointerType();
2759 case UTT_IsEnum:
2760 return T->isEnumeralType();
Chandler Carruth100f3a92011-05-01 06:11:03 +00002761 case UTT_IsUnion:
Chandler Carruthaf858862011-05-01 09:29:58 +00002762 return T->isUnionType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002763 case UTT_IsClass:
Chandler Carruthaf858862011-05-01 09:29:58 +00002764 return T->isClassType() || T->isStructureType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002765 case UTT_IsFunction:
2766 return T->isFunctionType();
2767
2768 // Type trait expressions which correspond to the convenient composition
2769 // predicates in C++0x [meta.unary.comp].
2770 case UTT_IsReference:
2771 return T->isReferenceType();
2772 case UTT_IsArithmetic:
Chandler Carruthaf858862011-05-01 09:29:58 +00002773 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002774 case UTT_IsFundamental:
Chandler Carruthaf858862011-05-01 09:29:58 +00002775 return T->isFundamentalType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002776 case UTT_IsObject:
Chandler Carruthaf858862011-05-01 09:29:58 +00002777 return T->isObjectType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002778 case UTT_IsScalar:
John McCall31168b02011-06-15 23:02:42 +00002779 // Note: semantic analysis depends on Objective-C lifetime types to be
2780 // considered scalar types. However, such types do not actually behave
2781 // like scalar types at run time (since they may require retain/release
2782 // operations), so we report them as non-scalar.
2783 if (T->isObjCLifetimeType()) {
2784 switch (T.getObjCLifetime()) {
2785 case Qualifiers::OCL_None:
2786 case Qualifiers::OCL_ExplicitNone:
2787 return true;
2788
2789 case Qualifiers::OCL_Strong:
2790 case Qualifiers::OCL_Weak:
2791 case Qualifiers::OCL_Autoreleasing:
2792 return false;
2793 }
2794 }
2795
Chandler Carruth7ba7bd32011-05-01 09:29:55 +00002796 return T->isScalarType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002797 case UTT_IsCompound:
Chandler Carruthaf858862011-05-01 09:29:58 +00002798 return T->isCompoundType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002799 case UTT_IsMemberPointer:
2800 return T->isMemberPointerType();
2801
2802 // Type trait expressions which correspond to the type property predicates
2803 // in C++0x [meta.unary.prop].
2804 case UTT_IsConst:
2805 return T.isConstQualified();
2806 case UTT_IsVolatile:
2807 return T.isVolatileQualified();
2808 case UTT_IsTrivial:
John McCall31168b02011-06-15 23:02:42 +00002809 return T.isTrivialType(Self.Context);
Alexis Huntd9a5cc12011-05-13 00:31:07 +00002810 case UTT_IsTriviallyCopyable:
John McCall31168b02011-06-15 23:02:42 +00002811 return T.isTriviallyCopyableType(Self.Context);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002812 case UTT_IsStandardLayout:
2813 return T->isStandardLayoutType();
2814 case UTT_IsPOD:
John McCall31168b02011-06-15 23:02:42 +00002815 return T.isPODType(Self.Context);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002816 case UTT_IsLiteral:
2817 return T->isLiteralType();
2818 case UTT_IsEmpty:
2819 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2820 return !RD->isUnion() && RD->isEmpty();
2821 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002822 case UTT_IsPolymorphic:
Chandler Carruth100f3a92011-05-01 06:11:03 +00002823 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2824 return RD->isPolymorphic();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002825 return false;
2826 case UTT_IsAbstract:
Chandler Carruth100f3a92011-05-01 06:11:03 +00002827 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2828 return RD->isAbstract();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002829 return false;
Douglas Gregordca70af2011-12-03 18:14:24 +00002830 case UTT_IsFinal:
2831 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2832 return RD->hasAttr<FinalAttr>();
2833 return false;
John Wiegley65497cc2011-04-27 23:09:49 +00002834 case UTT_IsSigned:
2835 return T->isSignedIntegerType();
John Wiegley65497cc2011-04-27 23:09:49 +00002836 case UTT_IsUnsigned:
2837 return T->isUnsignedIntegerType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002838
2839 // Type trait expressions which query classes regarding their construction,
2840 // destruction, and copying. Rather than being based directly on the
2841 // related type predicates in the standard, they are specified by both
2842 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
2843 // specifications.
2844 //
2845 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
2846 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Alexis Huntf479f1b2011-05-09 18:22:59 +00002847 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002848 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2849 // If __is_pod (type) is true then the trait is true, else if type is
2850 // a cv class or union type (or array thereof) with a trivial default
2851 // constructor ([class.ctor]) then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00002852 if (T.isPODType(Self.Context))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002853 return true;
2854 if (const RecordType *RT =
2855 C.getBaseElementType(T)->getAs<RecordType>())
Alexis Huntf479f1b2011-05-09 18:22:59 +00002856 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDefaultConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002857 return false;
2858 case UTT_HasTrivialCopy:
2859 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2860 // If __is_pod (type) is true or type is a reference type then
2861 // the trait is true, else if type is a cv class or union type
2862 // with a trivial copy constructor ([class.copy]) then the trait
2863 // is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00002864 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002865 return true;
2866 if (const RecordType *RT = T->getAs<RecordType>())
2867 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2868 return false;
2869 case UTT_HasTrivialAssign:
2870 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2871 // If type is const qualified or is a reference type then the
2872 // trait is false. Otherwise if __is_pod (type) is true then the
2873 // trait is true, else if type is a cv class or union type with
2874 // a trivial copy assignment ([class.copy]) then the trait is
2875 // true, else it is false.
2876 // Note: the const and reference restrictions are interesting,
2877 // given that const and reference members don't prevent a class
2878 // from having a trivial copy assignment operator (but do cause
2879 // errors if the copy assignment operator is actually used, q.v.
2880 // [class.copy]p12).
2881
2882 if (C.getBaseElementType(T).isConstQualified())
2883 return false;
John McCall31168b02011-06-15 23:02:42 +00002884 if (T.isPODType(Self.Context))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002885 return true;
2886 if (const RecordType *RT = T->getAs<RecordType>())
2887 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2888 return false;
2889 case UTT_HasTrivialDestructor:
2890 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2891 // If __is_pod (type) is true or type is a reference type
2892 // then the trait is true, else if type is a cv class or union
2893 // type (or array thereof) with a trivial destructor
2894 // ([class.dtor]) then the trait is true, else it is
2895 // false.
John McCall31168b02011-06-15 23:02:42 +00002896 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002897 return true;
John McCall31168b02011-06-15 23:02:42 +00002898
2899 // Objective-C++ ARC: autorelease types don't require destruction.
2900 if (T->isObjCLifetimeType() &&
2901 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
2902 return true;
2903
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002904 if (const RecordType *RT =
2905 C.getBaseElementType(T)->getAs<RecordType>())
2906 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2907 return false;
2908 // TODO: Propagate nothrowness for implicitly declared special members.
2909 case UTT_HasNothrowAssign:
2910 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2911 // If type is const qualified or is a reference type then the
2912 // trait is false. Otherwise if __has_trivial_assign (type)
2913 // is true then the trait is true, else if type is a cv class
2914 // or union type with copy assignment operators that are known
2915 // not to throw an exception then the trait is true, else it is
2916 // false.
2917 if (C.getBaseElementType(T).isConstQualified())
2918 return false;
2919 if (T->isReferenceType())
2920 return false;
John McCall31168b02011-06-15 23:02:42 +00002921 if (T.isPODType(Self.Context) || T->isObjCLifetimeType())
2922 return true;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002923 if (const RecordType *RT = T->getAs<RecordType>()) {
2924 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2925 if (RD->hasTrivialCopyAssignment())
2926 return true;
2927
2928 bool FoundAssign = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002929 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redl058fc822010-09-14 23:40:14 +00002930 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2931 Sema::LookupOrdinaryName);
2932 if (Self.LookupQualifiedName(Res, RD)) {
Douglas Gregor6a0e23f2011-10-12 15:40:49 +00002933 Res.suppressDiagnostics();
Sebastian Redl058fc822010-09-14 23:40:14 +00002934 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2935 Op != OpEnd; ++Op) {
Douglas Gregor6a0e23f2011-10-12 15:40:49 +00002936 if (isa<FunctionTemplateDecl>(*Op))
2937 continue;
2938
Sebastian Redl058fc822010-09-14 23:40:14 +00002939 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2940 if (Operator->isCopyAssignmentOperator()) {
2941 FoundAssign = true;
2942 const FunctionProtoType *CPT
2943 = Operator->getType()->getAs<FunctionProtoType>();
Richard Smith938f40b2011-06-11 17:19:42 +00002944 if (CPT->getExceptionSpecType() == EST_Delayed)
2945 return false;
2946 if (!CPT->isNothrow(Self.Context))
2947 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002948 }
2949 }
2950 }
Douglas Gregor6a0e23f2011-10-12 15:40:49 +00002951
Richard Smith938f40b2011-06-11 17:19:42 +00002952 return FoundAssign;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002953 }
2954 return false;
2955 case UTT_HasNothrowCopy:
2956 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2957 // If __has_trivial_copy (type) is true then the trait is true, else
2958 // if type is a cv class or union type with copy constructors that are
2959 // known not to throw an exception then the trait is true, else it is
2960 // false.
John McCall31168b02011-06-15 23:02:42 +00002961 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002962 return true;
2963 if (const RecordType *RT = T->getAs<RecordType>()) {
2964 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2965 if (RD->hasTrivialCopyConstructor())
2966 return true;
2967
2968 bool FoundConstructor = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002969 unsigned FoundTQs;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002970 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl951006f2010-09-13 21:10:20 +00002971 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002972 Con != ConEnd; ++Con) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00002973 // A template constructor is never a copy constructor.
2974 // FIXME: However, it may actually be selected at the actual overload
2975 // resolution point.
2976 if (isa<FunctionTemplateDecl>(*Con))
2977 continue;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002978 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2979 if (Constructor->isCopyConstructor(FoundTQs)) {
2980 FoundConstructor = true;
2981 const FunctionProtoType *CPT
2982 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smith938f40b2011-06-11 17:19:42 +00002983 if (CPT->getExceptionSpecType() == EST_Delayed)
2984 return false;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002985 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00002986 // For now, we'll be conservative and assume that they can throw.
Richard Smith938f40b2011-06-11 17:19:42 +00002987 if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1)
2988 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002989 }
2990 }
2991
Richard Smith938f40b2011-06-11 17:19:42 +00002992 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002993 }
2994 return false;
2995 case UTT_HasNothrowConstructor:
2996 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2997 // If __has_trivial_constructor (type) is true then the trait is
2998 // true, else if type is a cv class or union type (or array
2999 // thereof) with a default constructor that is known not to
3000 // throw an exception then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00003001 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003002 return true;
3003 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
3004 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntf479f1b2011-05-09 18:22:59 +00003005 if (RD->hasTrivialDefaultConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003006 return true;
3007
Sebastian Redlc15c3262010-09-13 22:02:47 +00003008 DeclContext::lookup_const_iterator Con, ConEnd;
3009 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
3010 Con != ConEnd; ++Con) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00003011 // FIXME: In C++0x, a constructor template can be a default constructor.
3012 if (isa<FunctionTemplateDecl>(*Con))
3013 continue;
Sebastian Redlc15c3262010-09-13 22:02:47 +00003014 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3015 if (Constructor->isDefaultConstructor()) {
3016 const FunctionProtoType *CPT
3017 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smith938f40b2011-06-11 17:19:42 +00003018 if (CPT->getExceptionSpecType() == EST_Delayed)
3019 return false;
Sebastian Redlc15c3262010-09-13 22:02:47 +00003020 // TODO: check whether evaluating default arguments can throw.
3021 // For now, we'll be conservative and assume that they can throw.
Sebastian Redl31ad7542011-03-13 17:09:40 +00003022 return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
Sebastian Redlc15c3262010-09-13 22:02:47 +00003023 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003024 }
3025 }
3026 return false;
3027 case UTT_HasVirtualDestructor:
3028 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3029 // If type is a class type with a virtual destructor ([class.dtor])
3030 // then the trait is true, else it is false.
3031 if (const RecordType *Record = T->getAs<RecordType>()) {
3032 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redl058fc822010-09-14 23:40:14 +00003033 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003034 return Destructor->isVirtual();
3035 }
3036 return false;
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003037
3038 // These type trait expressions are modeled on the specifications for the
3039 // Embarcadero C++0x type trait functions:
3040 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
3041 case UTT_IsCompleteType:
3042 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
3043 // Returns True if and only if T is a complete type at the point of the
3044 // function call.
3045 return !T->isIncompleteType();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003046 }
Chandler Carruthb42fb192011-05-01 07:44:17 +00003047 llvm_unreachable("Type trait not covered by switch");
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003048}
3049
3050ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor54e5b132010-09-09 16:14:44 +00003051 SourceLocation KWLoc,
3052 TypeSourceInfo *TSInfo,
3053 SourceLocation RParen) {
3054 QualType T = TSInfo->getType();
Chandler Carruthb0776202011-04-30 10:07:32 +00003055 if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T))
3056 return ExprError();
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003057
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003058 bool Value = false;
3059 if (!T->isDependentType())
Chandler Carruth8e172c62011-05-01 06:51:22 +00003060 Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003061
3062 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson1f9648d2009-07-07 19:06:02 +00003063 RParen, Context.BoolTy));
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003064}
Sebastian Redl5822f082009-02-07 20:10:22 +00003065
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003066ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
3067 SourceLocation KWLoc,
3068 ParsedType LhsTy,
3069 ParsedType RhsTy,
3070 SourceLocation RParen) {
3071 TypeSourceInfo *LhsTSInfo;
3072 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
3073 if (!LhsTSInfo)
3074 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
3075
3076 TypeSourceInfo *RhsTSInfo;
3077 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
3078 if (!RhsTSInfo)
3079 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
3080
3081 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
3082}
3083
3084static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
3085 QualType LhsT, QualType RhsT,
3086 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00003087 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
3088 "Cannot evaluate traits of dependent types");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003089
3090 switch(BTT) {
John McCall388ef532011-01-28 22:02:36 +00003091 case BTT_IsBaseOf: {
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003092 // C++0x [meta.rel]p2
John McCall388ef532011-01-28 22:02:36 +00003093 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003094 // Base and Derived are not unions and name the same class type without
3095 // regard to cv-qualifiers.
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003096
John McCall388ef532011-01-28 22:02:36 +00003097 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
3098 if (!lhsRecord) return false;
3099
3100 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
3101 if (!rhsRecord) return false;
3102
3103 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
3104 == (lhsRecord == rhsRecord));
3105
3106 if (lhsRecord == rhsRecord)
3107 return !lhsRecord->getDecl()->isUnion();
3108
3109 // C++0x [meta.rel]p2:
3110 // If Base and Derived are class types and are different types
3111 // (ignoring possible cv-qualifiers) then Derived shall be a
3112 // complete type.
3113 if (Self.RequireCompleteType(KeyLoc, RhsT,
3114 diag::err_incomplete_type_used_in_type_trait_expr))
3115 return false;
3116
3117 return cast<CXXRecordDecl>(rhsRecord->getDecl())
3118 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
3119 }
John Wiegley65497cc2011-04-27 23:09:49 +00003120 case BTT_IsSame:
3121 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichet34b21132010-12-08 22:35:30 +00003122 case BTT_TypeCompatible:
3123 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
3124 RhsT.getUnqualifiedType());
John Wiegley65497cc2011-04-27 23:09:49 +00003125 case BTT_IsConvertible:
Douglas Gregor8006e762011-01-27 20:28:01 +00003126 case BTT_IsConvertibleTo: {
3127 // C++0x [meta.rel]p4:
3128 // Given the following function prototype:
3129 //
3130 // template <class T>
3131 // typename add_rvalue_reference<T>::type create();
3132 //
3133 // the predicate condition for a template specialization
3134 // is_convertible<From, To> shall be satisfied if and only if
3135 // the return expression in the following code would be
3136 // well-formed, including any implicit conversions to the return
3137 // type of the function:
3138 //
3139 // To test() {
3140 // return create<From>();
3141 // }
3142 //
3143 // Access checking is performed as if in a context unrelated to To and
3144 // From. Only the validity of the immediate context of the expression
3145 // of the return-statement (including conversions to the return type)
3146 // is considered.
3147 //
3148 // We model the initialization as a copy-initialization of a temporary
3149 // of the appropriate type, which for this expression is identical to the
3150 // return statement (since NRVO doesn't apply).
3151 if (LhsT->isObjectType() || LhsT->isFunctionType())
3152 LhsT = Self.Context.getRValueReferenceType(LhsT);
3153
3154 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorc03a1082011-01-28 02:26:04 +00003155 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor8006e762011-01-27 20:28:01 +00003156 Expr::getValueKindForType(LhsT));
3157 Expr *FromPtr = &From;
3158 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
3159 SourceLocation()));
3160
Douglas Gregoredb76852011-01-27 22:31:44 +00003161 // Perform the initialization within a SFINAE trap at translation unit
3162 // scope.
3163 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3164 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Douglas Gregor8006e762011-01-27 20:28:01 +00003165 InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00003166 if (Init.Failed())
Douglas Gregor8006e762011-01-27 20:28:01 +00003167 return false;
Douglas Gregoredb76852011-01-27 22:31:44 +00003168
Douglas Gregor8006e762011-01-27 20:28:01 +00003169 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
3170 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
3171 }
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003172 }
3173 llvm_unreachable("Unknown type trait or not implemented");
3174}
3175
3176ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
3177 SourceLocation KWLoc,
3178 TypeSourceInfo *LhsTSInfo,
3179 TypeSourceInfo *RhsTSInfo,
3180 SourceLocation RParen) {
3181 QualType LhsT = LhsTSInfo->getType();
3182 QualType RhsT = RhsTSInfo->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003183
John McCall388ef532011-01-28 22:02:36 +00003184 if (BTT == BTT_TypeCompatible) {
Francois Pichet34b21132010-12-08 22:35:30 +00003185 if (getLangOptions().CPlusPlus) {
3186 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
3187 << SourceRange(KWLoc, RParen);
3188 return ExprError();
3189 }
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003190 }
3191
3192 bool Value = false;
3193 if (!LhsT->isDependentType() && !RhsT->isDependentType())
3194 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
3195
Francois Pichet34b21132010-12-08 22:35:30 +00003196 // Select trait result type.
3197 QualType ResultType;
3198 switch (BTT) {
Francois Pichet34b21132010-12-08 22:35:30 +00003199 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
John Wiegley65497cc2011-04-27 23:09:49 +00003200 case BTT_IsConvertible: ResultType = Context.BoolTy; break;
3201 case BTT_IsSame: ResultType = Context.BoolTy; break;
Francois Pichet34b21132010-12-08 22:35:30 +00003202 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
Douglas Gregor8006e762011-01-27 20:28:01 +00003203 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
Francois Pichet34b21132010-12-08 22:35:30 +00003204 }
3205
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003206 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
3207 RhsTSInfo, Value, RParen,
Francois Pichet34b21132010-12-08 22:35:30 +00003208 ResultType));
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003209}
3210
John Wiegley6242b6a2011-04-28 00:16:57 +00003211ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3212 SourceLocation KWLoc,
3213 ParsedType Ty,
3214 Expr* DimExpr,
3215 SourceLocation RParen) {
3216 TypeSourceInfo *TSInfo;
3217 QualType T = GetTypeFromParser(Ty, &TSInfo);
3218 if (!TSInfo)
3219 TSInfo = Context.getTrivialTypeSourceInfo(T);
3220
3221 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
3222}
3223
3224static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
3225 QualType T, Expr *DimExpr,
3226 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00003227 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley6242b6a2011-04-28 00:16:57 +00003228
3229 switch(ATT) {
3230 case ATT_ArrayRank:
3231 if (T->isArrayType()) {
3232 unsigned Dim = 0;
3233 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3234 ++Dim;
3235 T = AT->getElementType();
3236 }
3237 return Dim;
John Wiegley6242b6a2011-04-28 00:16:57 +00003238 }
John Wiegleyd3522222011-04-28 02:06:46 +00003239 return 0;
3240
John Wiegley6242b6a2011-04-28 00:16:57 +00003241 case ATT_ArrayExtent: {
3242 llvm::APSInt Value;
3243 uint64_t Dim;
John Wiegleyd3522222011-04-28 02:06:46 +00003244 if (DimExpr->isIntegerConstantExpr(Value, Self.Context, 0, false)) {
3245 if (Value < llvm::APSInt(Value.getBitWidth(), Value.isUnsigned())) {
3246 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
3247 DimExpr->getSourceRange();
3248 return false;
3249 }
John Wiegley6242b6a2011-04-28 00:16:57 +00003250 Dim = Value.getLimitedValue();
John Wiegleyd3522222011-04-28 02:06:46 +00003251 } else {
3252 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
3253 DimExpr->getSourceRange();
3254 return false;
3255 }
John Wiegley6242b6a2011-04-28 00:16:57 +00003256
3257 if (T->isArrayType()) {
3258 unsigned D = 0;
3259 bool Matched = false;
3260 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3261 if (Dim == D) {
3262 Matched = true;
3263 break;
3264 }
3265 ++D;
3266 T = AT->getElementType();
3267 }
3268
John Wiegleyd3522222011-04-28 02:06:46 +00003269 if (Matched && T->isArrayType()) {
3270 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
3271 return CAT->getSize().getLimitedValue();
3272 }
John Wiegley6242b6a2011-04-28 00:16:57 +00003273 }
John Wiegleyd3522222011-04-28 02:06:46 +00003274 return 0;
John Wiegley6242b6a2011-04-28 00:16:57 +00003275 }
3276 }
3277 llvm_unreachable("Unknown type trait or not implemented");
3278}
3279
3280ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
3281 SourceLocation KWLoc,
3282 TypeSourceInfo *TSInfo,
3283 Expr* DimExpr,
3284 SourceLocation RParen) {
3285 QualType T = TSInfo->getType();
John Wiegley6242b6a2011-04-28 00:16:57 +00003286
Chandler Carruthc5276e52011-05-01 08:48:21 +00003287 // FIXME: This should likely be tracked as an APInt to remove any host
3288 // assumptions about the width of size_t on the target.
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00003289 uint64_t Value = 0;
3290 if (!T->isDependentType())
3291 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
3292
Chandler Carruthc5276e52011-05-01 08:48:21 +00003293 // While the specification for these traits from the Embarcadero C++
3294 // compiler's documentation says the return type is 'unsigned int', Clang
3295 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
3296 // compiler, there is no difference. On several other platforms this is an
3297 // important distinction.
John Wiegley6242b6a2011-04-28 00:16:57 +00003298 return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value,
Chandler Carruth9cf632c2011-05-01 07:49:26 +00003299 DimExpr, RParen,
Chandler Carruthc5276e52011-05-01 08:48:21 +00003300 Context.getSizeType()));
John Wiegley6242b6a2011-04-28 00:16:57 +00003301}
3302
John Wiegleyf9f65842011-04-25 06:54:41 +00003303ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003304 SourceLocation KWLoc,
3305 Expr *Queried,
3306 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00003307 // If error parsing the expression, ignore.
3308 if (!Queried)
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003309 return ExprError();
John Wiegleyf9f65842011-04-25 06:54:41 +00003310
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003311 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00003312
3313 return move(Result);
3314}
3315
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003316static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
3317 switch (ET) {
3318 case ET_IsLValueExpr: return E->isLValue();
3319 case ET_IsRValueExpr: return E->isRValue();
3320 }
3321 llvm_unreachable("Expression trait not covered by switch");
3322}
3323
John Wiegleyf9f65842011-04-25 06:54:41 +00003324ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003325 SourceLocation KWLoc,
3326 Expr *Queried,
3327 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00003328 if (Queried->isTypeDependent()) {
3329 // Delay type-checking for type-dependent expressions.
3330 } else if (Queried->getType()->isPlaceholderType()) {
3331 ExprResult PE = CheckPlaceholderExpr(Queried);
3332 if (PE.isInvalid()) return ExprError();
3333 return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen);
3334 }
3335
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003336 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf57eba32011-05-01 08:48:19 +00003337
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003338 return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value,
3339 RParen, Context.BoolTy));
John Wiegleyf9f65842011-04-25 06:54:41 +00003340}
3341
Richard Trieu82402a02011-09-15 21:56:47 +00003342QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCall7decc9e2010-11-18 06:31:45 +00003343 ExprValueKind &VK,
3344 SourceLocation Loc,
3345 bool isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00003346 assert(!LHS.get()->getType()->isPlaceholderType() &&
3347 !RHS.get()->getType()->isPlaceholderType() &&
John McCall0b645e92011-06-30 17:15:34 +00003348 "placeholders should have been weeded out by now");
3349
3350 // The LHS undergoes lvalue conversions if this is ->*.
3351 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00003352 LHS = DefaultLvalueConversion(LHS.take());
3353 if (LHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00003354 }
3355
3356 // The RHS always undergoes lvalue conversions.
Richard Trieu82402a02011-09-15 21:56:47 +00003357 RHS = DefaultLvalueConversion(RHS.take());
3358 if (RHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00003359
Sebastian Redl5822f082009-02-07 20:10:22 +00003360 const char *OpSpelling = isIndirect ? "->*" : ".*";
3361 // C++ 5.5p2
3362 // The binary operator .* [p3: ->*] binds its second operand, which shall
3363 // be of type "pointer to member of T" (where T is a completely-defined
3364 // class type) [...]
Richard Trieu82402a02011-09-15 21:56:47 +00003365 QualType RHSType = RHS.get()->getType();
3366 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00003367 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00003368 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieu82402a02011-09-15 21:56:47 +00003369 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl5822f082009-02-07 20:10:22 +00003370 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00003371 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00003372
Sebastian Redl5822f082009-02-07 20:10:22 +00003373 QualType Class(MemPtr->getClass(), 0);
3374
Douglas Gregord07ba342010-10-13 20:41:14 +00003375 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
3376 // member pointer points must be completely-defined. However, there is no
3377 // reason for this semantic distinction, and the rule is not enforced by
3378 // other compilers. Therefore, we do not check this property, as it is
3379 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00003380
Sebastian Redl5822f082009-02-07 20:10:22 +00003381 // C++ 5.5p2
3382 // [...] to its first operand, which shall be of class T or of a class of
3383 // which T is an unambiguous and accessible base class. [p3: a pointer to
3384 // such a class]
Richard Trieu82402a02011-09-15 21:56:47 +00003385 QualType LHSType = LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00003386 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00003387 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
3388 LHSType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00003389 else {
3390 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieu82402a02011-09-15 21:56:47 +00003391 << OpSpelling << 1 << LHSType
Douglas Gregora771f462010-03-31 17:46:05 +00003392 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00003393 return QualType();
3394 }
3395 }
3396
Richard Trieu82402a02011-09-15 21:56:47 +00003397 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00003398 // If we want to check the hierarchy, we need a complete type.
Richard Trieu82402a02011-09-15 21:56:47 +00003399 if (RequireCompleteType(Loc, LHSType, PDiag(diag::err_bad_memptr_lhs)
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00003400 << OpSpelling << (int)isIndirect)) {
3401 return QualType();
3402 }
Anders Carlssona70cff62010-04-24 19:06:50 +00003403 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00003404 /*DetectVirtual=*/false);
Mike Stump87c57ac2009-05-16 07:39:55 +00003405 // FIXME: Would it be useful to print full ambiguity paths, or is that
3406 // overkill?
Richard Trieu82402a02011-09-15 21:56:47 +00003407 if (!IsDerivedFrom(LHSType, Class, Paths) ||
Sebastian Redl5822f082009-02-07 20:10:22 +00003408 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
3409 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieu82402a02011-09-15 21:56:47 +00003410 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00003411 return QualType();
3412 }
Eli Friedman1fcf66b2010-01-16 00:00:48 +00003413 // Cast LHS to type of use.
3414 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Eli Friedmanbe4b3632011-09-27 21:58:52 +00003415 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003416
John McCallcf142162010-08-07 06:22:56 +00003417 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00003418 BuildBasePathArray(Paths, BasePath);
Richard Trieu82402a02011-09-15 21:56:47 +00003419 LHS = ImpCastExprToType(LHS.take(), UseType, CK_DerivedToBase, VK,
3420 &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00003421 }
3422
Richard Trieu82402a02011-09-15 21:56:47 +00003423 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00003424 // Diagnose use of pointer-to-member type which when used as
3425 // the functional cast in a pointer-to-member expression.
3426 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
3427 return QualType();
3428 }
John McCall7decc9e2010-11-18 06:31:45 +00003429
Sebastian Redl5822f082009-02-07 20:10:22 +00003430 // C++ 5.5p2
3431 // The result is an object or a function of the type specified by the
3432 // second operand.
3433 // The cv qualifiers are the union of those in the pointer and the left side,
3434 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl5822f082009-02-07 20:10:22 +00003435 QualType Result = MemPtr->getPointeeType();
Richard Trieu82402a02011-09-15 21:56:47 +00003436 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00003437
Douglas Gregor1d042092011-01-26 16:40:18 +00003438 // C++0x [expr.mptr.oper]p6:
3439 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003440 // ill-formed if the second operand is a pointer to member function with
3441 // ref-qualifier &. In a ->* expression or in a .* expression whose object
3442 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor1d042092011-01-26 16:40:18 +00003443 // is a pointer to member function with ref-qualifier &&.
3444 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
3445 switch (Proto->getRefQualifier()) {
3446 case RQ_None:
3447 // Do nothing
3448 break;
3449
3450 case RQ_LValue:
Richard Trieu82402a02011-09-15 21:56:47 +00003451 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00003452 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00003453 << RHSType << 1 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00003454 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003455
Douglas Gregor1d042092011-01-26 16:40:18 +00003456 case RQ_RValue:
Richard Trieu82402a02011-09-15 21:56:47 +00003457 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00003458 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00003459 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00003460 break;
3461 }
3462 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003463
John McCall7decc9e2010-11-18 06:31:45 +00003464 // C++ [expr.mptr.oper]p6:
3465 // The result of a .* expression whose second operand is a pointer
3466 // to a data member is of the same value category as its
3467 // first operand. The result of a .* expression whose second
3468 // operand is a pointer to a member function is a prvalue. The
3469 // result of an ->* expression is an lvalue if its second operand
3470 // is a pointer to data member and a prvalue otherwise.
John McCall0009fcc2011-04-26 20:42:42 +00003471 if (Result->isFunctionType()) {
John McCall7decc9e2010-11-18 06:31:45 +00003472 VK = VK_RValue;
John McCall0009fcc2011-04-26 20:42:42 +00003473 return Context.BoundMemberTy;
3474 } else if (isIndirect) {
John McCall7decc9e2010-11-18 06:31:45 +00003475 VK = VK_LValue;
John McCall0009fcc2011-04-26 20:42:42 +00003476 } else {
Richard Trieu82402a02011-09-15 21:56:47 +00003477 VK = LHS.get()->getValueKind();
John McCall0009fcc2011-04-26 20:42:42 +00003478 }
John McCall7decc9e2010-11-18 06:31:45 +00003479
Sebastian Redl5822f082009-02-07 20:10:22 +00003480 return Result;
3481}
Sebastian Redl1a99f442009-04-16 17:51:27 +00003482
Sebastian Redl1a99f442009-04-16 17:51:27 +00003483/// \brief Try to convert a type to another according to C++0x 5.16p3.
3484///
3485/// This is part of the parameter validation for the ? operator. If either
3486/// value operand is a class type, the two operands are attempted to be
3487/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00003488/// It returns true if the program is ill-formed and has already been diagnosed
3489/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003490static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
3491 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00003492 bool &HaveConversion,
3493 QualType &ToType) {
3494 HaveConversion = false;
3495 ToType = To->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003496
3497 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00003498 SourceLocation());
Sebastian Redl1a99f442009-04-16 17:51:27 +00003499 // C++0x 5.16p3
3500 // The process for determining whether an operand expression E1 of type T1
3501 // can be converted to match an operand expression E2 of type T2 is defined
3502 // as follows:
3503 // -- If E2 is an lvalue:
John McCall086a4642010-11-24 05:12:34 +00003504 bool ToIsLvalue = To->isLValue();
Douglas Gregorf9edf802010-03-26 20:59:55 +00003505 if (ToIsLvalue) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003506 // E1 can be converted to match E2 if E1 can be implicitly converted to
3507 // type "lvalue reference to T2", subject to the constraint that in the
3508 // conversion the reference must bind directly to E1.
Douglas Gregor838fcc32010-03-26 20:14:36 +00003509 QualType T = Self.Context.getLValueReferenceType(ToType);
3510 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003511
Douglas Gregor838fcc32010-03-26 20:14:36 +00003512 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3513 if (InitSeq.isDirectReferenceBinding()) {
3514 ToType = T;
3515 HaveConversion = true;
3516 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003517 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003518
Douglas Gregor838fcc32010-03-26 20:14:36 +00003519 if (InitSeq.isAmbiguous())
3520 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003521 }
John McCall65eb8792010-02-25 01:37:24 +00003522
Sebastian Redl1a99f442009-04-16 17:51:27 +00003523 // -- If E2 is an rvalue, or if the conversion above cannot be done:
3524 // -- if E1 and E2 have class type, and the underlying class types are
3525 // the same or one is a base class of the other:
3526 QualType FTy = From->getType();
3527 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003528 const RecordType *FRec = FTy->getAs<RecordType>();
3529 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003530 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Douglas Gregor838fcc32010-03-26 20:14:36 +00003531 Self.IsDerivedFrom(FTy, TTy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003532 if (FRec && TRec &&
Douglas Gregor838fcc32010-03-26 20:14:36 +00003533 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003534 // E1 can be converted to match E2 if the class of T2 is the
3535 // same type as, or a base class of, the class of T1, and
3536 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00003537 if (FRec == TRec || FDerivedFromT) {
3538 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00003539 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3540 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00003541 if (InitSeq) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00003542 HaveConversion = true;
3543 return false;
3544 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003545
Douglas Gregor838fcc32010-03-26 20:14:36 +00003546 if (InitSeq.isAmbiguous())
3547 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003548 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003549 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003550
Douglas Gregor838fcc32010-03-26 20:14:36 +00003551 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003552 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003553
Douglas Gregor838fcc32010-03-26 20:14:36 +00003554 // -- Otherwise: E1 can be converted to match E2 if E1 can be
3555 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003556 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregorf9edf802010-03-26 20:59:55 +00003557 // an rvalue).
3558 //
3559 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
3560 // to the array-to-pointer or function-to-pointer conversions.
3561 if (!TTy->getAs<TagType>())
3562 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003563
Douglas Gregor838fcc32010-03-26 20:14:36 +00003564 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3565 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00003566 HaveConversion = !InitSeq.Failed();
Douglas Gregor838fcc32010-03-26 20:14:36 +00003567 ToType = TTy;
3568 if (InitSeq.isAmbiguous())
3569 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3570
Sebastian Redl1a99f442009-04-16 17:51:27 +00003571 return false;
3572}
3573
3574/// \brief Try to find a common type for two according to C++0x 5.16p5.
3575///
3576/// This is part of the parameter validation for the ? operator. If either
3577/// value operand is a class type, overload resolution is used to find a
3578/// conversion to a common type.
John Wiegley01296292011-04-08 18:41:53 +00003579static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003580 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00003581 Expr *Args[2] = { LHS.get(), RHS.get() };
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003582 OverloadCandidateSet CandidateSet(QuestionLoc);
3583 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
3584 CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003585
3586 OverloadCandidateSet::iterator Best;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003587 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley01296292011-04-08 18:41:53 +00003588 case OR_Success: {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003589 // We found a match. Perform the conversions on the arguments and move on.
John Wiegley01296292011-04-08 18:41:53 +00003590 ExprResult LHSRes =
3591 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
3592 Best->Conversions[0], Sema::AA_Converting);
3593 if (LHSRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00003594 break;
John Wiegley01296292011-04-08 18:41:53 +00003595 LHS = move(LHSRes);
3596
3597 ExprResult RHSRes =
3598 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
3599 Best->Conversions[1], Sema::AA_Converting);
3600 if (RHSRes.isInvalid())
3601 break;
3602 RHS = move(RHSRes);
Chandler Carruth30141632011-02-25 19:41:05 +00003603 if (Best->Function)
3604 Self.MarkDeclarationReferenced(QuestionLoc, Best->Function);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003605 return false;
John Wiegley01296292011-04-08 18:41:53 +00003606 }
3607
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003608 case OR_No_Viable_Function:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003609
3610 // Emit a better diagnostic if one of the expressions is a null pointer
3611 // constant and the other is a pointer type. In this case, the user most
3612 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00003613 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003614 return true;
3615
3616 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00003617 << LHS.get()->getType() << RHS.get()->getType()
3618 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003619 return true;
3620
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003621 case OR_Ambiguous:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003622 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley01296292011-04-08 18:41:53 +00003623 << LHS.get()->getType() << RHS.get()->getType()
3624 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00003625 // FIXME: Print the possible common types by printing the return types of
3626 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003627 break;
3628
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003629 case OR_Deleted:
David Blaikie83d382b2011-09-23 05:06:16 +00003630 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl1a99f442009-04-16 17:51:27 +00003631 }
3632 return true;
3633}
3634
Sebastian Redl5775af1a2009-04-17 16:30:52 +00003635/// \brief Perform an "extended" implicit conversion as returned by
3636/// TryClassUnification.
John Wiegley01296292011-04-08 18:41:53 +00003637static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00003638 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley01296292011-04-08 18:41:53 +00003639 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00003640 SourceLocation());
John Wiegley01296292011-04-08 18:41:53 +00003641 Expr *Arg = E.take();
3642 InitializationSequence InitSeq(Self, Entity, Kind, &Arg, 1);
3643 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&Arg, 1));
Douglas Gregor838fcc32010-03-26 20:14:36 +00003644 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00003645 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003646
John Wiegley01296292011-04-08 18:41:53 +00003647 E = Result;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00003648 return false;
3649}
3650
Sebastian Redl1a99f442009-04-16 17:51:27 +00003651/// \brief Check the operands of ?: under C++ semantics.
3652///
3653/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
3654/// extension. In this case, LHS == Cond. (But they're not aliases.)
John Wiegley01296292011-04-08 18:41:53 +00003655QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCallc07a0c72011-02-17 10:25:35 +00003656 ExprValueKind &VK, ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00003657 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00003658 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
3659 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003660
3661 // C++0x 5.16p1
3662 // The first expression is contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00003663 if (!Cond.get()->isTypeDependent()) {
3664 ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
3665 if (CondRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00003666 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003667 Cond = move(CondRes);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003668 }
3669
John McCall7decc9e2010-11-18 06:31:45 +00003670 // Assume r-value.
3671 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00003672 OK = OK_Ordinary;
John McCall7decc9e2010-11-18 06:31:45 +00003673
Sebastian Redl1a99f442009-04-16 17:51:27 +00003674 // Either of the arguments dependent?
John Wiegley01296292011-04-08 18:41:53 +00003675 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl1a99f442009-04-16 17:51:27 +00003676 return Context.DependentTy;
3677
3678 // C++0x 5.16p2
3679 // If either the second or the third operand has type (cv) void, ...
John Wiegley01296292011-04-08 18:41:53 +00003680 QualType LTy = LHS.get()->getType();
3681 QualType RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003682 bool LVoid = LTy->isVoidType();
3683 bool RVoid = RTy->isVoidType();
3684 if (LVoid || RVoid) {
3685 // ... then the [l2r] conversions are performed on the second and third
3686 // operands ...
John Wiegley01296292011-04-08 18:41:53 +00003687 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3688 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3689 if (LHS.isInvalid() || RHS.isInvalid())
3690 return QualType();
3691 LTy = LHS.get()->getType();
3692 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003693
3694 // ... and one of the following shall hold:
3695 // -- The second or the third operand (but not both) is a throw-
3696 // expression; the result is of the type of the other and is an rvalue.
John Wiegley01296292011-04-08 18:41:53 +00003697 bool LThrow = isa<CXXThrowExpr>(LHS.get());
3698 bool RThrow = isa<CXXThrowExpr>(RHS.get());
Sebastian Redl1a99f442009-04-16 17:51:27 +00003699 if (LThrow && !RThrow)
3700 return RTy;
3701 if (RThrow && !LThrow)
3702 return LTy;
3703
3704 // -- Both the second and third operands have type void; the result is of
3705 // type void and is an rvalue.
3706 if (LVoid && RVoid)
3707 return Context.VoidTy;
3708
3709 // Neither holds, error.
3710 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
3711 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley01296292011-04-08 18:41:53 +00003712 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003713 return QualType();
3714 }
3715
3716 // Neither is void.
3717
3718 // C++0x 5.16p3
3719 // Otherwise, if the second and third operand have different types, and
3720 // either has (cv) class type, and attempt is made to convert each of those
3721 // operands to the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003722 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00003723 (LTy->isRecordType() || RTy->isRecordType())) {
3724 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
3725 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00003726 QualType L2RType, R2LType;
3727 bool HaveL2R, HaveR2L;
John Wiegley01296292011-04-08 18:41:53 +00003728 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00003729 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003730 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00003731 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003732
Sebastian Redl1a99f442009-04-16 17:51:27 +00003733 // If both can be converted, [...] the program is ill-formed.
3734 if (HaveL2R && HaveR2L) {
3735 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley01296292011-04-08 18:41:53 +00003736 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003737 return QualType();
3738 }
3739
3740 // If exactly one conversion is possible, that conversion is applied to
3741 // the chosen operand and the converted operands are used in place of the
3742 // original operands for the remainder of this section.
3743 if (HaveL2R) {
John Wiegley01296292011-04-08 18:41:53 +00003744 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00003745 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003746 LTy = LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003747 } else if (HaveR2L) {
John Wiegley01296292011-04-08 18:41:53 +00003748 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00003749 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003750 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003751 }
3752 }
3753
3754 // C++0x 5.16p4
John McCall7decc9e2010-11-18 06:31:45 +00003755 // If the second and third operands are glvalues of the same value
3756 // category and have the same type, the result is of that type and
3757 // value category and it is a bit-field if the second or the third
3758 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00003759 // We only extend this to bitfields, not to the crazy other kinds of
3760 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00003761 bool Same = Context.hasSameType(LTy, RTy);
John McCall7decc9e2010-11-18 06:31:45 +00003762 if (Same &&
John Wiegley01296292011-04-08 18:41:53 +00003763 LHS.get()->isGLValue() &&
3764 LHS.get()->getValueKind() == RHS.get()->getValueKind() &&
3765 LHS.get()->isOrdinaryOrBitFieldObject() &&
3766 RHS.get()->isOrdinaryOrBitFieldObject()) {
3767 VK = LHS.get()->getValueKind();
3768 if (LHS.get()->getObjectKind() == OK_BitField ||
3769 RHS.get()->getObjectKind() == OK_BitField)
John McCall4bc41ae2010-11-18 19:01:18 +00003770 OK = OK_BitField;
John McCall7decc9e2010-11-18 06:31:45 +00003771 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00003772 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003773
3774 // C++0x 5.16p5
3775 // Otherwise, the result is an rvalue. If the second and third operands
3776 // do not have the same type, and either has (cv) class type, ...
3777 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
3778 // ... overload resolution is used to determine the conversions (if any)
3779 // to be applied to the operands. If the overload resolution fails, the
3780 // program is ill-formed.
3781 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
3782 return QualType();
3783 }
3784
3785 // C++0x 5.16p6
3786 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
3787 // conversions are performed on the second and third operands.
John Wiegley01296292011-04-08 18:41:53 +00003788 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3789 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3790 if (LHS.isInvalid() || RHS.isInvalid())
3791 return QualType();
3792 LTy = LHS.get()->getType();
3793 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003794
3795 // After those conversions, one of the following shall hold:
3796 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00003797 // is of that type. If the operands have class type, the result
3798 // is a prvalue temporary of the result type, which is
3799 // copy-initialized from either the second operand or the third
3800 // operand depending on the value of the first operand.
3801 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
3802 if (LTy->isRecordType()) {
3803 // The operands have class type. Make a temporary copy.
3804 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003805 ExprResult LHSCopy = PerformCopyInitialization(Entity,
3806 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00003807 LHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00003808 if (LHSCopy.isInvalid())
3809 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003810
3811 ExprResult RHSCopy = PerformCopyInitialization(Entity,
3812 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00003813 RHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00003814 if (RHSCopy.isInvalid())
3815 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003816
John Wiegley01296292011-04-08 18:41:53 +00003817 LHS = LHSCopy;
3818 RHS = RHSCopy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00003819 }
3820
Sebastian Redl1a99f442009-04-16 17:51:27 +00003821 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00003822 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003823
Douglas Gregor46188682010-05-18 22:42:18 +00003824 // Extension: conditional operator involving vector types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003825 if (LTy->isVectorType() || RTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00003826 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor46188682010-05-18 22:42:18 +00003827
Sebastian Redl1a99f442009-04-16 17:51:27 +00003828 // -- The second and third operands have arithmetic or enumeration type;
3829 // the usual arithmetic conversions are performed to bring them to a
3830 // common type, and the result is of that type.
3831 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
3832 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00003833 if (LHS.isInvalid() || RHS.isInvalid())
3834 return QualType();
3835 return LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003836 }
3837
3838 // -- The second and third operands have pointer type, or one has pointer
3839 // type and the other is a null pointer constant; pointer conversions
3840 // and qualification conversions are performed to bring them to their
3841 // composite pointer type. The result is of the composite pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00003842 // -- The second and third operands have pointer to member type, or one has
3843 // pointer to member type and the other is a null pointer constant;
3844 // pointer to member conversions and qualification conversions are
3845 // performed to bring them to a common type, whose cv-qualification
3846 // shall match the cv-qualification of either the second or the third
3847 // operand. The result is of the common type.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003848 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00003849 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003850 isSFINAEContext()? 0 : &NonStandardCompositeType);
3851 if (!Composite.isNull()) {
3852 if (NonStandardCompositeType)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003853 Diag(QuestionLoc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003854 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
3855 << LTy << RTy << Composite
John Wiegley01296292011-04-08 18:41:53 +00003856 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003857
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003858 return Composite;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003859 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003860
Douglas Gregor697a3912010-04-01 22:47:07 +00003861 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00003862 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
3863 if (!Composite.isNull())
3864 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003865
Chandler Carruth9c9127e2011-02-19 00:13:59 +00003866 // Check if we are using a null with a non-pointer type.
John Wiegley01296292011-04-08 18:41:53 +00003867 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth9c9127e2011-02-19 00:13:59 +00003868 return QualType();
3869
Sebastian Redl1a99f442009-04-16 17:51:27 +00003870 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00003871 << LHS.get()->getType() << RHS.get()->getType()
3872 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003873 return QualType();
3874}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003875
3876/// \brief Find a merged pointer type and convert the two expressions to it.
3877///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003878/// This finds the composite pointer type (or member pointer type) for @p E1
3879/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
3880/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003881/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003882///
Douglas Gregor19175ff2010-04-16 23:20:25 +00003883/// \param Loc The location of the operator requiring these two expressions to
3884/// be converted to the composite pointer type.
3885///
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003886/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
3887/// a non-standard (but still sane) composite type to which both expressions
3888/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
3889/// will be set true.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003890QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor19175ff2010-04-16 23:20:25 +00003891 Expr *&E1, Expr *&E2,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003892 bool *NonStandardCompositeType) {
3893 if (NonStandardCompositeType)
3894 *NonStandardCompositeType = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003895
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003896 assert(getLangOptions().CPlusPlus && "This function assumes C++");
3897 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003898
Fariborz Jahanian33e148f2009-12-08 20:04:24 +00003899 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
3900 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003901 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003902
3903 // C++0x 5.9p2
3904 // Pointer conversions and qualification conversions are performed on
3905 // pointer operands to bring them to their composite pointer type. If
3906 // one operand is a null pointer constant, the composite pointer type is
3907 // the type of the other operand.
Douglas Gregor56751b52009-09-25 04:25:58 +00003908 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003909 if (T2->isMemberPointerType())
John Wiegley01296292011-04-08 18:41:53 +00003910 E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003911 else
John Wiegley01296292011-04-08 18:41:53 +00003912 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003913 return T2;
3914 }
Douglas Gregor56751b52009-09-25 04:25:58 +00003915 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003916 if (T1->isMemberPointerType())
John Wiegley01296292011-04-08 18:41:53 +00003917 E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003918 else
John Wiegley01296292011-04-08 18:41:53 +00003919 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003920 return T1;
3921 }
Mike Stump11289f42009-09-09 15:08:12 +00003922
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003923 // Now both have to be pointers or member pointers.
Sebastian Redl658262f2009-11-16 21:03:45 +00003924 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
3925 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003926 return QualType();
3927
3928 // Otherwise, of one of the operands has type "pointer to cv1 void," then
3929 // the other has type "pointer to cv2 T" and the composite pointer type is
3930 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
3931 // Otherwise, the composite pointer type is a pointer type similar to the
3932 // type of one of the operands, with a cv-qualification signature that is
3933 // the union of the cv-qualification signatures of the operand types.
3934 // In practice, the first part here is redundant; it's subsumed by the second.
3935 // What we do here is, we build the two possible composite types, and try the
3936 // conversions in both directions. If only one works, or if the two composite
3937 // types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00003938 // FIXME: extended qualifiers?
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003939 typedef SmallVector<unsigned, 4> QualifierVector;
Sebastian Redl658262f2009-11-16 21:03:45 +00003940 QualifierVector QualifierUnion;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003941 typedef SmallVector<std::pair<const Type *, const Type *>, 4>
Sebastian Redl658262f2009-11-16 21:03:45 +00003942 ContainingClassVector;
3943 ContainingClassVector MemberOfClass;
3944 QualType Composite1 = Context.getCanonicalType(T1),
3945 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003946 unsigned NeedConstBefore = 0;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003947 do {
3948 const PointerType *Ptr1, *Ptr2;
3949 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3950 (Ptr2 = Composite2->getAs<PointerType>())) {
3951 Composite1 = Ptr1->getPointeeType();
3952 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003953
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003954 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003955 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003956 if (NonStandardCompositeType &&
3957 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3958 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003959
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003960 QualifierUnion.push_back(
3961 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3962 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3963 continue;
3964 }
Mike Stump11289f42009-09-09 15:08:12 +00003965
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003966 const MemberPointerType *MemPtr1, *MemPtr2;
3967 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3968 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3969 Composite1 = MemPtr1->getPointeeType();
3970 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003971
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003972 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003973 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003974 if (NonStandardCompositeType &&
3975 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3976 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003977
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003978 QualifierUnion.push_back(
3979 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3980 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
3981 MemPtr2->getClass()));
3982 continue;
3983 }
Mike Stump11289f42009-09-09 15:08:12 +00003984
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003985 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00003986
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003987 // Cannot unwrap any more types.
3988 break;
3989 } while (true);
Mike Stump11289f42009-09-09 15:08:12 +00003990
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003991 if (NeedConstBefore && NonStandardCompositeType) {
3992 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003993 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003994 // requirements of C++ [conv.qual]p4 bullet 3.
3995 for (unsigned I = 0; I != NeedConstBefore; ++I) {
3996 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
3997 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
3998 *NonStandardCompositeType = true;
3999 }
4000 }
4001 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004002
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004003 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redl658262f2009-11-16 21:03:45 +00004004 ContainingClassVector::reverse_iterator MOC
4005 = MemberOfClass.rbegin();
4006 for (QualifierVector::reverse_iterator
4007 I = QualifierUnion.rbegin(),
4008 E = QualifierUnion.rend();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004009 I != E; (void)++I, ++MOC) {
John McCall8ccfcb52009-09-24 19:53:00 +00004010 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004011 if (MOC->first && MOC->second) {
4012 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00004013 Composite1 = Context.getMemberPointerType(
4014 Context.getQualifiedType(Composite1, Quals),
4015 MOC->first);
4016 Composite2 = Context.getMemberPointerType(
4017 Context.getQualifiedType(Composite2, Quals),
4018 MOC->second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004019 } else {
4020 // Rebuild pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00004021 Composite1
4022 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
4023 Composite2
4024 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004025 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004026 }
4027
Douglas Gregor19175ff2010-04-16 23:20:25 +00004028 // Try to convert to the first composite pointer type.
4029 InitializedEntity Entity1
4030 = InitializedEntity::InitializeTemporary(Composite1);
4031 InitializationKind Kind
4032 = InitializationKind::CreateCopy(Loc, SourceLocation());
4033 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
4034 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump11289f42009-09-09 15:08:12 +00004035
Douglas Gregor19175ff2010-04-16 23:20:25 +00004036 if (E1ToC1 && E2ToC1) {
4037 // Conversion to Composite1 is viable.
4038 if (!Context.hasSameType(Composite1, Composite2)) {
4039 // Composite2 is a different type from Composite1. Check whether
4040 // Composite2 is also viable.
4041 InitializedEntity Entity2
4042 = InitializedEntity::InitializeTemporary(Composite2);
4043 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4044 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4045 if (E1ToC2 && E2ToC2) {
4046 // Both Composite1 and Composite2 are viable and are different;
4047 // this is an ambiguity.
4048 return QualType();
4049 }
4050 }
4051
4052 // Convert E1 to Composite1
John McCalldadc5752010-08-24 06:29:42 +00004053 ExprResult E1Result
John McCall37ad5512010-08-23 06:44:23 +00004054 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00004055 if (E1Result.isInvalid())
4056 return QualType();
4057 E1 = E1Result.takeAs<Expr>();
4058
4059 // Convert E2 to Composite1
John McCalldadc5752010-08-24 06:29:42 +00004060 ExprResult E2Result
John McCall37ad5512010-08-23 06:44:23 +00004061 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00004062 if (E2Result.isInvalid())
4063 return QualType();
4064 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004065
Douglas Gregor19175ff2010-04-16 23:20:25 +00004066 return Composite1;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004067 }
4068
Douglas Gregor19175ff2010-04-16 23:20:25 +00004069 // Check whether Composite2 is viable.
4070 InitializedEntity Entity2
4071 = InitializedEntity::InitializeTemporary(Composite2);
4072 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4073 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4074 if (!E1ToC2 || !E2ToC2)
4075 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004076
Douglas Gregor19175ff2010-04-16 23:20:25 +00004077 // Convert E1 to Composite2
John McCalldadc5752010-08-24 06:29:42 +00004078 ExprResult E1Result
John McCall37ad5512010-08-23 06:44:23 +00004079 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00004080 if (E1Result.isInvalid())
4081 return QualType();
4082 E1 = E1Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004083
Douglas Gregor19175ff2010-04-16 23:20:25 +00004084 // Convert E2 to Composite2
John McCalldadc5752010-08-24 06:29:42 +00004085 ExprResult E2Result
John McCall37ad5512010-08-23 06:44:23 +00004086 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00004087 if (E2Result.isInvalid())
4088 return QualType();
4089 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004090
Douglas Gregor19175ff2010-04-16 23:20:25 +00004091 return Composite2;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004092}
Anders Carlsson85a307d2009-05-17 18:41:29 +00004093
John McCalldadc5752010-08-24 06:29:42 +00004094ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00004095 if (!E)
4096 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004097
John McCall31168b02011-06-15 23:02:42 +00004098 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
4099
4100 // If the result is a glvalue, we shouldn't bind it.
4101 if (!E->isRValue())
Anders Carlssonf86a8d12009-08-15 23:41:35 +00004102 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00004103
John McCall31168b02011-06-15 23:02:42 +00004104 // In ARC, calls that return a retainable type can return retained,
4105 // in which case we have to insert a consuming cast.
4106 if (getLangOptions().ObjCAutoRefCount &&
4107 E->getType()->isObjCRetainableType()) {
4108
4109 bool ReturnsRetained;
4110
4111 // For actual calls, we compute this by examining the type of the
4112 // called value.
4113 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
4114 Expr *Callee = Call->getCallee()->IgnoreParens();
4115 QualType T = Callee->getType();
4116
4117 if (T == Context.BoundMemberTy) {
4118 // Handle pointer-to-members.
4119 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
4120 T = BinOp->getRHS()->getType();
4121 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
4122 T = Mem->getMemberDecl()->getType();
4123 }
4124
4125 if (const PointerType *Ptr = T->getAs<PointerType>())
4126 T = Ptr->getPointeeType();
4127 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
4128 T = Ptr->getPointeeType();
4129 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
4130 T = MemPtr->getPointeeType();
4131
4132 const FunctionType *FTy = T->getAs<FunctionType>();
4133 assert(FTy && "call to value not of function type?");
4134 ReturnsRetained = FTy->getExtInfo().getProducesResult();
4135
4136 // ActOnStmtExpr arranges things so that StmtExprs of retainable
4137 // type always produce a +1 object.
4138 } else if (isa<StmtExpr>(E)) {
4139 ReturnsRetained = true;
4140
4141 // For message sends and property references, we try to find an
4142 // actual method. FIXME: we should infer retention by selector in
4143 // cases where we don't have an actual method.
4144 } else {
John McCall32a4da02011-08-03 07:02:44 +00004145 ObjCMethodDecl *D = 0;
John McCall31168b02011-06-15 23:02:42 +00004146 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
4147 D = Send->getMethodDecl();
John McCall31168b02011-06-15 23:02:42 +00004148 }
4149
4150 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCall32a4da02011-08-03 07:02:44 +00004151
4152 // Don't do reclaims on performSelector calls; despite their
4153 // return type, the invoked method doesn't necessarily actually
4154 // return an object.
4155 if (!ReturnsRetained &&
4156 D && D->getMethodFamily() == OMF_performSelector)
4157 return Owned(E);
John McCall31168b02011-06-15 23:02:42 +00004158 }
4159
John McCall16de4d22011-11-14 19:53:16 +00004160 // Don't reclaim an object of Class type.
4161 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
4162 return Owned(E);
4163
John McCall4db5c3c2011-07-07 06:58:02 +00004164 ExprNeedsCleanups = true;
4165
John McCall2d637d22011-09-10 06:18:15 +00004166 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
4167 : CK_ARCReclaimReturnedObject);
John McCall4db5c3c2011-07-07 06:58:02 +00004168 return Owned(ImplicitCastExpr::Create(Context, E->getType(), ck, E, 0,
4169 VK_RValue));
John McCall31168b02011-06-15 23:02:42 +00004170 }
4171
4172 if (!getLangOptions().CPlusPlus)
4173 return Owned(E);
Douglas Gregor363b1512009-12-24 18:51:59 +00004174
Peter Collingbournefbef4c82011-11-27 22:09:28 +00004175 QualType ET = Context.getBaseElementType(E->getType());
4176 const RecordType *RT = ET->getAs<RecordType>();
Anders Carlsson2d4cada2009-05-30 20:36:53 +00004177 if (!RT)
4178 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00004179
John McCall67da35c2010-02-04 22:26:26 +00004180 // That should be enough to guarantee that this type is complete.
4181 // If it has a trivial destructor, we can avoid the extra copy.
Jeffrey Yasskinbbc4eea2011-01-27 19:17:54 +00004182 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCallbdb989e2010-08-12 02:40:37 +00004183 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall67da35c2010-02-04 22:26:26 +00004184 return Owned(E);
4185
John McCall31168b02011-06-15 23:02:42 +00004186 CXXDestructorDecl *Destructor = LookupDestructor(RD);
4187
4188 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
4189 if (Destructor) {
Fariborz Jahanian67828442009-08-03 19:13:25 +00004190 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00004191 CheckDestructorAccess(E->getExprLoc(), Destructor,
4192 PDiag(diag::err_access_dtor_temp)
4193 << E->getType());
John McCall31168b02011-06-15 23:02:42 +00004194
John McCall28fc7092011-11-10 05:35:25 +00004195 // We need a cleanup, but we don't need to remember the temporary.
John McCall31168b02011-06-15 23:02:42 +00004196 ExprNeedsCleanups = true;
John McCall8e36d532010-04-07 00:41:46 +00004197 }
Anders Carlsson2d4cada2009-05-30 20:36:53 +00004198 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
4199}
4200
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004201ExprResult
John McCall5d413782010-12-06 08:20:24 +00004202Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004203 if (SubExpr.isInvalid())
4204 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004205
John McCall5d413782010-12-06 08:20:24 +00004206 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004207}
4208
John McCall28fc7092011-11-10 05:35:25 +00004209Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
4210 assert(SubExpr && "sub expression can't be null!");
4211
4212 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
4213 assert(ExprCleanupObjects.size() >= FirstCleanup);
4214 assert(ExprNeedsCleanups || ExprCleanupObjects.size() == FirstCleanup);
4215 if (!ExprNeedsCleanups)
4216 return SubExpr;
4217
4218 ArrayRef<ExprWithCleanups::CleanupObject> Cleanups
4219 = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
4220 ExprCleanupObjects.size() - FirstCleanup);
4221
4222 Expr *E = ExprWithCleanups::Create(Context, SubExpr, Cleanups);
4223 DiscardCleanupsInEvaluationContext();
4224
4225 return E;
4226}
4227
John McCall5d413782010-12-06 08:20:24 +00004228Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00004229 assert(SubStmt && "sub statement can't be null!");
4230
John McCall31168b02011-06-15 23:02:42 +00004231 if (!ExprNeedsCleanups)
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00004232 return SubStmt;
4233
4234 // FIXME: In order to attach the temporaries, wrap the statement into
4235 // a StmtExpr; currently this is only used for asm statements.
4236 // This is hacky, either create a new CXXStmtWithTemporaries statement or
4237 // a new AsmStmtWithTemporaries.
4238 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
4239 SourceLocation(),
4240 SourceLocation());
4241 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
4242 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00004243 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00004244}
4245
John McCalldadc5752010-08-24 06:29:42 +00004246ExprResult
John McCallb268a282010-08-23 23:25:46 +00004247Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallba7bf592010-08-24 05:47:05 +00004248 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregore610ada2010-02-24 18:44:31 +00004249 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004250 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004251 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00004252 if (Result.isInvalid()) return ExprError();
4253 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00004254
John McCall526ab472011-10-25 17:37:35 +00004255 Result = CheckPlaceholderExpr(Base);
4256 if (Result.isInvalid()) return ExprError();
4257 Base = Result.take();
4258
John McCallb268a282010-08-23 23:25:46 +00004259 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00004260 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004261 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00004262 // If we have a pointer to a dependent type and are using the -> operator,
4263 // the object type is the type that the pointer points to. We might still
4264 // have enough information about that type to do something useful.
4265 if (OpKind == tok::arrow)
4266 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4267 BaseType = Ptr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004268
John McCallba7bf592010-08-24 05:47:05 +00004269 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00004270 MayBePseudoDestructor = true;
John McCallb268a282010-08-23 23:25:46 +00004271 return Owned(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004272 }
Mike Stump11289f42009-09-09 15:08:12 +00004273
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004274 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00004275 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004276 // returned, with the original second operand.
4277 if (OpKind == tok::arrow) {
John McCallc1538c02009-09-30 01:01:30 +00004278 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00004279 llvm::SmallPtrSet<CanQualType,8> CTypes;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004280 SmallVector<SourceLocation, 8> Locations;
John McCallbd0465b2009-09-30 01:30:54 +00004281 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004282
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004283 while (BaseType->isRecordType()) {
John McCallb268a282010-08-23 23:25:46 +00004284 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
4285 if (Result.isInvalid())
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004286 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00004287 Base = Result.get();
4288 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonfbd2d492009-10-13 22:55:59 +00004289 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallb268a282010-08-23 23:25:46 +00004290 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00004291 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCallbd0465b2009-09-30 01:30:54 +00004292 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00004293 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00004294 for (unsigned i = 0; i < Locations.size(); i++)
4295 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00004296 return ExprError();
4297 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004298 }
Mike Stump11289f42009-09-09 15:08:12 +00004299
Douglas Gregorbf3a8262012-01-12 16:11:24 +00004300 if (BaseType->isPointerType() || BaseType->isObjCObjectPointerType())
Douglas Gregore4f764f2009-11-20 19:58:21 +00004301 BaseType = BaseType->getPointeeType();
4302 }
Mike Stump11289f42009-09-09 15:08:12 +00004303
Douglas Gregorbf3a8262012-01-12 16:11:24 +00004304 // Objective-C properties allow "." access on Objective-C pointer types,
4305 // so adjust the base type to the object type itself.
4306 if (BaseType->isObjCObjectPointerType())
4307 BaseType = BaseType->getPointeeType();
4308
4309 // C++ [basic.lookup.classref]p2:
4310 // [...] If the type of the object expression is of pointer to scalar
4311 // type, the unqualified-id is looked up in the context of the complete
4312 // postfix-expression.
4313 //
4314 // This also indicates that we could be parsing a pseudo-destructor-name.
4315 // Note that Objective-C class and object types can be pseudo-destructor
4316 // expressions or normal member (ivar or property) access expressions.
4317 if (BaseType->isObjCObjectOrInterfaceType()) {
4318 MayBePseudoDestructor = true;
4319 } else if (!BaseType->isRecordType()) {
John McCallba7bf592010-08-24 05:47:05 +00004320 ObjectType = ParsedType();
Douglas Gregore610ada2010-02-24 18:44:31 +00004321 MayBePseudoDestructor = true;
John McCallb268a282010-08-23 23:25:46 +00004322 return Owned(Base);
Douglas Gregor2b6ca462009-09-03 21:38:09 +00004323 }
Mike Stump11289f42009-09-09 15:08:12 +00004324
Douglas Gregor3fad6172009-11-17 05:17:33 +00004325 // The object type must be complete (or dependent).
4326 if (!BaseType->isDependentType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004327 RequireCompleteType(OpLoc, BaseType,
Douglas Gregor3fad6172009-11-17 05:17:33 +00004328 PDiag(diag::err_incomplete_member_access)))
4329 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004330
Douglas Gregor2b6ca462009-09-03 21:38:09 +00004331 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004332 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00004333 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00004334 // type C (or of pointer to a class type C), the unqualified-id is looked
4335 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00004336 ObjectType = ParsedType::make(BaseType);
Mike Stump11289f42009-09-09 15:08:12 +00004337 return move(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004338}
4339
John McCalldadc5752010-08-24 06:29:42 +00004340ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCallb268a282010-08-23 23:25:46 +00004341 Expr *MemExpr) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004342 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCallb268a282010-08-23 23:25:46 +00004343 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
4344 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregora771f462010-03-31 17:46:05 +00004345 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004346
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004347 return ActOnCallExpr(/*Scope*/ 0,
John McCallb268a282010-08-23 23:25:46 +00004348 MemExpr,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004349 /*LPLoc*/ ExpectedLParenLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00004350 MultiExprArg(),
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004351 /*RPLoc*/ ExpectedLParenLoc);
4352}
Douglas Gregore610ada2010-02-24 18:44:31 +00004353
David Blaikie1d578782011-12-16 16:03:09 +00004354static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *Base,
4355 tok::TokenKind& OpKind, SourceLocation OpLoc) {
4356 // C++ [expr.pseudo]p2:
4357 // The left-hand side of the dot operator shall be of scalar type. The
4358 // left-hand side of the arrow operator shall be of pointer to scalar type.
4359 // This scalar type is the object type.
4360 if (OpKind == tok::arrow) {
4361 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4362 ObjectType = Ptr->getPointeeType();
4363 } else if (!Base->isTypeDependent()) {
4364 // The user wrote "p->" when she probably meant "p."; fix it.
4365 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4366 << ObjectType << true
4367 << FixItHint::CreateReplacement(OpLoc, ".");
4368 if (S.isSFINAEContext())
4369 return true;
4370
4371 OpKind = tok::period;
4372 }
4373 }
4374
4375 return false;
4376}
4377
John McCalldadc5752010-08-24 06:29:42 +00004378ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00004379 SourceLocation OpLoc,
4380 tok::TokenKind OpKind,
4381 const CXXScopeSpec &SS,
4382 TypeSourceInfo *ScopeTypeInfo,
4383 SourceLocation CCLoc,
4384 SourceLocation TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00004385 PseudoDestructorTypeStorage Destructed,
John McCalla2c4e722011-02-25 05:21:17 +00004386 bool HasTrailingLParen) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00004387 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004388
John McCallb268a282010-08-23 23:25:46 +00004389 QualType ObjectType = Base->getType();
David Blaikie1d578782011-12-16 16:03:09 +00004390 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4391 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004392
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004393 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
4394 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
John McCallb268a282010-08-23 23:25:46 +00004395 << ObjectType << Base->getSourceRange();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004396 return ExprError();
4397 }
4398
4399 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004400 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004401 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00004402 if (DestructedTypeInfo) {
4403 QualType DestructedType = DestructedTypeInfo->getType();
4404 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00004405 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCall31168b02011-06-15 23:02:42 +00004406 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
4407 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
4408 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
4409 << ObjectType << DestructedType << Base->getSourceRange()
4410 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004411
John McCall31168b02011-06-15 23:02:42 +00004412 // Recover by setting the destructed type to the object type.
4413 DestructedType = ObjectType;
4414 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
Douglas Gregor678f90d2010-02-25 01:56:36 +00004415 DestructedTypeStart);
John McCall31168b02011-06-15 23:02:42 +00004416 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4417 } else if (DestructedType.getObjCLifetime() !=
4418 ObjectType.getObjCLifetime()) {
4419
4420 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
4421 // Okay: just pretend that the user provided the correctly-qualified
4422 // type.
4423 } else {
4424 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
4425 << ObjectType << DestructedType << Base->getSourceRange()
4426 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
4427 }
4428
4429 // Recover by setting the destructed type to the object type.
4430 DestructedType = ObjectType;
4431 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
4432 DestructedTypeStart);
4433 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4434 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00004435 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004436 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004437
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004438 // C++ [expr.pseudo]p2:
4439 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
4440 // form
4441 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004442 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004443 //
4444 // shall designate the same scalar type.
4445 if (ScopeTypeInfo) {
4446 QualType ScopeType = ScopeTypeInfo->getType();
4447 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00004448 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004449
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00004450 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004451 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00004452 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00004453 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004454
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004455 ScopeType = QualType();
4456 ScopeTypeInfo = 0;
4457 }
4458 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004459
John McCallb268a282010-08-23 23:25:46 +00004460 Expr *Result
4461 = new (Context) CXXPseudoDestructorExpr(Context, Base,
4462 OpKind == tok::arrow, OpLoc,
Douglas Gregora6ce6082011-02-25 18:19:59 +00004463 SS.getWithLocInContext(Context),
John McCallb268a282010-08-23 23:25:46 +00004464 ScopeTypeInfo,
4465 CCLoc,
4466 TildeLoc,
4467 Destructed);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004468
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004469 if (HasTrailingLParen)
John McCallb268a282010-08-23 23:25:46 +00004470 return Owned(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004471
John McCallb268a282010-08-23 23:25:46 +00004472 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004473}
4474
John McCalldadc5752010-08-24 06:29:42 +00004475ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00004476 SourceLocation OpLoc,
4477 tok::TokenKind OpKind,
4478 CXXScopeSpec &SS,
4479 UnqualifiedId &FirstTypeName,
4480 SourceLocation CCLoc,
4481 SourceLocation TildeLoc,
4482 UnqualifiedId &SecondTypeName,
4483 bool HasTrailingLParen) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004484 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4485 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4486 "Invalid first type name in pseudo-destructor");
4487 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4488 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4489 "Invalid second type name in pseudo-destructor");
4490
John McCallb268a282010-08-23 23:25:46 +00004491 QualType ObjectType = Base->getType();
David Blaikie1d578782011-12-16 16:03:09 +00004492 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4493 return ExprError();
Douglas Gregor678f90d2010-02-25 01:56:36 +00004494
4495 // Compute the object type that we should use for name lookup purposes. Only
4496 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00004497 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00004498 if (!SS.isSet()) {
John McCalla2c4e722011-02-25 05:21:17 +00004499 if (ObjectType->isRecordType())
4500 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallba7bf592010-08-24 05:47:05 +00004501 else if (ObjectType->isDependentType())
4502 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00004503 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004504
4505 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004506 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004507 QualType DestructedType;
4508 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregor678f90d2010-02-25 01:56:36 +00004509 PseudoDestructorTypeStorage Destructed;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004510 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004511 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00004512 SecondTypeName.StartLocation,
Fariborz Jahanian87967422011-02-08 18:05:59 +00004513 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004514 if (!T &&
Douglas Gregor678f90d2010-02-25 01:56:36 +00004515 ((SS.isSet() && !computeDeclContext(SS, false)) ||
4516 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004517 // The name of the type being destroyed is a dependent name, and we
Douglas Gregor678f90d2010-02-25 01:56:36 +00004518 // couldn't find anything useful in scope. Just store the identifier and
4519 // it's location, and we'll perform (qualified) name lookup again at
4520 // template instantiation time.
4521 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
4522 SecondTypeName.StartLocation);
4523 } else if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004524 Diag(SecondTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004525 diag::err_pseudo_dtor_destructor_non_type)
4526 << SecondTypeName.Identifier << ObjectType;
4527 if (isSFINAEContext())
4528 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004529
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004530 // Recover by assuming we had the right type all along.
4531 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004532 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004533 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004534 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004535 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004536 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004537 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4538 TemplateId->getTemplateArgs(),
4539 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00004540 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4541 TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004542 TemplateId->TemplateNameLoc,
4543 TemplateId->LAngleLoc,
4544 TemplateArgsPtr,
4545 TemplateId->RAngleLoc);
4546 if (T.isInvalid() || !T.get()) {
4547 // Recover by assuming we had the right type all along.
4548 DestructedType = ObjectType;
4549 } else
4550 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004551 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004552
4553 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004554 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00004555 if (!DestructedType.isNull()) {
4556 if (!DestructedTypeInfo)
4557 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004558 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00004559 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4560 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004561
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004562 // Convert the name of the scope type (the type prior to '::') into a type.
4563 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004564 QualType ScopeType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004565 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004566 FirstTypeName.Identifier) {
4567 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004568 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00004569 FirstTypeName.StartLocation,
Douglas Gregora6ce6082011-02-25 18:19:59 +00004570 S, &SS, true, false, ObjectTypePtrForLookup);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004571 if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004572 Diag(FirstTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004573 diag::err_pseudo_dtor_destructor_non_type)
4574 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004575
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004576 if (isSFINAEContext())
4577 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004578
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004579 // Just drop this type. It's unnecessary anyway.
4580 ScopeType = QualType();
4581 } else
4582 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004583 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004584 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004585 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004586 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4587 TemplateId->getTemplateArgs(),
4588 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00004589 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4590 TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004591 TemplateId->TemplateNameLoc,
4592 TemplateId->LAngleLoc,
4593 TemplateArgsPtr,
4594 TemplateId->RAngleLoc);
4595 if (T.isInvalid() || !T.get()) {
4596 // Recover by dropping this type.
4597 ScopeType = QualType();
4598 } else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004599 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004600 }
4601 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004602
Douglas Gregor90ad9222010-02-24 23:02:30 +00004603 if (!ScopeType.isNull() && !ScopeTypeInfo)
4604 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
4605 FirstTypeName.StartLocation);
4606
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004607
John McCallb268a282010-08-23 23:25:46 +00004608 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00004609 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00004610 Destructed, HasTrailingLParen);
Douglas Gregore610ada2010-02-24 18:44:31 +00004611}
4612
David Blaikie1d578782011-12-16 16:03:09 +00004613ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4614 SourceLocation OpLoc,
4615 tok::TokenKind OpKind,
4616 SourceLocation TildeLoc,
4617 const DeclSpec& DS,
4618 bool HasTrailingLParen) {
4619
4620 QualType ObjectType = Base->getType();
4621 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4622 return ExprError();
4623
4624 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
4625
4626 TypeLocBuilder TLB;
4627 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
4628 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
4629 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
4630 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
4631
4632 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
4633 0, SourceLocation(), TildeLoc,
4634 Destructed, HasTrailingLParen);
4635}
4636
John Wiegley01296292011-04-08 18:41:53 +00004637ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004638 CXXMethodDecl *Method,
4639 bool HadMultipleCandidates) {
John Wiegley01296292011-04-08 18:41:53 +00004640 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
4641 FoundDecl, Method);
4642 if (Exp.isInvalid())
Douglas Gregor668443e2011-01-20 00:18:04 +00004643 return true;
Eli Friedmanf7195532009-12-09 04:53:56 +00004644
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004645 MemberExpr *ME =
John Wiegley01296292011-04-08 18:41:53 +00004646 new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00004647 SourceLocation(), Context.BoundMemberTy,
John McCall7decc9e2010-11-18 06:31:45 +00004648 VK_RValue, OK_Ordinary);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004649 if (HadMultipleCandidates)
4650 ME->setHadMultipleCandidates(true);
4651
John McCall7decc9e2010-11-18 06:31:45 +00004652 QualType ResultType = Method->getResultType();
4653 ExprValueKind VK = Expr::getValueKindForType(ResultType);
4654 ResultType = ResultType.getNonLValueExprType(Context);
4655
John Wiegley01296292011-04-08 18:41:53 +00004656 MarkDeclarationReferenced(Exp.get()->getLocStart(), Method);
Douglas Gregor27381f32009-11-23 12:27:39 +00004657 CXXMemberCallExpr *CE =
John McCall7decc9e2010-11-18 06:31:45 +00004658 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
John Wiegley01296292011-04-08 18:41:53 +00004659 Exp.get()->getLocEnd());
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00004660 return CE;
4661}
4662
Sebastian Redl4202c0f2010-09-10 20:55:43 +00004663ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4664 SourceLocation RParen) {
Sebastian Redl4202c0f2010-09-10 20:55:43 +00004665 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
4666 Operand->CanThrow(Context),
4667 KeyLoc, RParen));
4668}
4669
4670ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
4671 Expr *Operand, SourceLocation RParen) {
4672 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00004673}
4674
John McCall34376a62010-12-04 03:47:34 +00004675/// Perform the conversions required for an expression used in a
4676/// context that ignores the result.
John Wiegley01296292011-04-08 18:41:53 +00004677ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall526ab472011-10-25 17:37:35 +00004678 if (E->hasPlaceholderType()) {
4679 ExprResult result = CheckPlaceholderExpr(E);
4680 if (result.isInvalid()) return Owned(E);
4681 E = result.take();
4682 }
4683
John McCallfee942d2010-12-02 02:07:15 +00004684 // C99 6.3.2.1:
4685 // [Except in specific positions,] an lvalue that does not have
4686 // array type is converted to the value stored in the
4687 // designated object (and is no longer an lvalue).
John McCalld68b2d02011-06-27 21:24:11 +00004688 if (E->isRValue()) {
4689 // In C, function designators (i.e. expressions of function type)
4690 // are r-values, but we still want to do function-to-pointer decay
4691 // on them. This is both technically correct and convenient for
4692 // some clients.
4693 if (!getLangOptions().CPlusPlus && E->getType()->isFunctionType())
4694 return DefaultFunctionArrayConversion(E);
4695
4696 return Owned(E);
4697 }
John McCallfee942d2010-12-02 02:07:15 +00004698
John McCall34376a62010-12-04 03:47:34 +00004699 // Otherwise, this rule does not apply in C++, at least not for the moment.
John Wiegley01296292011-04-08 18:41:53 +00004700 if (getLangOptions().CPlusPlus) return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00004701
4702 // GCC seems to also exclude expressions of incomplete enum type.
4703 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
4704 if (!T->getDecl()->isComplete()) {
4705 // FIXME: stupid workaround for a codegen bug!
John Wiegley01296292011-04-08 18:41:53 +00004706 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
4707 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00004708 }
4709 }
4710
John Wiegley01296292011-04-08 18:41:53 +00004711 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
4712 if (Res.isInvalid())
4713 return Owned(E);
4714 E = Res.take();
4715
John McCallca61b652010-12-04 12:29:11 +00004716 if (!E->getType()->isVoidType())
4717 RequireCompleteType(E->getExprLoc(), E->getType(),
4718 diag::err_incomplete_type);
John Wiegley01296292011-04-08 18:41:53 +00004719 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00004720}
4721
John Wiegley01296292011-04-08 18:41:53 +00004722ExprResult Sema::ActOnFinishFullExpr(Expr *FE) {
4723 ExprResult FullExpr = Owned(FE);
4724
4725 if (!FullExpr.get())
Douglas Gregora6e053e2010-12-15 01:34:56 +00004726 return ExprError();
John McCall34376a62010-12-04 03:47:34 +00004727
John Wiegley01296292011-04-08 18:41:53 +00004728 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregor506bd562010-12-13 22:49:22 +00004729 return ExprError();
4730
Douglas Gregor95715f92011-12-15 00:53:32 +00004731 // Top-level message sends default to 'id' when we're in a debugger.
4732 if (getLangOptions().DebuggerSupport &&
4733 FullExpr.get()->getType() == Context.UnknownAnyTy &&
4734 isa<ObjCMessageExpr>(FullExpr.get())) {
4735 FullExpr = forceUnknownAnyToType(FullExpr.take(), Context.getObjCIdType());
4736 if (FullExpr.isInvalid())
4737 return ExprError();
4738 }
4739
John McCall3aef3d82011-04-10 19:13:55 +00004740 FullExpr = CheckPlaceholderExpr(FullExpr.take());
4741 if (FullExpr.isInvalid())
4742 return ExprError();
Douglas Gregor0ec210b2011-03-07 02:05:23 +00004743
John Wiegley01296292011-04-08 18:41:53 +00004744 FullExpr = IgnoredValueConversions(FullExpr.take());
4745 if (FullExpr.isInvalid())
4746 return ExprError();
4747
Richard Trieu021baa32011-09-23 20:10:00 +00004748 CheckImplicitConversions(FullExpr.get(), FullExpr.get()->getExprLoc());
John McCall5d413782010-12-06 08:20:24 +00004749 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00004750}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00004751
4752StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
4753 if (!FullStmt) return StmtError();
4754
John McCall5d413782010-12-06 08:20:24 +00004755 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00004756}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00004757
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004758Sema::IfExistsResult
4759Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
4760 CXXScopeSpec &SS,
4761 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00004762 DeclarationName TargetName = TargetNameInfo.getName();
4763 if (!TargetName)
Douglas Gregor43edb322011-10-24 22:31:10 +00004764 return IER_DoesNotExist;
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004765
Douglas Gregor43edb322011-10-24 22:31:10 +00004766 // If the name itself is dependent, then the result is dependent.
4767 if (TargetName.isDependentName())
4768 return IER_Dependent;
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004769
Francois Pichet4a7de3e2011-05-06 20:48:22 +00004770 // Do the redeclaration lookup in the current scope.
4771 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
4772 Sema::NotForRedeclaration);
Douglas Gregor43edb322011-10-24 22:31:10 +00004773 LookupParsedName(R, S, &SS);
Francois Pichet4a7de3e2011-05-06 20:48:22 +00004774 R.suppressDiagnostics();
Douglas Gregor43edb322011-10-24 22:31:10 +00004775
4776 switch (R.getResultKind()) {
4777 case LookupResult::Found:
4778 case LookupResult::FoundOverloaded:
4779 case LookupResult::FoundUnresolvedValue:
4780 case LookupResult::Ambiguous:
4781 return IER_Exists;
4782
4783 case LookupResult::NotFound:
4784 return IER_DoesNotExist;
4785
4786 case LookupResult::NotFoundInCurrentInstantiation:
4787 return IER_Dependent;
4788 }
David Blaikie8a40f702012-01-17 06:56:22 +00004789
4790 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet4a7de3e2011-05-06 20:48:22 +00004791}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004792
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00004793Sema::IfExistsResult
4794Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4795 bool IsIfExists, CXXScopeSpec &SS,
4796 UnqualifiedId &Name) {
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004797 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00004798
4799 // Check for unexpanded parameter packs.
4800 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
4801 collectUnexpandedParameterPacks(SS, Unexpanded);
4802 collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
4803 if (!Unexpanded.empty()) {
4804 DiagnoseUnexpandedParameterPacks(KeywordLoc,
4805 IsIfExists? UPPC_IfExists
4806 : UPPC_IfNotExists,
4807 Unexpanded);
4808 return IER_Error;
4809 }
4810
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004811 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
4812}
4813
Eli Friedmanc7c97142012-01-04 02:40:39 +00004814//===----------------------------------------------------------------------===//
4815// Lambdas.
4816//===----------------------------------------------------------------------===//
4817
Eli Friedman71c80552012-01-05 03:35:19 +00004818void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
4819 Declarator &ParamInfo,
4820 Scope *CurScope) {
4821 DeclContext *DC = CurContext;
Eli Friedman4817cf72012-01-06 03:05:34 +00004822 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
Eli Friedman71c80552012-01-05 03:35:19 +00004823 DC = DC->getParent();
Eli Friedmanc7c97142012-01-04 02:40:39 +00004824
Eli Friedman71c80552012-01-05 03:35:19 +00004825 // Start constructing the lambda class.
4826 CXXRecordDecl *Class = CXXRecordDecl::Create(Context, TTK_Class, DC,
4827 Intro.Range.getBegin(),
4828 /*IdLoc=*/SourceLocation(),
4829 /*Id=*/0);
4830 Class->startDefinition();
Eli Friedman73a04092012-01-07 04:59:52 +00004831 Class->setLambda(true);
Eli Friedman71c80552012-01-05 03:35:19 +00004832 CurContext->addDecl(Class);
Eli Friedmanc7c97142012-01-04 02:40:39 +00004833
Eli Friedman44803322012-01-07 01:08:17 +00004834 QualType ThisCaptureType;
Eli Friedman20139d32012-01-11 02:36:31 +00004835 llvm::DenseMap<VarDecl*, unsigned> CaptureMap;
4836 unsigned CXXThisCaptureIndex = 0;
Eli Friedman73a04092012-01-07 04:59:52 +00004837 llvm::SmallVector<LambdaScopeInfo::Capture, 4> Captures;
Eli Friedman44803322012-01-07 01:08:17 +00004838 for (llvm::SmallVector<LambdaCapture, 4>::const_iterator
4839 C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E; ++C) {
4840 if (C->Kind == LCK_This) {
4841 if (!ThisCaptureType.isNull()) {
4842 Diag(C->Loc, diag::err_capture_more_than_once) << "'this'";
4843 continue;
4844 }
4845
4846 if (Intro.Default == LCD_ByCopy) {
4847 Diag(C->Loc, diag::err_this_capture_with_copy_default);
4848 continue;
4849 }
4850
4851 ThisCaptureType = getCurrentThisType();
Eli Friedman44803322012-01-07 01:08:17 +00004852 if (ThisCaptureType.isNull()) {
4853 Diag(C->Loc, diag::err_invalid_this_use);
4854 continue;
4855 }
Eli Friedman73a04092012-01-07 04:59:52 +00004856 CheckCXXThisCapture(C->Loc);
4857
Eli Friedman20139d32012-01-11 02:36:31 +00004858 // FIXME: Need getCurCapture().
4859 bool isNested = getCurBlock() || getCurLambda();
4860 CapturingScopeInfo::Capture Cap(CapturingScopeInfo::Capture::ThisCapture,
4861 isNested);
4862 Captures.push_back(Cap);
4863 CXXThisCaptureIndex = Captures.size();
Eli Friedman44803322012-01-07 01:08:17 +00004864 continue;
4865 }
4866
4867 assert(C->Id && "missing identifier for capture");
4868
4869 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
4870 Diag(C->Loc, diag::err_reference_capture_with_reference_default);
4871 continue;
4872 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
4873 Diag(C->Loc, diag::err_copy_capture_with_copy_default);
4874 continue;
4875 }
4876
Eli Friedman44803322012-01-07 01:08:17 +00004877 DeclarationNameInfo Name(C->Id, C->Loc);
4878 LookupResult R(*this, Name, LookupOrdinaryName);
4879 CXXScopeSpec ScopeSpec;
4880 LookupParsedName(R, CurScope, &ScopeSpec);
4881 if (R.isAmbiguous())
4882 continue;
4883 if (R.empty())
4884 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, CTC_Unknown))
4885 continue;
4886
4887 VarDecl *Var = R.getAsSingle<VarDecl>();
4888 if (!Var) {
4889 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
4890 continue;
4891 }
4892
Eli Friedman20139d32012-01-11 02:36:31 +00004893 if (CaptureMap.count(Var)) {
4894 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
4895 continue;
4896 }
4897
Eli Friedman44803322012-01-07 01:08:17 +00004898 if (!Var->hasLocalStorage()) {
4899 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
4900 continue;
4901 }
4902
Eli Friedman20139d32012-01-11 02:36:31 +00004903 // FIXME: This is completely wrong for nested captures and variables
4904 // with a non-trivial constructor.
4905 // FIXME: We should refuse to capture __block variables.
4906 Captures.push_back(LambdaScopeInfo::Capture(Var, C->Kind == LCK_ByRef,
4907 /*isNested*/false, 0));
4908 CaptureMap[Var] = Captures.size();
Eli Friedman44803322012-01-07 01:08:17 +00004909 }
4910
Eli Friedman71c80552012-01-05 03:35:19 +00004911 // Build the call operator; we don't really have all the relevant information
4912 // at this point, but we need something to attach child declarations to.
Eli Friedman4817cf72012-01-06 03:05:34 +00004913 QualType MethodTy;
Eli Friedman36d12942012-01-04 04:41:38 +00004914 TypeSourceInfo *MethodTyInfo;
Eli Friedman4817cf72012-01-06 03:05:34 +00004915 if (ParamInfo.getNumTypeObjects() == 0) {
4916 FunctionProtoType::ExtProtoInfo EPI;
4917 EPI.TypeQuals |= DeclSpec::TQ_const;
4918 MethodTy = Context.getFunctionType(Context.DependentTy,
4919 /*Args=*/0, /*NumArgs=*/0, EPI);
4920 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
4921 } else {
4922 assert(ParamInfo.isFunctionDeclarator() &&
4923 "lambda-declarator is a function");
4924 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
4925 if (!FTI.hasMutableQualifier())
4926 FTI.TypeQuals |= DeclSpec::TQ_const;
4927 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
4928 // FIXME: Can these asserts actually fail?
4929 assert(MethodTyInfo && "no type from lambda-declarator");
4930 MethodTy = MethodTyInfo->getType();
4931 assert(!MethodTy.isNull() && "no type from lambda declarator");
4932 }
Eli Friedman36d12942012-01-04 04:41:38 +00004933
Eli Friedman71c80552012-01-05 03:35:19 +00004934 DeclarationName MethodName
4935 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
4936 CXXMethodDecl *Method
4937 = CXXMethodDecl::Create(Context,
4938 Class,
4939 ParamInfo.getSourceRange().getEnd(),
4940 DeclarationNameInfo(MethodName,
4941 /*NameLoc=*/SourceLocation()),
Eli Friedman4817cf72012-01-06 03:05:34 +00004942 MethodTy,
Eli Friedman71c80552012-01-05 03:35:19 +00004943 MethodTyInfo,
4944 /*isStatic=*/false,
4945 SC_None,
4946 /*isInline=*/true,
4947 /*isConstExpr=*/false,
4948 ParamInfo.getSourceRange().getEnd());
4949 Method->setAccess(AS_public);
4950 Class->addDecl(Method);
4951 Method->setLexicalDeclContext(DC); // FIXME: Is this really correct?
4952
Eli Friedman71c80552012-01-05 03:35:19 +00004953 ProcessDeclAttributes(CurScope, Method, ParamInfo);
4954
Eli Friedman71c80552012-01-05 03:35:19 +00004955 // Enter a new evaluation context to insulate the block from any
4956 // cleanups from the enclosing full-expression.
4957 PushExpressionEvaluationContext(PotentiallyEvaluated);
4958
4959 PushDeclContext(CurScope, Method);
Eli Friedman4817cf72012-01-06 03:05:34 +00004960
Eli Friedman4817cf72012-01-06 03:05:34 +00004961 // Set the parameters on the decl, if specified.
4962 if (isa<FunctionProtoTypeLoc>(MethodTyInfo->getTypeLoc())) {
4963 FunctionProtoTypeLoc Proto =
4964 cast<FunctionProtoTypeLoc>(MethodTyInfo->getTypeLoc());
4965 Method->setParams(Proto.getParams());
4966 CheckParmsForFunctionDef(Method->param_begin(),
4967 Method->param_end(),
4968 /*CheckParameterNames=*/false);
4969
4970 // Introduce our parameters into the function scope
4971 for (unsigned p = 0, NumParams = Method->getNumParams(); p < NumParams; ++p) {
4972 ParmVarDecl *Param = Method->getParamDecl(p);
4973 Param->setOwningFunction(Method);
4974
4975 // If this has an identifier, add it to the scope stack.
4976 if (Param->getIdentifier()) {
4977 CheckShadow(CurScope, Param);
4978
4979 PushOnScopeChains(Param, CurScope);
4980 }
4981 }
4982 }
4983
Eli Friedman73a04092012-01-07 04:59:52 +00004984 // Introduce the lambda scope.
4985 PushLambdaScope(Class);
4986
4987 LambdaScopeInfo *LSI = getCurLambda();
Eli Friedman20139d32012-01-11 02:36:31 +00004988 LSI->CXXThisCaptureIndex = CXXThisCaptureIndex;
4989 std::swap(LSI->CaptureMap, CaptureMap);
Eli Friedman73a04092012-01-07 04:59:52 +00004990 std::swap(LSI->Captures, Captures);
Eli Friedman20139d32012-01-11 02:36:31 +00004991 LSI->NumExplicitCaptures = Captures.size();
4992 if (Intro.Default == LCD_ByCopy)
4993 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
4994 else if (Intro.Default == LCD_ByRef)
4995 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
Eli Friedman73a04092012-01-07 04:59:52 +00004996
Eli Friedman4817cf72012-01-06 03:05:34 +00004997 const FunctionType *Fn = MethodTy->getAs<FunctionType>();
4998 QualType RetTy = Fn->getResultType();
4999 if (RetTy != Context.DependentTy) {
5000 LSI->ReturnType = RetTy;
Eli Friedman20139d32012-01-11 02:36:31 +00005001 } else {
Eli Friedman4817cf72012-01-06 03:05:34 +00005002 LSI->HasImplicitReturnType = true;
5003 }
5004
5005 // FIXME: Check return type is complete, !isObjCObjectType
5006
Eli Friedmanc7c97142012-01-04 02:40:39 +00005007}
5008
5009void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope) {
5010 // Leave the expression-evaluation context.
5011 DiscardCleanupsInEvaluationContext();
5012 PopExpressionEvaluationContext();
5013
5014 // Leave the context of the lambda.
Eli Friedman71c80552012-01-05 03:35:19 +00005015 PopDeclContext();
5016 PopFunctionScopeInfo();
Eli Friedmanc7c97142012-01-04 02:40:39 +00005017}
5018
5019ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc,
5020 Stmt *Body, Scope *CurScope) {
5021 // FIXME: Implement
5022 Diag(StartLoc, diag::err_lambda_unsupported);
5023 ActOnLambdaError(StartLoc, CurScope);
5024 return ExprError();
5025}