blob: 5e7fb33d054fa7a954d069ec62738bf3bd8ccde2 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall2a7fb272010-08-25 05:32:35 +000015#include "clang/Sema/DeclSpec.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
John McCall2a7fb272010-08-25 05:32:35 +000018#include "clang/Sema/ParsedTemplate.h"
John McCall469a1eb2011-02-02 13:00:07 +000019#include "clang/Sema/ScopeInfo.h"
Richard Smith7a614d82011-06-11 17:19:42 +000020#include "clang/Sema/Scope.h"
John McCall2a7fb272010-08-25 05:32:35 +000021#include "clang/Sema/TemplateDeduction.h"
Steve Naroff210679c2007-08-25 14:02:58 +000022#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000023#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000024#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000025#include "clang/AST/ExprCXX.h"
Fariborz Jahaniand4266622010-06-16 18:56:04 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregorb57fb492010-02-24 22:38:50 +000027#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000028#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000029#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000030#include "clang/Lex/Preprocessor.h"
David Blaikie91ec7892011-12-16 16:03:09 +000031#include "TypeLocBuilder.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000032#include "llvm/ADT/STLExtras.h"
Chandler Carruth73e0a912011-05-01 07:23:17 +000033#include "llvm/Support/ErrorHandling.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000034using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000035using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000036
John McCallb3d87482010-08-24 05:47:05 +000037ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000038 IdentifierInfo &II,
John McCallb3d87482010-08-24 05:47:05 +000039 SourceLocation NameLoc,
40 Scope *S, CXXScopeSpec &SS,
41 ParsedType ObjectTypePtr,
42 bool EnteringContext) {
Douglas Gregor124b8782010-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 Gregor93649fd2010-02-23 00:15:22 +000062 // See also PR6358 and PR6359.
Sebastian Redlc0fee502010-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 Gregor124b8782010-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 Gregor93649fd2010-02-23 00:15:22 +000077 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000078
Douglas Gregor93649fd2010-02-23 00:15:22 +000079 bool AlreadySearched = false;
80 bool LookAtPrefix = true;
Sebastian Redlc0fee502010-07-07 23:17:38 +000081 // C++ [basic.lookup.qual]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000082 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redlc0fee502010-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 Takumi00995302011-01-27 07:09:49 +000085 //
86 // ::[opt] nested-name-specifier ~ class-name
Sebastian Redlc0fee502010-07-07 23:17:38 +000087 //
88 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth5e895a82010-02-21 10:19:54 +000089 // a qualified-id of the form:
Douglas Gregor124b8782010-02-16 19:09:40 +000090 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +000091 // ::opt nested-name-specifier class-name :: ~ class-name
Douglas Gregor124b8782010-02-16 19:09:40 +000092 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000093 // the class-names are looked up as types in the scope designated by
Sebastian Redlc0fee502010-07-07 23:17:38 +000094 // the nested-name-specifier.
Douglas Gregor124b8782010-02-16 19:09:40 +000095 //
Sebastian Redlc0fee502010-07-07 23:17:38 +000096 // Here, we check the first case (completely) and determine whether the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000097 // code below is permitted to look at the prefix of the
Sebastian Redlc0fee502010-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 Takumidfbb02a2011-01-27 07:10:08 +0000106
Sebastian Redlc0fee502010-07-07 23:17:38 +0000107 // The second case from the C++03 rules quoted further above.
Douglas Gregor93649fd2010-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 Gregor7e384942011-02-25 16:07:42 +0000113 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor93649fd2010-02-23 00:15:22 +0000114 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
115 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000116 } else if (ObjectTypePtr) {
Douglas Gregor124b8782010-02-16 19:09:40 +0000117 LookupCtx = computeDeclContext(SearchType);
118 isDependent = SearchType->isDependentType();
119 } else {
120 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000121 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregor124b8782010-02-16 19:09:40 +0000122 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000123
Douglas Gregoredc90502010-02-25 04:46:04 +0000124 LookInScope = false;
Douglas Gregor124b8782010-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 Takumidfbb02a2011-01-27 07:10:08 +0000135 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregor124b8782010-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 Gregor7ec18732011-03-04 22:32:08 +0000144 TypeDecl *NonMatchingTypeDecl = 0;
Douglas Gregor124b8782010-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 Gregor7ec18732011-03-04 22:32:08 +0000148 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregor124b8782010-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 Gregora2e7dd22010-02-25 01:56:36 +0000153 else if (Step == 1 && LookInScope && S)
Douglas Gregor124b8782010-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 McCallb3d87482010-08-24 05:47:05 +0000160 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000161
162 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
163 QualType T = Context.getTypeDeclType(Type);
Douglas Gregor124b8782010-02-16 19:09:40 +0000164
165 if (SearchType.isNull() || SearchType->isDependentType() ||
166 Context.hasSameUnqualifiedType(T, SearchType)) {
167 // We found our type!
168
John McCallb3d87482010-08-24 05:47:05 +0000169 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000170 }
John Wiegley36784e72011-03-08 08:13:22 +0000171
Douglas Gregor7ec18732011-03-04 22:32:08 +0000172 if (!SearchType.isNull())
173 NonMatchingTypeDecl = Type;
Douglas Gregor124b8782010-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 Takumidfbb02a2011-01-27 07:10:08 +0000181 // issue 399, for which there isn't even an obvious direction.
Douglas Gregor124b8782010-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 McCall3cb0ebd2010-03-10 03:28:59 +0000187 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
188 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregor124b8782010-02-16 19:09:40 +0000189 }
190 }
191 if (MemberOfType.isNull())
192 MemberOfType = SearchType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000193
Douglas Gregor124b8782010-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 McCallb3d87482010-08-24 05:47:05 +0000205 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000206 }
207
208 continue;
209 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000210
Douglas Gregor124b8782010-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 McCallb3d87482010-08-24 05:47:05 +0000224 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-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 Takumidfbb02a2011-01-27 07:10:08 +0000231 if (DependentTemplateName *DepTemplate
Douglas Gregor124b8782010-02-16 19:09:40 +0000232 = SpecName.getAsDependentTemplateName()) {
233 if (DepTemplate->isIdentifier() &&
234 DepTemplate->getIdentifier() == Template->getIdentifier())
John McCallb3d87482010-08-24 05:47:05 +0000235 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-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 Gregore29425b2011-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 McCallb3d87482010-08-24 05:47:05 +0000251 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000252 }
253
Douglas Gregor7ec18732011-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 Takumidfbb02a2011-01-27 07:10:08 +0000262 << &II;
Douglas Gregor124b8782010-02-16 19:09:40 +0000263 else
264 Diag(NameLoc, diag::err_destructor_class_name);
265
John McCallb3d87482010-08-24 05:47:05 +0000266 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000267}
268
David Blaikie53a75c02011-12-08 16:13:53 +0000269ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) {
David Blaikie4db8c442011-12-12 04:13:55 +0000270 if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType)
David Blaikie53a75c02011-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 Gregor57fdc8a2010-04-26 22:37:10 +0000285/// \brief Build a C++ typeid expression with a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000286ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000287 SourceLocation TypeidLoc,
288 TypeSourceInfo *Operand,
289 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000290 // C++ [expr.typeid]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000291 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000292 // that is the operand of typeid are always ignored.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000293 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000294 // type, the class shall be completely-defined.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000295 Qualifiers Quals;
296 QualType T
297 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
298 Quals);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000299 if (T->getAs<RecordType>() &&
300 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
301 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000302
Douglas Gregor57fdc8a2010-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 McCall60d7b3a2010-08-24 06:29:42 +0000309ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000310 SourceLocation TypeidLoc,
311 Expr *E,
312 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000313 bool isUnevaluatedOperand = true;
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000314 if (E && !E->isTypeDependent()) {
John McCall6dbba4f2011-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 Gregor57fdc8a2010-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 Takumidfbb02a2011-01-27 07:10:08 +0000329
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000330 // C++ [expr.typeid]p3:
Sebastian Redl906082e2010-07-20 04:20:21 +0000331 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000332 // polymorphic class type [...] [the] expression is an unevaluated
333 // operand. [...]
Sebastian Redl906082e2010-07-20 04:20:21 +0000334 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000335 isUnevaluatedOperand = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000336
337 // We require a vtable to query the type at run time.
338 MarkVTableUsed(TypeidLoc, RecordD);
339 }
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000340 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000341
Douglas Gregor57fdc8a2010-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 Takumidfbb02a2011-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 Gregor57fdc8a2010-04-26 22:37:10 +0000346 // type.
Douglas Gregord1c1d7b2010-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 Friedmanc1c0dfb2011-09-27 21:58:52 +0000351 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).take();
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000352 }
353 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000354
Douglas Gregor57fdc8a2010-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 Takumidfbb02a2011-01-27 07:10:08 +0000360
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000361 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCall9ae2f072010-08-23 23:25:46 +0000362 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000363 SourceRange(TypeidLoc, RParenLoc)));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000364}
365
366/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCall60d7b3a2010-08-24 06:29:42 +0000367ExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000368Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
369 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000370 // Find the std::type_info type.
Sebastian Redlce0682f2011-03-31 19:29:24 +0000371 if (!getStdNamespace())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000372 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000373
Douglas Gregor4eb4f0f2010-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 Takumidfbb02a2011-01-27 07:10:08 +0000382
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000383 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000384
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000385 if (isType) {
386 // The operand is a type; handle it as such.
387 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +0000388 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
389 &TInfo);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000390 if (T.isNull())
391 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000392
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000393 if (!TInfo)
394 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000395
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000396 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000397 }
Mike Stump1eb44332009-09-09 15:08:12 +0000398
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000399 // The operand is an expression.
John McCall9ae2f072010-08-23 23:25:46 +0000400 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000401}
402
Francois Pichet6915c522010-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 McCallf4c73712011-01-19 06:33:43 +0000406 const Type *Ty = QT.getTypePtr();;
Francois Pichet913b7bf2010-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 Pichet8db75a22011-05-08 10:02:20 +0000412 // Loop all record redeclaration looking for an uuid attribute.
Francois Pichet6915c522010-12-27 01:32:00 +0000413 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Francois Pichet8db75a22011-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 Pichet6915c522010-12-27 01:32:00 +0000417 return Uuid;
Francois Pichet6915c522010-12-27 01:32:00 +0000418 }
Francois Pichet8db75a22011-05-08 10:02:20 +0000419
Francois Pichet6915c522010-12-27 01:32:00 +0000420 return 0;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000421}
422
Francois Pichet01b7c302010-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 Pichet6915c522010-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 Takumidfbb02a2011-01-27 07:10:08 +0000432
Francois Pichet01b7c302010-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 Pichet6915c522010-12-27 01:32:00 +0000444 if (!E->getType()->isDependentType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000445 if (!GetUuidAttrOfType(E->getType()) &&
Francois Pichet6915c522010-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 Pichet01b7c302010-09-08 12:20:18 +0000450 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
451 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000452 SourceRange(TypeidLoc, RParenLoc)));
Francois Pichet01b7c302010-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 Takumidfbb02a2011-01-27 07:10:08 +0000459 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet01b7c302010-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 Takumidfbb02a2011-01-27 07:10:08 +0000467 }
468
Francois Pichet01b7c302010-09-08 12:20:18 +0000469 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000470
Francois Pichet01b7c302010-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 Takumidfbb02a2011-01-27 07:10:08 +0000478
Francois Pichet01b7c302010-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 Takumidfbb02a2011-01-27 07:10:08 +0000485 // The operand is an expression.
Francois Pichet01b7c302010-09-08 12:20:18 +0000486 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
487}
488
Steve Naroff1b273c42007-09-16 14:56:35 +0000489/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCall60d7b3a2010-08-24 06:29:42 +0000490ExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000491Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000492 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000493 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000494 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
495 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000496}
Chris Lattner50dd2892008-02-26 00:51:44 +0000497
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000498/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCall60d7b3a2010-08-24 06:29:42 +0000499ExprResult
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000500Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
501 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
502}
503
Chris Lattner50dd2892008-02-26 00:51:44 +0000504/// ActOnCXXThrow - Parse throw expressions.
John McCall60d7b3a2010-08-24 06:29:42 +0000505ExprResult
Douglas Gregorbca01b42011-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 Carlsson729b8532011-02-23 03:46:46 +0000544 // Don't report an error if 'throw' is used in system headers.
Anders Carlsson15348ae2011-02-28 02:27:16 +0000545 if (!getLangOptions().CXXExceptions &&
Anders Carlsson729b8532011-02-23 03:46:46 +0000546 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb1fba312011-02-19 21:53:09 +0000547 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Douglas Gregorbca01b42011-07-06 22:04:06 +0000548
John Wiegley429bb272011-04-08 18:41:53 +0000549 if (Ex && !Ex->isTypeDependent()) {
Douglas Gregorbca01b42011-07-06 22:04:06 +0000550 ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex, IsThrownVarInScope);
John Wiegley429bb272011-04-08 18:41:53 +0000551 if (ExRes.isInvalid())
552 return ExprError();
553 Ex = ExRes.take();
554 }
Douglas Gregorbca01b42011-07-06 22:04:06 +0000555
556 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc,
557 IsThrownVarInScope));
Sebastian Redl972041f2009-04-27 20:27:31 +0000558}
559
560/// CheckCXXThrowOperand - Validate the operand of a throw.
Douglas Gregorbca01b42011-07-06 22:04:06 +0000561ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
562 bool IsThrownVarInScope) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000563 // C++ [except.throw]p3:
Douglas Gregor154fe982009-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 Takumidfbb02a2011-01-27 07:10:08 +0000567 // the type from "array of T" or "function returning T" to "pointer to T"
Douglas Gregor154fe982009-12-23 22:04:40 +0000568 // or "pointer to function returning T", [...]
569 if (E->getType().hasQualifiers())
John Wiegley429bb272011-04-08 18:41:53 +0000570 E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +0000571 E->getValueKind()).take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000572
John Wiegley429bb272011-04-08 18:41:53 +0000573 ExprResult Res = DefaultFunctionArrayConversion(E);
574 if (Res.isInvalid())
575 return ExprError();
576 E = Res.take();
Sebastian Redl972041f2009-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 McCallac418162010-04-22 01:10:34 +0000581 bool isPointer = false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000582 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000583 Ty = Ptr->getPointeeType();
John McCallac418162010-04-22 01:10:34 +0000584 isPointer = true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000585 }
586 if (!isPointer || !Ty->isVoidType()) {
587 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000588 PDiag(isPointer ? diag::err_throw_incomplete_ptr
589 : diag::err_throw_incomplete)
590 << E->getSourceRange()))
John Wiegley429bb272011-04-08 18:41:53 +0000591 return ExprError();
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000592
Douglas Gregorbf422f92010-04-15 18:05:39 +0000593 if (RequireNonAbstractType(ThrowLoc, E->getType(),
594 PDiag(diag::err_throw_abstract_type)
595 << E->getSourceRange()))
John Wiegley429bb272011-04-08 18:41:53 +0000596 return ExprError();
Sebastian Redl972041f2009-04-27 20:27:31 +0000597 }
598
John McCallac418162010-04-22 01:10:34 +0000599 // Initialize the exception result. This implicitly weeds out
600 // abstract types or types with inaccessible copy constructors.
Douglas Gregorbca01b42011-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 McCallac418162010-04-22 01:10:34 +0000617 InitializedEntity Entity =
Douglas Gregor72dfa272011-01-21 22:46:35 +0000618 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
Douglas Gregorbca01b42011-07-06 22:04:06 +0000619 /*NRVO=*/NRVOVariable != 0);
John Wiegley429bb272011-04-08 18:41:53 +0000620 Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
Douglas Gregorbca01b42011-07-06 22:04:06 +0000621 QualType(), E,
622 IsThrownVarInScope);
John McCallac418162010-04-22 01:10:34 +0000623 if (Res.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000624 return ExprError();
625 E = Res.take();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000626
Eli Friedman5ed9b932010-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 Wiegley429bb272011-04-08 18:41:53 +0000630 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000631 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
632
Douglas Gregor6fb745b2010-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 Friedman5ed9b932010-06-03 20:39:03 +0000635 MarkVTableUsed(ThrowLoc, RD);
636
Eli Friedman98efb9f2010-10-12 20:32:36 +0000637 // If a pointer is thrown, the referenced object will not be destroyed.
638 if (isPointer)
John Wiegley429bb272011-04-08 18:41:53 +0000639 return Owned(E);
Eli Friedman98efb9f2010-10-12 20:32:36 +0000640
Eli Friedman5ed9b932010-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 Wiegley429bb272011-04-08 18:41:53 +0000643 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000644
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000645 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +0000646 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman5ed9b932010-06-03 20:39:03 +0000647 if (!Destructor)
John Wiegley429bb272011-04-08 18:41:53 +0000648 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000649
650 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
651 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregored8abf12010-07-08 06:14:04 +0000652 PDiag(diag::err_access_dtor_exception) << Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000653 return Owned(E);
Chris Lattner50dd2892008-02-26 00:51:44 +0000654}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000655
Eli Friedman72899c32012-01-07 04:59:52 +0000656QualType Sema::getCurrentThisType() {
657 DeclContext *DC = getFunctionLevelDeclContext();
Richard Smith7a614d82011-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 McCall469a1eb2011-02-02 13:00:07 +0000671
Richard Smith7a614d82011-06-11 17:19:42 +0000672 return ThisTy;
John McCall5808ce42011-02-03 08:15:49 +0000673}
674
Eli Friedman72899c32012-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--) {
683 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(FunctionScopes[idx])) {
684 if (LSI->CapturesCXXThis) {
685 // This lambda already captures 'this'; there isn't anything more to do.
686 break;
687 }
688 if (LSI->Default == LCD_ByRef) {
689 // This lambda can implicitly capture 'this'; continue looking upwards.
690 // FIXME: Is this check correct? The rules in the standard are a bit
691 // unclear.
692 NumClosures++;
693 continue;
694 }
695 // This lambda can't implicitly capture 'this'; fail out.
696 // (We need to delay the diagnostic in the
697 // PotentiallyPotentiallyEvaluated case because it doesn't apply to
698 // unevaluated contexts.)
699 if (ExprEvalContexts.back().Context == PotentiallyPotentiallyEvaluated)
700 ExprEvalContexts.back()
701 .addDiagnostic(Loc, PDiag(diag::err_implicit_this_capture));
702 else
703 Diag(Loc, diag::err_implicit_this_capture);
704 return;
705 }
706 if (isa<BlockScopeInfo>(FunctionScopes[idx])) {
707 NumClosures++;
708 continue;
709 }
710 break;
711 }
712
713 // Mark that we're implicitly capturing 'this' in all the scopes we skipped.
714 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
715 // contexts.
716 for (unsigned idx = FunctionScopes.size() - 1;
717 NumClosures; --idx, --NumClosures) {
718 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(FunctionScopes[idx])) {
719 BSI->CapturesCXXThis = true;
720 } else {
721 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(FunctionScopes[idx]);
722 assert(LSI && "Unexpected closure");
723 LSI->CapturesCXXThis = true;
724 LSI->Captures.push_back(LambdaScopeInfo::Capture::ThisCapture);
725 }
726 }
727}
728
Richard Smith7a614d82011-06-11 17:19:42 +0000729ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCall5808ce42011-02-03 08:15:49 +0000730 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
731 /// is a non-lvalue expression whose value is the address of the object for
732 /// which the function is called.
733
Douglas Gregor341350e2011-10-18 16:47:30 +0000734 QualType ThisTy = getCurrentThisType();
Richard Smith7a614d82011-06-11 17:19:42 +0000735 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCall5808ce42011-02-03 08:15:49 +0000736
Eli Friedman72899c32012-01-07 04:59:52 +0000737 CheckCXXThisCapture(Loc);
Richard Smith7a614d82011-06-11 17:19:42 +0000738 return Owned(new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000739}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000740
John McCall60d7b3a2010-08-24 06:29:42 +0000741ExprResult
Douglas Gregorab6677e2010-09-08 00:15:04 +0000742Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000743 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000744 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000745 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000746 if (!TypeRep)
747 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000748
John McCall9d125032010-01-15 18:39:57 +0000749 TypeSourceInfo *TInfo;
750 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
751 if (!TInfo)
752 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregorab6677e2010-09-08 00:15:04 +0000753
754 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
755}
756
757/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
758/// Can be interpreted either as function-style casting ("int(x)")
759/// or class type construction ("ClassType(x,y,z)")
760/// or creation of a value-initialized type ("int()").
761ExprResult
762Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
763 SourceLocation LParenLoc,
764 MultiExprArg exprs,
765 SourceLocation RParenLoc) {
766 QualType Ty = TInfo->getType();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000767 unsigned NumExprs = exprs.size();
768 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000769 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000770 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
771
Sebastian Redlf53597f2009-03-15 17:47:39 +0000772 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000773 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000774 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000775
Douglas Gregorab6677e2010-09-08 00:15:04 +0000776 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000777 LParenLoc,
778 Exprs, NumExprs,
779 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000780 }
781
Anders Carlssonbb60a502009-08-27 03:53:50 +0000782 if (Ty->isArrayType())
783 return ExprError(Diag(TyBeginLoc,
784 diag::err_value_init_for_array_type) << FullRange);
785 if (!Ty->isVoidType() &&
786 RequireCompleteType(TyBeginLoc, Ty,
787 PDiag(diag::err_invalid_incomplete_type_use)
788 << FullRange))
789 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000790
Anders Carlssonbb60a502009-08-27 03:53:50 +0000791 if (RequireNonAbstractType(TyBeginLoc, Ty,
792 diag::err_allocation_of_abstract_type))
793 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000794
795
Douglas Gregor506ae412009-01-16 18:33:17 +0000796 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000797 // If the expression list is a single expression, the type conversion
798 // expression is equivalent (in definedness, and if defined in meaning) to the
799 // corresponding cast expression.
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000800 if (NumExprs == 1) {
John McCallb45ae252011-10-05 07:41:44 +0000801 Expr *Arg = Exprs[0];
Anders Carlsson0aebc812009-09-09 21:33:21 +0000802 exprs.release();
John McCallb45ae252011-10-05 07:41:44 +0000803 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000804 }
805
Douglas Gregor19311e72010-09-08 21:40:08 +0000806 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
807 InitializationKind Kind
808 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
809 LParenLoc, RParenLoc)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000810 : InitializationKind::CreateValue(TyBeginLoc,
Douglas Gregor19311e72010-09-08 21:40:08 +0000811 LParenLoc, RParenLoc);
812 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
813 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redlf53597f2009-03-15 17:47:39 +0000814
Douglas Gregor19311e72010-09-08 21:40:08 +0000815 // FIXME: Improve AST representation?
816 return move(Result);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000817}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000818
John McCall6ec278d2011-01-27 09:37:56 +0000819/// doesUsualArrayDeleteWantSize - Answers whether the usual
820/// operator delete[] for the given type has a size_t parameter.
821static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
822 QualType allocType) {
823 const RecordType *record =
824 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
825 if (!record) return false;
826
827 // Try to find an operator delete[] in class scope.
828
829 DeclarationName deleteName =
830 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
831 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
832 S.LookupQualifiedName(ops, record->getDecl());
833
834 // We're just doing this for information.
835 ops.suppressDiagnostics();
836
837 // Very likely: there's no operator delete[].
838 if (ops.empty()) return false;
839
840 // If it's ambiguous, it should be illegal to call operator delete[]
841 // on this thing, so it doesn't matter if we allocate extra space or not.
842 if (ops.isAmbiguous()) return false;
843
844 LookupResult::Filter filter = ops.makeFilter();
845 while (filter.hasNext()) {
846 NamedDecl *del = filter.next()->getUnderlyingDecl();
847
848 // C++0x [basic.stc.dynamic.deallocation]p2:
849 // A template instance is never a usual deallocation function,
850 // regardless of its signature.
851 if (isa<FunctionTemplateDecl>(del)) {
852 filter.erase();
853 continue;
854 }
855
856 // C++0x [basic.stc.dynamic.deallocation]p2:
857 // If class T does not declare [an operator delete[] with one
858 // parameter] but does declare a member deallocation function
859 // named operator delete[] with exactly two parameters, the
860 // second of which has type std::size_t, then this function
861 // is a usual deallocation function.
862 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
863 filter.erase();
864 continue;
865 }
866 }
867 filter.done();
868
869 if (!ops.isSingleResult()) return false;
870
871 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
872 return (del->getNumParams() == 2);
873}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000874
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000875/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
876/// @code new (memory) int[size][4] @endcode
877/// or
878/// @code ::new Foo(23, "hello") @endcode
879/// For the interpretation of this heap of arguments, consult the base version.
John McCall60d7b3a2010-08-24 06:29:42 +0000880ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000881Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000882 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000883 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000884 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000885 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000886 SourceLocation ConstructorRParen) {
Richard Smith34b41d92011-02-20 03:19:35 +0000887 bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
888
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000889 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000890 // If the specified type is an array, unwrap it and save the expression.
891 if (D.getNumTypeObjects() > 0 &&
892 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
893 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smith34b41d92011-02-20 03:19:35 +0000894 if (TypeContainsAuto)
895 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
896 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000897 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000898 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
899 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000900 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000901 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
902 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000903
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000904 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000905 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000906 }
907
Douglas Gregor043cad22009-09-11 00:18:58 +0000908 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000909 if (ArraySize) {
910 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000911 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
912 break;
913
914 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
915 if (Expr *NumElts = (Expr *)Array.NumElts) {
916 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
917 !NumElts->isIntegerConstantExpr(Context)) {
918 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
919 << NumElts->getSourceRange();
920 return ExprError();
921 }
922 }
923 }
924 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000925
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +0000926 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
John McCallbf1a0282010-06-04 23:28:52 +0000927 QualType AllocType = TInfo->getType();
Chris Lattnereaaebc72009-04-25 08:06:05 +0000928 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000929 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000930
Mike Stump1eb44332009-09-09 15:08:12 +0000931 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000932 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000933 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000934 PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000935 TypeIdParens,
Mike Stump1eb44332009-09-09 15:08:12 +0000936 AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000937 TInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000938 ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000939 ConstructorLParen,
940 move(ConstructorArgs),
Richard Smith34b41d92011-02-20 03:19:35 +0000941 ConstructorRParen,
942 TypeContainsAuto);
Douglas Gregor3433cf72009-05-21 00:00:09 +0000943}
944
John McCall60d7b3a2010-08-24 06:29:42 +0000945ExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000946Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
947 SourceLocation PlacementLParen,
948 MultiExprArg PlacementArgs,
949 SourceLocation PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000950 SourceRange TypeIdParens,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000951 QualType AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000952 TypeSourceInfo *AllocTypeInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000953 Expr *ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000954 SourceLocation ConstructorLParen,
955 MultiExprArg ConstructorArgs,
Richard Smith34b41d92011-02-20 03:19:35 +0000956 SourceLocation ConstructorRParen,
957 bool TypeMayContainAuto) {
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000958 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000959
Richard Smith34b41d92011-02-20 03:19:35 +0000960 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
961 if (TypeMayContainAuto && AllocType->getContainedAutoType()) {
962 if (ConstructorArgs.size() == 0)
963 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
964 << AllocType << TypeRange);
965 if (ConstructorArgs.size() != 1) {
966 Expr *FirstBad = ConstructorArgs.get()[1];
967 return ExprError(Diag(FirstBad->getSourceRange().getBegin(),
968 diag::err_auto_new_ctor_multiple_expressions)
969 << AllocType << TypeRange);
970 }
Richard Smitha085da82011-03-17 16:11:59 +0000971 TypeSourceInfo *DeducedType = 0;
972 if (!DeduceAutoType(AllocTypeInfo, ConstructorArgs.get()[0], DeducedType))
Richard Smith34b41d92011-02-20 03:19:35 +0000973 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
974 << AllocType
975 << ConstructorArgs.get()[0]->getType()
976 << TypeRange
977 << ConstructorArgs.get()[0]->getSourceRange());
Richard Smitha085da82011-03-17 16:11:59 +0000978 if (!DeducedType)
979 return ExprError();
Richard Smith34b41d92011-02-20 03:19:35 +0000980
Richard Smitha085da82011-03-17 16:11:59 +0000981 AllocTypeInfo = DeducedType;
982 AllocType = AllocTypeInfo->getType();
Richard Smith34b41d92011-02-20 03:19:35 +0000983 }
984
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000985 // Per C++0x [expr.new]p5, the type being constructed may be a
986 // typedef of an array type.
John McCall9ae2f072010-08-23 23:25:46 +0000987 if (!ArraySize) {
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000988 if (const ConstantArrayType *Array
989 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000990 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
991 Context.getSizeType(),
992 TypeRange.getEnd());
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000993 AllocType = Array->getElementType();
994 }
995 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000996
Douglas Gregora0750762010-10-06 16:00:31 +0000997 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
998 return ExprError();
999
John McCallf85e1932011-06-15 23:02:42 +00001000 // In ARC, infer 'retaining' for the allocated
1001 if (getLangOptions().ObjCAutoRefCount &&
1002 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1003 AllocType->isObjCLifetimeType()) {
1004 AllocType = Context.getLifetimeQualifiedType(AllocType,
1005 AllocType->getObjCARCImplicitLifetime());
1006 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001007
John McCallf85e1932011-06-15 23:02:42 +00001008 QualType ResultType = Context.getPointerType(AllocType);
1009
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001010 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
1011 // or enumeration type with a non-negative value."
Sebastian Redl28507842009-02-26 14:39:58 +00001012 if (ArraySize && !ArraySize->isTypeDependent()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001013
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001014 QualType SizeType = ArraySize->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001015
Richard Smithebaf0e62011-10-18 20:49:44 +00001016 ExprResult ConvertedSize = ConvertToIntegralOrEnumerationType(
1017 StartLoc, ArraySize,
1018 PDiag(diag::err_array_size_not_integral),
1019 PDiag(diag::err_array_size_incomplete_type)
1020 << ArraySize->getSourceRange(),
1021 PDiag(diag::err_array_size_explicit_conversion),
1022 PDiag(diag::note_array_size_conversion),
1023 PDiag(diag::err_array_size_ambiguous_conversion),
1024 PDiag(diag::note_array_size_conversion),
1025 PDiag(getLangOptions().CPlusPlus0x ?
1026 diag::warn_cxx98_compat_array_size_conversion :
1027 diag::ext_array_size_conversion));
Douglas Gregor6bc574d2010-06-30 00:20:43 +00001028 if (ConvertedSize.isInvalid())
1029 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001030
John McCall9ae2f072010-08-23 23:25:46 +00001031 ArraySize = ConvertedSize.take();
Douglas Gregor6bc574d2010-06-30 00:20:43 +00001032 SizeType = ArraySize->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001033 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor6bc574d2010-06-30 00:20:43 +00001034 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001035
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001036 // Let's see if this is a constant < 0. If so, we reject it out of hand.
1037 // We don't care about special rules, so we tell the machinery it's not
1038 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +00001039 if (!ArraySize->isValueDependent()) {
1040 llvm::APSInt Value;
1041 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
1042 if (Value < llvm::APSInt(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001043 llvm::APInt::getNullValue(Value.getBitWidth()),
Anders Carlssonac18b2e2009-09-23 00:37:25 +00001044 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +00001045 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +00001046 diag::err_typecheck_negative_array_size)
Sebastian Redlf53597f2009-03-15 17:47:39 +00001047 << ArraySize->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001048
Douglas Gregor2767ce22010-08-18 00:39:00 +00001049 if (!AllocType->isDependentType()) {
1050 unsigned ActiveSizeBits
1051 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1052 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001053 Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +00001054 diag::err_array_too_large)
1055 << Value.toString(10)
1056 << ArraySize->getSourceRange();
1057 return ExprError();
1058 }
1059 }
Douglas Gregor4bd40312010-07-13 15:54:32 +00001060 } else if (TypeIdParens.isValid()) {
1061 // Can't have dynamic array size when the type-id is in parentheses.
1062 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1063 << ArraySize->getSourceRange()
1064 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1065 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001066
Douglas Gregor4bd40312010-07-13 15:54:32 +00001067 TypeIdParens = SourceRange();
Sebastian Redl28507842009-02-26 14:39:58 +00001068 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001069 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001070
John McCallf85e1932011-06-15 23:02:42 +00001071 // ARC: warn about ABI issues.
1072 if (getLangOptions().ObjCAutoRefCount) {
1073 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1074 if (BaseAllocType.hasStrongOrWeakObjCLifetime())
1075 Diag(StartLoc, diag::warn_err_new_delete_object_array)
1076 << 0 << BaseAllocType;
1077 }
1078
John McCall7d166272011-05-15 07:14:44 +00001079 // Note that we do *not* convert the argument in any way. It can
1080 // be signed, larger than size_t, whatever.
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001081 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001082
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001083 FunctionDecl *OperatorNew = 0;
1084 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +00001085 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
1086 unsigned NumPlaceArgs = PlacementArgs.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001087
Sebastian Redl28507842009-02-26 14:39:58 +00001088 if (!AllocType->isDependentType() &&
1089 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
1090 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +00001091 SourceRange(PlacementLParen, PlacementRParen),
1092 UseGlobal, AllocType, ArraySize, PlaceArgs,
1093 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +00001094 return ExprError();
John McCall6ec278d2011-01-27 09:37:56 +00001095
1096 // If this is an array allocation, compute whether the usual array
1097 // deallocation function for the type has a size_t parameter.
1098 bool UsualArrayDeleteWantsSize = false;
1099 if (ArraySize && !AllocType->isDependentType())
1100 UsualArrayDeleteWantsSize
1101 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1102
Chris Lattner5f9e2722011-07-23 10:55:15 +00001103 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001104 if (OperatorNew) {
1105 // Add default arguments, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001106 const FunctionProtoType *Proto =
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001107 OperatorNew->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001108 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00001109 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001110
Anders Carlsson28e94832010-05-03 02:07:56 +00001111 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001112 Proto, 1, PlaceArgs, NumPlaceArgs,
Anders Carlsson28e94832010-05-03 02:07:56 +00001113 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001114 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001115
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001116 NumPlaceArgs = AllPlaceArgs.size();
1117 if (NumPlaceArgs > 0)
1118 PlaceArgs = &AllPlaceArgs[0];
1119 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001120
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001121 bool Init = ConstructorLParen.isValid();
1122 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001123 CXXConstructorDecl *Constructor = 0;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001124 bool HadMultipleCandidates = false;
Sebastian Redlf53597f2009-03-15 17:47:39 +00001125 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
1126 unsigned NumConsArgs = ConstructorArgs.size();
John McCallca0408f2010-08-23 06:44:23 +00001127 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmana8ce9ec2009-11-08 22:15:39 +00001128
Anders Carlsson48c95012010-05-03 15:45:23 +00001129 // Array 'new' can't have any initializers.
Anders Carlsson55cbd6e2010-05-16 16:24:20 +00001130 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlsson48c95012010-05-03 15:45:23 +00001131 SourceRange InitRange(ConsArgs[0]->getLocStart(),
1132 ConsArgs[NumConsArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001133
Anders Carlsson48c95012010-05-03 15:45:23 +00001134 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1135 return ExprError();
1136 }
1137
Douglas Gregor99a2e602009-12-16 01:38:02 +00001138 if (!AllocType->isDependentType() &&
1139 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
1140 // C++0x [expr.new]p15:
1141 // A new-expression that creates an object of type T initializes that
1142 // object as follows:
1143 InitializationKind Kind
1144 // - If the new-initializer is omitted, the object is default-
1145 // initialized (8.5); if no initialization is performed,
1146 // the object has indeterminate value
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001147 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001148 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor99a2e602009-12-16 01:38:02 +00001149 // initialization rules of 8.5 for direct-initialization.
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001150 : InitializationKind::CreateDirect(TypeRange.getBegin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001151 ConstructorLParen,
Douglas Gregor99a2e602009-12-16 01:38:02 +00001152 ConstructorRParen);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001153
Douglas Gregor99a2e602009-12-16 01:38:02 +00001154 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00001155 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001156 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001157 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor99a2e602009-12-16 01:38:02 +00001158 move(ConstructorArgs));
1159 if (FullInit.isInvalid())
1160 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001161
1162 // FullInit is our initializer; walk through it to determine if it's a
Douglas Gregor99a2e602009-12-16 01:38:02 +00001163 // constructor call, which CXXNewExpr handles directly.
1164 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
1165 if (CXXBindTemporaryExpr *Binder
1166 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
1167 FullInitExpr = Binder->getSubExpr();
1168 if (CXXConstructExpr *Construct
1169 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
1170 Constructor = Construct->getConstructor();
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001171 HadMultipleCandidates = Construct->hadMultipleCandidates();
Douglas Gregor99a2e602009-12-16 01:38:02 +00001172 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
1173 AEnd = Construct->arg_end();
1174 A != AEnd; ++A)
John McCall3fa5cae2010-10-26 07:05:15 +00001175 ConvertedConstructorArgs.push_back(*A);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001176 } else {
1177 // Take the converted initializer.
1178 ConvertedConstructorArgs.push_back(FullInit.release());
1179 }
1180 } else {
1181 // No initialization required.
1182 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001183
Douglas Gregor99a2e602009-12-16 01:38:02 +00001184 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +00001185 NumConsArgs = ConvertedConstructorArgs.size();
1186 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001187 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001188
Douglas Gregor6d908702010-02-26 05:06:18 +00001189 // Mark the new and delete operators as referenced.
1190 if (OperatorNew)
1191 MarkDeclarationReferenced(StartLoc, OperatorNew);
1192 if (OperatorDelete)
1193 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1194
John McCall84ff0fc2011-07-13 20:12:57 +00001195 // C++0x [expr.new]p17:
1196 // If the new expression creates an array of objects of class type,
1197 // access and ambiguity control are done for the destructor.
1198 if (ArraySize && Constructor) {
1199 if (CXXDestructorDecl *dtor = LookupDestructor(Constructor->getParent())) {
1200 MarkDeclarationReferenced(StartLoc, dtor);
1201 CheckDestructorAccess(StartLoc, dtor,
1202 PDiag(diag::err_access_dtor)
1203 << Context.getBaseElementType(AllocType));
1204 }
1205 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001206
Sebastian Redlf53597f2009-03-15 17:47:39 +00001207 PlacementArgs.release();
1208 ConstructorArgs.release();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001209
Ted Kremenekad7fe862010-02-11 22:51:03 +00001210 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregor4bd40312010-07-13 15:54:32 +00001211 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001212 ArraySize, Constructor, Init,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001213 ConsArgs, NumConsArgs,
1214 HadMultipleCandidates,
1215 OperatorDelete,
John McCall6ec278d2011-01-27 09:37:56 +00001216 UsualArrayDeleteWantsSize,
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001217 ResultType, AllocTypeInfo,
1218 StartLoc,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001219 Init ? ConstructorRParen :
Chandler Carruth428edaf2010-10-25 08:47:36 +00001220 TypeRange.getEnd(),
1221 ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001222}
1223
1224/// CheckAllocatedType - Checks that a type is suitable as the allocated type
1225/// in a new-expression.
1226/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +00001227bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00001228 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001229 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1230 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +00001231 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001232 return Diag(Loc, diag::err_bad_new_type)
1233 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001234 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001235 return Diag(Loc, diag::err_bad_new_type)
1236 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001237 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +00001238 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001239 PDiag(diag::err_new_incomplete_type)
1240 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001241 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +00001242 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +00001243 diag::err_allocation_of_abstract_type))
1244 return true;
Douglas Gregora0750762010-10-06 16:00:31 +00001245 else if (AllocType->isVariablyModifiedType())
1246 return Diag(Loc, diag::err_variably_modified_new_type)
1247 << AllocType;
Douglas Gregor5666d362011-04-15 19:46:20 +00001248 else if (unsigned AddressSpace = AllocType.getAddressSpace())
1249 return Diag(Loc, diag::err_address_space_qualified_new)
1250 << AllocType.getUnqualifiedType() << AddressSpace;
John McCallf85e1932011-06-15 23:02:42 +00001251 else if (getLangOptions().ObjCAutoRefCount) {
1252 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
1253 QualType BaseAllocType = Context.getBaseElementType(AT);
1254 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1255 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001256 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001257 << BaseAllocType;
1258 }
1259 }
Douglas Gregor5666d362011-04-15 19:46:20 +00001260
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001261 return false;
1262}
1263
Douglas Gregor6d908702010-02-26 05:06:18 +00001264/// \brief Determine whether the given function is a non-placement
1265/// deallocation function.
1266static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1267 if (FD->isInvalidDecl())
1268 return false;
1269
1270 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1271 return Method->isUsualDeallocationFunction();
1272
1273 return ((FD->getOverloadedOperator() == OO_Delete ||
1274 FD->getOverloadedOperator() == OO_Array_Delete) &&
1275 FD->getNumParams() == 1);
1276}
1277
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001278/// FindAllocationFunctions - Finds the overloads of operator new and delete
1279/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001280bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1281 bool UseGlobal, QualType AllocType,
1282 bool IsArray, Expr **PlaceArgs,
1283 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001284 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +00001285 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001286 // --- Choosing an allocation function ---
1287 // C++ 5.3.4p8 - 14 & 18
1288 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1289 // in the scope of the allocated class.
1290 // 2) If an array size is given, look for operator new[], else look for
1291 // operator new.
1292 // 3) The first argument is always size_t. Append the arguments from the
1293 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001294
Chris Lattner5f9e2722011-07-23 10:55:15 +00001295 SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001296 // We don't care about the actual value of this argument.
1297 // FIXME: Should the Sema create the expression and embed it in the syntax
1298 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00001299 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001300 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssond67c4c32009-08-16 20:29:29 +00001301 Context.getSizeType(),
1302 SourceLocation());
1303 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001304 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1305
Douglas Gregor6d908702010-02-26 05:06:18 +00001306 // C++ [expr.new]p8:
1307 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001308 // function's name is operator new and the deallocation function's
Douglas Gregor6d908702010-02-26 05:06:18 +00001309 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001310 // type, the allocation function's name is operator new[] and the
1311 // deallocation function's name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001312 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1313 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +00001314 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1315 IsArray ? OO_Array_Delete : OO_Delete);
1316
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001317 QualType AllocElemType = Context.getBaseElementType(AllocType);
1318
1319 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +00001320 CXXRecordDecl *Record
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001321 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +00001322 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001323 AllocArgs.size(), Record, /*AllowMissing=*/true,
1324 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001325 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001326 }
1327 if (!OperatorNew) {
1328 // Didn't find a member overload. Look for a global one.
1329 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +00001330 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +00001331 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001332 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1333 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001334 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001335 }
1336
John McCall9c82afc2010-04-20 02:18:25 +00001337 // We don't need an operator delete if we're running under
1338 // -fno-exceptions.
1339 if (!getLangOptions().Exceptions) {
1340 OperatorDelete = 0;
1341 return false;
1342 }
1343
Anders Carlssond9583892009-05-31 20:26:12 +00001344 // FindAllocationOverload can change the passed in arguments, so we need to
1345 // copy them back.
1346 if (NumPlaceArgs > 0)
1347 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001348
Douglas Gregor6d908702010-02-26 05:06:18 +00001349 // C++ [expr.new]p19:
1350 //
1351 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001352 // deallocation function's name is looked up in the global
Douglas Gregor6d908702010-02-26 05:06:18 +00001353 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001354 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6d908702010-02-26 05:06:18 +00001355 // the scope of T. If this lookup fails to find the name, or if
1356 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001357 // deallocation function's name is looked up in the global scope.
Douglas Gregor6d908702010-02-26 05:06:18 +00001358 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001359 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001360 CXXRecordDecl *RD
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001361 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6d908702010-02-26 05:06:18 +00001362 LookupQualifiedName(FoundDelete, RD);
1363 }
John McCall90c8c572010-03-18 08:19:33 +00001364 if (FoundDelete.isAmbiguous())
1365 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +00001366
1367 if (FoundDelete.empty()) {
1368 DeclareGlobalNewDelete();
1369 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1370 }
1371
1372 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +00001373
Chris Lattner5f9e2722011-07-23 10:55:15 +00001374 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCall9aa472c2010-03-19 07:35:19 +00001375
John McCalledeb6c92010-09-14 21:34:24 +00001376 // Whether we're looking for a placement operator delete is dictated
1377 // by whether we selected a placement operator new, not by whether
1378 // we had explicit placement arguments. This matters for things like
1379 // struct A { void *operator new(size_t, int = 0); ... };
1380 // A *a = new A()
1381 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1382
1383 if (isPlacementNew) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001384 // C++ [expr.new]p20:
1385 // A declaration of a placement deallocation function matches the
1386 // declaration of a placement allocation function if it has the
1387 // same number of parameters and, after parameter transformations
1388 // (8.3.5), all parameter types except the first are
1389 // identical. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001390 //
Douglas Gregor6d908702010-02-26 05:06:18 +00001391 // To perform this comparison, we compute the function type that
1392 // the deallocation function should have, and use that type both
1393 // for template argument deduction and for comparison purposes.
John McCalle23cf432010-12-14 08:05:40 +00001394 //
1395 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6d908702010-02-26 05:06:18 +00001396 QualType ExpectedFunctionType;
1397 {
1398 const FunctionProtoType *Proto
1399 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00001400
Chris Lattner5f9e2722011-07-23 10:55:15 +00001401 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001402 ArgTypes.push_back(Context.VoidPtrTy);
Douglas Gregor6d908702010-02-26 05:06:18 +00001403 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1404 ArgTypes.push_back(Proto->getArgType(I));
1405
John McCalle23cf432010-12-14 08:05:40 +00001406 FunctionProtoType::ExtProtoInfo EPI;
1407 EPI.Variadic = Proto->isVariadic();
1408
Douglas Gregor6d908702010-02-26 05:06:18 +00001409 ExpectedFunctionType
1410 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
John McCalle23cf432010-12-14 08:05:40 +00001411 ArgTypes.size(), EPI);
Douglas Gregor6d908702010-02-26 05:06:18 +00001412 }
1413
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001414 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001415 DEnd = FoundDelete.end();
1416 D != DEnd; ++D) {
1417 FunctionDecl *Fn = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001418 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6d908702010-02-26 05:06:18 +00001419 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1420 // Perform template argument deduction to try to match the
1421 // expected function type.
1422 TemplateDeductionInfo Info(Context, StartLoc);
1423 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1424 continue;
1425 } else
1426 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1427
1428 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001429 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001430 }
1431 } else {
1432 // C++ [expr.new]p20:
1433 // [...] Any non-placement deallocation function matches a
1434 // non-placement allocation function. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001435 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001436 DEnd = FoundDelete.end();
1437 D != DEnd; ++D) {
1438 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1439 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001440 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001441 }
1442 }
1443
1444 // C++ [expr.new]p20:
1445 // [...] If the lookup finds a single matching deallocation
1446 // function, that function will be called; otherwise, no
1447 // deallocation function will be called.
1448 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001449 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001450
1451 // C++0x [expr.new]p20:
1452 // If the lookup finds the two-parameter form of a usual
1453 // deallocation function (3.7.4.2) and that function, considered
1454 // as a placement deallocation function, would have been
1455 // selected as a match for the allocation function, the program
1456 // is ill-formed.
1457 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1458 isNonPlacementDeallocationFunction(OperatorDelete)) {
1459 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001460 << SourceRange(PlaceArgs[0]->getLocStart(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001461 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1462 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1463 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001464 } else {
1465 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001466 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001467 }
1468 }
1469
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001470 return false;
1471}
1472
Sebastian Redl7f662392008-12-04 22:20:51 +00001473/// FindAllocationOverload - Find an fitting overload for the allocation
1474/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001475bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1476 DeclarationName Name, Expr** Args,
1477 unsigned NumArgs, DeclContext *Ctx,
Sean Hunt2be7e902011-05-12 22:46:29 +00001478 bool AllowMissing, FunctionDecl *&Operator,
1479 bool Diagnose) {
John McCalla24dc2e2009-11-17 02:14:36 +00001480 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1481 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001482 if (R.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001483 if (AllowMissing || !Diagnose)
Sebastian Redl7f662392008-12-04 22:20:51 +00001484 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001485 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001486 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001487 }
1488
John McCall90c8c572010-03-18 08:19:33 +00001489 if (R.isAmbiguous())
1490 return true;
1491
1492 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001493
John McCall5769d612010-02-08 23:07:23 +00001494 OverloadCandidateSet Candidates(StartLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001495 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001496 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001497 // Even member operator new/delete are implicitly treated as
1498 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001499 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001500
John McCall9aa472c2010-03-19 07:35:19 +00001501 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1502 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001503 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1504 Candidates,
1505 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001506 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001507 }
1508
John McCall9aa472c2010-03-19 07:35:19 +00001509 FunctionDecl *Fn = cast<FunctionDecl>(D);
1510 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001511 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001512 }
1513
1514 // Do the resolution.
1515 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00001516 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001517 case OR_Success: {
1518 // Got one!
1519 FunctionDecl *FnDecl = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00001520 MarkDeclarationReferenced(StartLoc, FnDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001521 // The first argument is size_t, and the first parameter must be size_t,
1522 // too. This is checked on declaration and can be assumed. (It can't be
1523 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001524 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001525 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1526 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001527 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1528 FnDecl->getParamDecl(i));
1529
1530 if (!Diagnose && !CanPerformCopyInitialization(Entity, Owned(Args[i])))
1531 return true;
1532
John McCall60d7b3a2010-08-24 06:29:42 +00001533 ExprResult Result
Sean Hunt2be7e902011-05-12 22:46:29 +00001534 = PerformCopyInitialization(Entity, SourceLocation(), Owned(Args[i]));
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001535 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001536 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001537
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001538 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001539 }
1540 Operator = FnDecl;
Sean Hunt2be7e902011-05-12 22:46:29 +00001541 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl,
1542 Diagnose);
Sebastian Redl7f662392008-12-04 22:20:51 +00001543 return false;
1544 }
1545
1546 case OR_No_Viable_Function:
Chandler Carruth361d3802011-06-08 10:26:03 +00001547 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001548 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1549 << Name << Range;
Chandler Carruth361d3802011-06-08 10:26:03 +00001550 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1551 }
Sebastian Redl7f662392008-12-04 22:20:51 +00001552 return true;
1553
1554 case OR_Ambiguous:
Chandler Carruth361d3802011-06-08 10:26:03 +00001555 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001556 Diag(StartLoc, diag::err_ovl_ambiguous_call)
1557 << Name << Range;
Chandler Carruth361d3802011-06-08 10:26:03 +00001558 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
1559 }
Sebastian Redl7f662392008-12-04 22:20:51 +00001560 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001561
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001562 case OR_Deleted: {
Chandler Carruth361d3802011-06-08 10:26:03 +00001563 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001564 Diag(StartLoc, diag::err_ovl_deleted_call)
1565 << Best->Function->isDeleted()
1566 << Name
1567 << getDeletedOrUnavailableSuffix(Best->Function)
1568 << Range;
Chandler Carruth361d3802011-06-08 10:26:03 +00001569 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1570 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001571 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001572 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001573 }
David Blaikieb219cfc2011-09-23 05:06:16 +00001574 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Sebastian Redl7f662392008-12-04 22:20:51 +00001575}
1576
1577
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001578/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1579/// delete. These are:
1580/// @code
Sebastian Redl8999fe12011-03-14 18:08:30 +00001581/// // C++03:
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001582/// void* operator new(std::size_t) throw(std::bad_alloc);
1583/// void* operator new[](std::size_t) throw(std::bad_alloc);
1584/// void operator delete(void *) throw();
1585/// void operator delete[](void *) throw();
Sebastian Redl8999fe12011-03-14 18:08:30 +00001586/// // C++0x:
1587/// void* operator new(std::size_t);
1588/// void* operator new[](std::size_t);
1589/// void operator delete(void *);
1590/// void operator delete[](void *);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001591/// @endcode
Sebastian Redl8999fe12011-03-14 18:08:30 +00001592/// C++0x operator delete is implicitly noexcept.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001593/// Note that the placement and nothrow forms of new are *not* implicitly
1594/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001595void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001596 if (GlobalNewDeleteDeclared)
1597 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001598
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001599 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001600 // [...] The following allocation and deallocation functions (18.4) are
1601 // implicitly declared in global scope in each translation unit of a
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001602 // program
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001603 //
Sebastian Redl8999fe12011-03-14 18:08:30 +00001604 // C++03:
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001605 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001606 // void* operator new[](std::size_t) throw(std::bad_alloc);
1607 // void operator delete(void*) throw();
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001608 // void operator delete[](void*) throw();
Sebastian Redl8999fe12011-03-14 18:08:30 +00001609 // C++0x:
1610 // void* operator new(std::size_t);
1611 // void* operator new[](std::size_t);
1612 // void operator delete(void*);
1613 // void operator delete[](void*);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001614 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001615 // These implicit declarations introduce only the function names operator
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001616 // new, operator new[], operator delete, operator delete[].
1617 //
1618 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1619 // "std" or "bad_alloc" as necessary to form the exception specification.
1620 // However, we do not make these implicit declarations visible to name
1621 // lookup.
Sebastian Redl8999fe12011-03-14 18:08:30 +00001622 // Note that the C++0x versions of operator delete are deallocation functions,
1623 // and thus are implicitly noexcept.
1624 if (!StdBadAlloc && !getLangOptions().CPlusPlus0x) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001625 // The "std::bad_alloc" class has not yet been declared, so build it
1626 // implicitly.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001627 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1628 getOrCreateStdNamespace(),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001629 SourceLocation(), SourceLocation(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001630 &PP.getIdentifierTable().get("bad_alloc"),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001631 0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001632 getStdBadAlloc()->setImplicit(true);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001633 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001634
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001635 GlobalNewDeleteDeclared = true;
1636
1637 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1638 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001639 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001640
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001641 DeclareGlobalAllocationFunction(
1642 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001643 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001644 DeclareGlobalAllocationFunction(
1645 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001646 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001647 DeclareGlobalAllocationFunction(
1648 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1649 Context.VoidTy, VoidPtr);
1650 DeclareGlobalAllocationFunction(
1651 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1652 Context.VoidTy, VoidPtr);
1653}
1654
1655/// DeclareGlobalAllocationFunction - Declares a single implicit global
1656/// allocation function if it doesn't already exist.
1657void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001658 QualType Return, QualType Argument,
1659 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001660 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1661
1662 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001663 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001664 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001665 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001666 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001667 // Only look at non-template functions, as it is the predefined,
1668 // non-templated allocation function we are trying to declare here.
1669 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1670 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001671 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001672 Func->getParamDecl(0)->getType().getUnqualifiedType());
1673 // FIXME: Do we need to check for default arguments here?
Douglas Gregor7b868622010-08-18 15:06:25 +00001674 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1675 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00001676 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001677 return;
Douglas Gregor7b868622010-08-18 15:06:25 +00001678 }
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001679 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001680 }
1681 }
1682
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001683 QualType BadAllocType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001684 bool HasBadAllocExceptionSpec
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001685 = (Name.getCXXOverloadedOperator() == OO_New ||
1686 Name.getCXXOverloadedOperator() == OO_Array_New);
Sebastian Redl8999fe12011-03-14 18:08:30 +00001687 if (HasBadAllocExceptionSpec && !getLangOptions().CPlusPlus0x) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001688 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001689 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001690 }
John McCalle23cf432010-12-14 08:05:40 +00001691
1692 FunctionProtoType::ExtProtoInfo EPI;
John McCalle23cf432010-12-14 08:05:40 +00001693 if (HasBadAllocExceptionSpec) {
Sebastian Redl8999fe12011-03-14 18:08:30 +00001694 if (!getLangOptions().CPlusPlus0x) {
1695 EPI.ExceptionSpecType = EST_Dynamic;
1696 EPI.NumExceptions = 1;
1697 EPI.Exceptions = &BadAllocType;
1698 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00001699 } else {
Sebastian Redl8999fe12011-03-14 18:08:30 +00001700 EPI.ExceptionSpecType = getLangOptions().CPlusPlus0x ?
1701 EST_BasicNoexcept : EST_DynamicNone;
John McCalle23cf432010-12-14 08:05:40 +00001702 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001703
John McCalle23cf432010-12-14 08:05:40 +00001704 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001705 FunctionDecl *Alloc =
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001706 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
1707 SourceLocation(), Name,
John McCalld931b082010-08-26 03:08:43 +00001708 FnType, /*TInfo=*/0, SC_None,
1709 SC_None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001710 Alloc->setImplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001711
Nuno Lopesfc284482009-12-16 16:59:22 +00001712 if (AddMallocAttr)
Sean Huntcf807c42010-08-18 23:23:40 +00001713 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001714
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001715 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001716 SourceLocation(), 0,
1717 Argument, /*TInfo=*/0,
1718 SC_None, SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00001719 Alloc->setParams(Param);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001720
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001721 // FIXME: Also add this declaration to the IdentifierResolver, but
1722 // make sure it is at the end of the chain to coincide with the
1723 // global scope.
John McCall5f1e0942010-08-24 08:50:51 +00001724 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001725}
1726
Anders Carlsson78f74552009-11-15 18:45:20 +00001727bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1728 DeclarationName Name,
Sean Hunt2be7e902011-05-12 22:46:29 +00001729 FunctionDecl* &Operator, bool Diagnose) {
John McCalla24dc2e2009-11-17 02:14:36 +00001730 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001731 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001732 LookupQualifiedName(Found, RD);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001733
John McCalla24dc2e2009-11-17 02:14:36 +00001734 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001735 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001736
Chandler Carruth23893242010-06-28 00:30:51 +00001737 Found.suppressDiagnostics();
1738
Chris Lattner5f9e2722011-07-23 10:55:15 +00001739 SmallVector<DeclAccessPair,4> Matches;
Anders Carlsson78f74552009-11-15 18:45:20 +00001740 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1741 F != FEnd; ++F) {
Chandler Carruth09556fd2010-08-08 07:04:00 +00001742 NamedDecl *ND = (*F)->getUnderlyingDecl();
1743
1744 // Ignore template operator delete members from the check for a usual
1745 // deallocation function.
1746 if (isa<FunctionTemplateDecl>(ND))
1747 continue;
1748
1749 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall046a7462010-08-04 00:31:26 +00001750 Matches.push_back(F.getPair());
1751 }
1752
1753 // There's exactly one suitable operator; pick it.
1754 if (Matches.size() == 1) {
1755 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
Sean Hunt2be7e902011-05-12 22:46:29 +00001756
1757 if (Operator->isDeleted()) {
1758 if (Diagnose) {
1759 Diag(StartLoc, diag::err_deleted_function_use);
1760 Diag(Operator->getLocation(), diag::note_unavailable_here) << true;
1761 }
1762 return true;
1763 }
1764
John McCall046a7462010-08-04 00:31:26 +00001765 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Sean Hunt2be7e902011-05-12 22:46:29 +00001766 Matches[0], Diagnose);
John McCall046a7462010-08-04 00:31:26 +00001767 return false;
1768
1769 // We found multiple suitable operators; complain about the ambiguity.
1770 } else if (!Matches.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001771 if (Diagnose) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00001772 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1773 << Name << RD;
John McCall046a7462010-08-04 00:31:26 +00001774
Chris Lattner5f9e2722011-07-23 10:55:15 +00001775 for (SmallVectorImpl<DeclAccessPair>::iterator
Sean Huntcb45a0f2011-05-12 22:46:25 +00001776 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1777 Diag((*F)->getUnderlyingDecl()->getLocation(),
1778 diag::note_member_declared_here) << Name;
1779 }
John McCall046a7462010-08-04 00:31:26 +00001780 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001781 }
1782
1783 // We did find operator delete/operator delete[] declarations, but
1784 // none of them were suitable.
1785 if (!Found.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001786 if (Diagnose) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00001787 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1788 << Name << RD;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001789
Sean Huntcb45a0f2011-05-12 22:46:25 +00001790 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1791 F != FEnd; ++F)
1792 Diag((*F)->getUnderlyingDecl()->getLocation(),
1793 diag::note_member_declared_here) << Name;
1794 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001795 return true;
1796 }
1797
1798 // Look for a global declaration.
1799 DeclareGlobalNewDelete();
1800 DeclContext *TUDecl = Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001801
Anders Carlsson78f74552009-11-15 18:45:20 +00001802 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1803 Expr* DeallocArgs[1];
1804 DeallocArgs[0] = &Null;
1805 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
Sean Hunt2be7e902011-05-12 22:46:29 +00001806 DeallocArgs, 1, TUDecl, !Diagnose,
1807 Operator, Diagnose))
Anders Carlsson78f74552009-11-15 18:45:20 +00001808 return true;
1809
1810 assert(Operator && "Did not find a deallocation function!");
1811 return false;
1812}
1813
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001814/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1815/// @code ::delete ptr; @endcode
1816/// or
1817/// @code delete [] ptr; @endcode
John McCall60d7b3a2010-08-24 06:29:42 +00001818ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001819Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley429bb272011-04-08 18:41:53 +00001820 bool ArrayForm, Expr *ExE) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001821 // C++ [expr.delete]p1:
1822 // The operand shall have a pointer type, or a class type having a single
1823 // conversion function to a pointer type. The result has type void.
1824 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001825 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1826
John Wiegley429bb272011-04-08 18:41:53 +00001827 ExprResult Ex = Owned(ExE);
Anders Carlssond67c4c32009-08-16 20:29:29 +00001828 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001829 bool ArrayFormAsWritten = ArrayForm;
John McCall6ec278d2011-01-27 09:37:56 +00001830 bool UsualArrayDeleteWantsSize = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001831
John Wiegley429bb272011-04-08 18:41:53 +00001832 if (!Ex.get()->isTypeDependent()) {
1833 QualType Type = Ex.get()->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001834
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001835 if (const RecordType *Record = Type->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001836 if (RequireCompleteType(StartLoc, Type,
Douglas Gregor254a9422010-07-29 14:44:35 +00001837 PDiag(diag::err_delete_incomplete_class_type)))
1838 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001839
Chris Lattner5f9e2722011-07-23 10:55:15 +00001840 SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
John McCall32daa422010-03-31 01:36:47 +00001841
Fariborz Jahanian53462782009-09-11 21:44:33 +00001842 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001843 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001844 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001845 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001846 NamedDecl *D = I.getDecl();
1847 if (isa<UsingShadowDecl>(D))
1848 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1849
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001850 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001851 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001852 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001853
John McCall32daa422010-03-31 01:36:47 +00001854 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001855
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001856 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1857 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedman13578692010-08-05 02:49:48 +00001858 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001859 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001860 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001861 if (ObjectPtrConversions.size() == 1) {
1862 // We have a single conversion to a pointer-to-object type. Perform
1863 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001864 // TODO: don't redo the conversion calculation.
John Wiegley429bb272011-04-08 18:41:53 +00001865 ExprResult Res =
1866 PerformImplicitConversion(Ex.get(),
John McCall32daa422010-03-31 01:36:47 +00001867 ObjectPtrConversions.front()->getConversionType(),
John Wiegley429bb272011-04-08 18:41:53 +00001868 AA_Converting);
1869 if (Res.isUsable()) {
1870 Ex = move(Res);
1871 Type = Ex.get()->getType();
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001872 }
1873 }
1874 else if (ObjectPtrConversions.size() > 1) {
1875 Diag(StartLoc, diag::err_ambiguous_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001876 << Type << Ex.get()->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001877 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1878 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001879 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001880 }
Sebastian Redl28507842009-02-26 14:39:58 +00001881 }
1882
Sebastian Redlf53597f2009-03-15 17:47:39 +00001883 if (!Type->isPointerType())
1884 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001885 << Type << Ex.get()->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001886
Ted Kremenek6217b802009-07-29 21:53:49 +00001887 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmane52c9142011-07-26 22:25:31 +00001888 QualType PointeeElem = Context.getBaseElementType(Pointee);
1889
1890 if (unsigned AddressSpace = Pointee.getAddressSpace())
1891 return Diag(Ex.get()->getLocStart(),
1892 diag::err_address_space_qualified_delete)
1893 << Pointee.getUnqualifiedType() << AddressSpace;
1894
1895 CXXRecordDecl *PointeeRD = 0;
Douglas Gregor94a61572010-05-24 17:01:56 +00001896 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001897 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregor94a61572010-05-24 17:01:56 +00001898 // effectively bans deletion of "void*". However, most compilers support
1899 // this, so we treat it as a warning unless we're in a SFINAE context.
1900 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001901 << Type << Ex.get()->getSourceRange();
Eli Friedmane52c9142011-07-26 22:25:31 +00001902 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00001903 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001904 << Type << Ex.get()->getSourceRange());
Eli Friedmane52c9142011-07-26 22:25:31 +00001905 } else if (!Pointee->isDependentType()) {
1906 if (!RequireCompleteType(StartLoc, Pointee,
1907 PDiag(diag::warn_delete_incomplete)
1908 << Ex.get()->getSourceRange())) {
1909 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
1910 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
1911 }
1912 }
1913
Abramo Bagnara30bb4202011-11-16 15:42:13 +00001914 // Perform lvalue-to-rvalue cast, if needed.
1915 Ex = DefaultLvalueConversion(Ex.take());
1916
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001917 // C++ [expr.delete]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001918 // [Note: a pointer to a const type can be the operand of a
1919 // delete-expression; it is not necessary to cast away the constness
1920 // (5.2.11) of the pointer expression before it is used as the operand
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001921 // of the delete-expression. ]
John McCallf85e1932011-06-15 23:02:42 +00001922 if (!Context.hasSameType(Ex.get()->getType(), Context.VoidPtrTy))
Abramo Bagnara30bb4202011-11-16 15:42:13 +00001923 Ex = Owned(ImplicitCastExpr::Create(Context, Context.VoidPtrTy,
1924 CK_BitCast, Ex.take(), 0, VK_RValue));
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001925
1926 if (Pointee->isArrayType() && !ArrayForm) {
1927 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley429bb272011-04-08 18:41:53 +00001928 << Type << Ex.get()->getSourceRange()
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001929 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1930 ArrayForm = true;
1931 }
1932
Anders Carlssond67c4c32009-08-16 20:29:29 +00001933 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1934 ArrayForm ? OO_Array_Delete : OO_Delete);
1935
Eli Friedmane52c9142011-07-26 22:25:31 +00001936 if (PointeeRD) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001937 if (!UseGlobal &&
Eli Friedmane52c9142011-07-26 22:25:31 +00001938 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
1939 OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001940 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001941
John McCall6ec278d2011-01-27 09:37:56 +00001942 // If we're allocating an array of records, check whether the
1943 // usual operator delete[] has a size_t parameter.
1944 if (ArrayForm) {
1945 // If the user specifically asked to use the global allocator,
1946 // we'll need to do the lookup into the class.
1947 if (UseGlobal)
1948 UsualArrayDeleteWantsSize =
1949 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
1950
1951 // Otherwise, the usual operator delete[] should be the
1952 // function we just found.
1953 else if (isa<CXXMethodDecl>(OperatorDelete))
1954 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
1955 }
1956
Eli Friedmane52c9142011-07-26 22:25:31 +00001957 if (!PointeeRD->hasTrivialDestructor())
1958 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001959 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001960 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor9b623632010-10-12 23:32:35 +00001961 DiagnoseUseOfDecl(Dtor, StartLoc);
1962 }
Argyrios Kyrtzidis6f0074a2011-05-24 19:53:26 +00001963
1964 // C++ [expr.delete]p3:
1965 // In the first alternative (delete object), if the static type of the
1966 // object to be deleted is different from its dynamic type, the static
1967 // type shall be a base class of the dynamic type of the object to be
1968 // deleted and the static type shall have a virtual destructor or the
1969 // behavior is undefined.
1970 //
1971 // Note: a final class cannot be derived from, no issue there
Eli Friedmanef8c79c2011-07-26 23:27:24 +00001972 if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) {
Eli Friedmane52c9142011-07-26 22:25:31 +00001973 CXXDestructorDecl *dtor = PointeeRD->getDestructor();
Eli Friedmanef8c79c2011-07-26 23:27:24 +00001974 if (dtor && !dtor->isVirtual()) {
1975 if (PointeeRD->isAbstract()) {
1976 // If the class is abstract, we warn by default, because we're
1977 // sure the code has undefined behavior.
1978 Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor)
1979 << PointeeElem;
1980 } else if (!ArrayForm) {
1981 // Otherwise, if this is not an array delete, it's a bit suspect,
1982 // but not necessarily wrong.
1983 Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
1984 }
1985 }
Argyrios Kyrtzidis6f0074a2011-05-24 19:53:26 +00001986 }
John McCallf85e1932011-06-15 23:02:42 +00001987
1988 } else if (getLangOptions().ObjCAutoRefCount &&
1989 PointeeElem->isObjCLifetimeType() &&
1990 (PointeeElem.getObjCLifetime() == Qualifiers::OCL_Strong ||
1991 PointeeElem.getObjCLifetime() == Qualifiers::OCL_Weak) &&
1992 ArrayForm) {
1993 Diag(StartLoc, diag::warn_err_new_delete_object_array)
1994 << 1 << PointeeElem;
Anders Carlssond67c4c32009-08-16 20:29:29 +00001995 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001996
Anders Carlssond67c4c32009-08-16 20:29:29 +00001997 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001998 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001999 DeclareGlobalNewDelete();
2000 DeclContext *TUDecl = Context.getTranslationUnitDecl();
John Wiegley429bb272011-04-08 18:41:53 +00002001 Expr *Arg = Ex.get();
Mike Stump1eb44332009-09-09 15:08:12 +00002002 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
John Wiegley429bb272011-04-08 18:41:53 +00002003 &Arg, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00002004 OperatorDelete))
2005 return ExprError();
2006 }
Mike Stump1eb44332009-09-09 15:08:12 +00002007
John McCall9c82afc2010-04-20 02:18:25 +00002008 MarkDeclarationReferenced(StartLoc, OperatorDelete);
John McCall6ec278d2011-01-27 09:37:56 +00002009
Douglas Gregord880f522011-02-01 15:50:11 +00002010 // Check access and ambiguity of operator delete and destructor.
Eli Friedmane52c9142011-07-26 22:25:31 +00002011 if (PointeeRD) {
2012 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
John Wiegley429bb272011-04-08 18:41:53 +00002013 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregord880f522011-02-01 15:50:11 +00002014 PDiag(diag::err_access_dtor) << PointeeElem);
2015 }
2016 }
2017
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002018 }
2019
Sebastian Redlf53597f2009-03-15 17:47:39 +00002020 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
John McCall6ec278d2011-01-27 09:37:56 +00002021 ArrayFormAsWritten,
2022 UsualArrayDeleteWantsSize,
John Wiegley429bb272011-04-08 18:41:53 +00002023 OperatorDelete, Ex.take(), StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002024}
2025
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002026/// \brief Check the use of the given variable as a C++ condition in an if,
2027/// while, do-while, or switch statement.
John McCall60d7b3a2010-08-24 06:29:42 +00002028ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCallf89e55a2010-11-18 06:31:45 +00002029 SourceLocation StmtLoc,
2030 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002031 QualType T = ConditionVar->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002032
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002033 // C++ [stmt.select]p2:
2034 // The declarator shall not specify a function or an array.
2035 if (T->isFunctionType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002036 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002037 diag::err_invalid_use_of_function_type)
2038 << ConditionVar->getSourceRange());
2039 else if (T->isArrayType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002040 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002041 diag::err_invalid_use_of_array_type)
2042 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00002043
John Wiegley429bb272011-04-08 18:41:53 +00002044 ExprResult Condition =
2045 Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
Douglas Gregor40d96a62011-02-28 21:54:11 +00002046 ConditionVar,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002047 ConditionVar->getLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00002048 ConditionVar->getType().getNonReferenceType(),
John Wiegley429bb272011-04-08 18:41:53 +00002049 VK_LValue));
2050 if (ConvertToBoolean) {
2051 Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
2052 if (Condition.isInvalid())
2053 return ExprError();
2054 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002055
John Wiegley429bb272011-04-08 18:41:53 +00002056 return move(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002057}
2058
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002059/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
John Wiegley429bb272011-04-08 18:41:53 +00002060ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002061 // C++ 6.4p4:
2062 // The value of a condition that is an initialized declaration in a statement
2063 // other than a switch statement is the value of the declared variable
2064 // implicitly converted to type bool. If that conversion is ill-formed, the
2065 // program is ill-formed.
2066 // The value of a condition that is an expression is the value of the
2067 // expression, implicitly converted to bool.
2068 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002069 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002070}
Douglas Gregor77a52232008-09-12 00:47:35 +00002071
2072/// Helper function to determine whether this is the (deprecated) C++
2073/// conversion from a string literal to a pointer to non-const char or
2074/// non-const wchar_t (for narrow and wide string literals,
2075/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00002076bool
Douglas Gregor77a52232008-09-12 00:47:35 +00002077Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
2078 // Look inside the implicit cast, if it exists.
2079 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
2080 From = Cast->getSubExpr();
2081
2082 // A string literal (2.13.4) that is not a wide string literal can
2083 // be converted to an rvalue of type "pointer to char"; a wide
2084 // string literal can be converted to an rvalue of type "pointer
2085 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00002086 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00002087 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00002088 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00002089 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00002090 // This conversion is considered only when there is an
2091 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregor5cee1192011-07-27 05:40:30 +00002092 if (!ToPtrType->getPointeeType().hasQualifiers()) {
2093 switch (StrLit->getKind()) {
2094 case StringLiteral::UTF8:
2095 case StringLiteral::UTF16:
2096 case StringLiteral::UTF32:
2097 // We don't allow UTF literals to be implicitly converted
2098 break;
2099 case StringLiteral::Ascii:
2100 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
2101 ToPointeeType->getKind() == BuiltinType::Char_S);
2102 case StringLiteral::Wide:
2103 return ToPointeeType->isWideCharType();
2104 }
2105 }
Douglas Gregor77a52232008-09-12 00:47:35 +00002106 }
2107
2108 return false;
2109}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002110
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002111static ExprResult BuildCXXCastArgument(Sema &S,
John McCall2de56d12010-08-25 11:45:40 +00002112 SourceLocation CastLoc,
2113 QualType Ty,
2114 CastKind Kind,
2115 CXXMethodDecl *Method,
John McCallca82a822011-09-21 08:36:56 +00002116 DeclAccessPair FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002117 bool HadMultipleCandidates,
John McCall2de56d12010-08-25 11:45:40 +00002118 Expr *From) {
Douglas Gregorba70ab62010-04-16 22:17:36 +00002119 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002120 default: llvm_unreachable("Unhandled cast kind!");
John McCall2de56d12010-08-25 11:45:40 +00002121 case CK_ConstructorConversion: {
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002122 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
John McCallca0408f2010-08-23 06:44:23 +00002123 ASTOwningVector<Expr*> ConstructorArgs(S);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002124
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002125 if (S.CompleteConstructorCall(Constructor,
John McCallf312b1e2010-08-26 23:41:50 +00002126 MultiExprArg(&From, 1),
Douglas Gregorba70ab62010-04-16 22:17:36 +00002127 CastLoc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00002128 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002129
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002130 S.CheckConstructorAccess(CastLoc, Constructor, Constructor->getAccess(),
2131 S.PDiag(diag::err_access_ctor));
2132
2133 ExprResult Result
2134 = S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2135 move_arg(ConstructorArgs),
2136 HadMultipleCandidates, /*ZeroInit*/ false,
2137 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregorba70ab62010-04-16 22:17:36 +00002138 if (Result.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00002139 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002140
Douglas Gregorba70ab62010-04-16 22:17:36 +00002141 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
2142 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002143
John McCall2de56d12010-08-25 11:45:40 +00002144 case CK_UserDefinedConversion: {
Douglas Gregorba70ab62010-04-16 22:17:36 +00002145 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002146
Douglas Gregorba70ab62010-04-16 22:17:36 +00002147 // Create an implicit call expr that calls it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002148 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method,
2149 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00002150 if (Result.isInvalid())
2151 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00002152 // Record usage of conversion in an implicit cast.
2153 Result = S.Owned(ImplicitCastExpr::Create(S.Context,
2154 Result.get()->getType(),
2155 CK_UserDefinedConversion,
2156 Result.get(), 0,
2157 Result.get()->getValueKind()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002158
John McCallca82a822011-09-21 08:36:56 +00002159 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ 0, FoundDecl);
2160
Douglas Gregorf2ae5262011-01-20 00:18:04 +00002161 return S.MaybeBindToTemporary(Result.get());
Douglas Gregorba70ab62010-04-16 22:17:36 +00002162 }
2163 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002164}
Douglas Gregorba70ab62010-04-16 22:17:36 +00002165
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002166/// PerformImplicitConversion - Perform an implicit conversion of the
2167/// expression From to the type ToType using the pre-computed implicit
John Wiegley429bb272011-04-08 18:41:53 +00002168/// conversion sequence ICS. Returns the converted
Douglas Gregor68647482009-12-16 03:45:30 +00002169/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002170/// used in the error message.
John Wiegley429bb272011-04-08 18:41:53 +00002171ExprResult
2172Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002173 const ImplicitConversionSequence &ICS,
John McCallf85e1932011-06-15 23:02:42 +00002174 AssignmentAction Action,
2175 CheckedConversionKind CCK) {
John McCall1d318332010-01-12 00:44:57 +00002176 switch (ICS.getKind()) {
John Wiegley429bb272011-04-08 18:41:53 +00002177 case ImplicitConversionSequence::StandardConversion: {
Richard Smithc8d7f582011-11-29 22:48:16 +00002178 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
2179 Action, CCK);
John Wiegley429bb272011-04-08 18:41:53 +00002180 if (Res.isInvalid())
2181 return ExprError();
2182 From = Res.take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002183 break;
John Wiegley429bb272011-04-08 18:41:53 +00002184 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002185
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002186 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002187
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00002188 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCalldaa8e4e2010-11-15 09:13:47 +00002189 CastKind CastKind;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002190 QualType BeforeToType;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00002191 assert(FD && "FIXME: aggregate initialization from init list");
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002192 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCall2de56d12010-08-25 11:45:40 +00002193 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002194
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002195 // If the user-defined conversion is specified by a conversion function,
2196 // the initial standard conversion sequence converts the source type to
2197 // the implicit object parameter of the conversion function.
2198 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCall9ec94452010-12-04 09:57:16 +00002199 } else {
2200 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCall2de56d12010-08-25 11:45:40 +00002201 CastKind = CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002202 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00002203 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002204 // If the user-defined conversion is specified by a constructor, the
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002205 // initial standard conversion sequence converts the source type to the
2206 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00002207 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
2208 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002209 }
Douglas Gregora3998bd2010-12-02 21:47:04 +00002210 // Watch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00002211 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley429bb272011-04-08 18:41:53 +00002212 ExprResult Res =
Richard Smithc8d7f582011-11-29 22:48:16 +00002213 PerformImplicitConversion(From, BeforeToType,
2214 ICS.UserDefined.Before, AA_Converting,
2215 CCK);
John Wiegley429bb272011-04-08 18:41:53 +00002216 if (Res.isInvalid())
2217 return ExprError();
2218 From = Res.take();
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002219 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002220
2221 ExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00002222 = BuildCXXCastArgument(*this,
2223 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00002224 ToType.getNonReferenceType(),
Douglas Gregor83eecbe2011-01-20 01:32:05 +00002225 CastKind, cast<CXXMethodDecl>(FD),
2226 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002227 ICS.UserDefined.HadMultipleCandidates,
John McCall9ae2f072010-08-23 23:25:46 +00002228 From);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002229
2230 if (CastArg.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00002231 return ExprError();
Eli Friedmand8889622009-11-27 04:41:50 +00002232
John Wiegley429bb272011-04-08 18:41:53 +00002233 From = CastArg.take();
Eli Friedmand8889622009-11-27 04:41:50 +00002234
Richard Smithc8d7f582011-11-29 22:48:16 +00002235 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
2236 AA_Converting, CCK);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00002237 }
John McCall1d318332010-01-12 00:44:57 +00002238
2239 case ImplicitConversionSequence::AmbiguousConversion:
John McCall120d63c2010-08-24 20:38:10 +00002240 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall1d318332010-01-12 00:44:57 +00002241 PDiag(diag::err_typecheck_ambiguous_condition)
2242 << From->getSourceRange());
John Wiegley429bb272011-04-08 18:41:53 +00002243 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002244
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002245 case ImplicitConversionSequence::EllipsisConversion:
David Blaikieb219cfc2011-09-23 05:06:16 +00002246 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002247
2248 case ImplicitConversionSequence::BadConversion:
John Wiegley429bb272011-04-08 18:41:53 +00002249 return ExprError();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002250 }
2251
2252 // Everything went well.
John Wiegley429bb272011-04-08 18:41:53 +00002253 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002254}
2255
Richard Smithc8d7f582011-11-29 22:48:16 +00002256/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002257/// expression From to the type ToType by following the standard
John Wiegley429bb272011-04-08 18:41:53 +00002258/// conversion sequence SCS. Returns the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00002259/// expression. Flavor is the context in which we're performing this
2260/// conversion, for use in error messages.
John Wiegley429bb272011-04-08 18:41:53 +00002261ExprResult
Richard Smithc8d7f582011-11-29 22:48:16 +00002262Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00002263 const StandardConversionSequence& SCS,
John McCallf85e1932011-06-15 23:02:42 +00002264 AssignmentAction Action,
2265 CheckedConversionKind CCK) {
2266 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
2267
Mike Stump390b4cc2009-05-16 07:39:55 +00002268 // Overall FIXME: we are recomputing too many types here and doing far too
2269 // much extra work. What this means is that we need to keep track of more
2270 // information that is computed when we try the implicit conversion initially,
2271 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002272 QualType FromType = From->getType();
John McCallf85e1932011-06-15 23:02:42 +00002273
Douglas Gregor225c41e2008-11-03 19:09:14 +00002274 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00002275 // FIXME: When can ToType be a reference type?
2276 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002277 if (SCS.Second == ICK_Derived_To_Base) {
John McCallca0408f2010-08-23 06:44:23 +00002278 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002279 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCallca0408f2010-08-23 06:44:23 +00002280 MultiExprArg(*this, &From, 1),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002281 /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002282 ConstructorArgs))
John Wiegley429bb272011-04-08 18:41:53 +00002283 return ExprError();
2284 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2285 ToType, SCS.CopyConstructor,
2286 move_arg(ConstructorArgs),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002287 /*HadMultipleCandidates*/ false,
John Wiegley429bb272011-04-08 18:41:53 +00002288 /*ZeroInit*/ false,
2289 CXXConstructExpr::CK_Complete,
2290 SourceRange());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002291 }
John Wiegley429bb272011-04-08 18:41:53 +00002292 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2293 ToType, SCS.CopyConstructor,
2294 MultiExprArg(*this, &From, 1),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002295 /*HadMultipleCandidates*/ false,
John Wiegley429bb272011-04-08 18:41:53 +00002296 /*ZeroInit*/ false,
2297 CXXConstructExpr::CK_Complete,
2298 SourceRange());
Douglas Gregor225c41e2008-11-03 19:09:14 +00002299 }
2300
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002301 // Resolve overloaded function references.
2302 if (Context.hasSameType(FromType, Context.OverloadTy)) {
2303 DeclAccessPair Found;
2304 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2305 true, Found);
2306 if (!Fn)
John Wiegley429bb272011-04-08 18:41:53 +00002307 return ExprError();
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002308
2309 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
John Wiegley429bb272011-04-08 18:41:53 +00002310 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002311
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002312 From = FixOverloadedFunctionReference(From, Found, Fn);
2313 FromType = From->getType();
2314 }
2315
Richard Smithc8d7f582011-11-29 22:48:16 +00002316 // Perform the first implicit conversion.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002317 switch (SCS.First) {
2318 case ICK_Identity:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002319 // Nothing to do.
2320 break;
2321
John McCallf6a16482010-12-04 03:47:34 +00002322 case ICK_Lvalue_To_Rvalue:
John McCall3c3b7f92011-10-25 17:37:35 +00002323 assert(From->getObjectKind() != OK_ObjCProperty);
John McCallf6a16482010-12-04 03:47:34 +00002324 FromType = FromType.getUnqualifiedType();
2325 From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
2326 From, 0, VK_RValue);
2327 break;
2328
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002329 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002330 FromType = Context.getArrayDecayedType(FromType);
Richard Smithc8d7f582011-11-29 22:48:16 +00002331 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
2332 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002333 break;
2334
2335 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002336 FromType = Context.getPointerType(FromType);
Richard Smithc8d7f582011-11-29 22:48:16 +00002337 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
2338 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002339 break;
2340
2341 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002342 llvm_unreachable("Improper first standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002343 }
2344
Richard Smithc8d7f582011-11-29 22:48:16 +00002345 // Perform the second implicit conversion
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002346 switch (SCS.Second) {
2347 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002348 // If both sides are functions (or pointers/references to them), there could
2349 // be incompatible exception declarations.
2350 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002351 return ExprError();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002352 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002353 break;
2354
Douglas Gregor43c79c22009-12-09 00:47:37 +00002355 case ICK_NoReturn_Adjustment:
2356 // If both sides are functions (or pointers/references to them), there could
2357 // be incompatible exception declarations.
2358 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002359 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002360
Richard Smithc8d7f582011-11-29 22:48:16 +00002361 From = ImpCastExprToType(From, ToType, CK_NoOp,
2362 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor43c79c22009-12-09 00:47:37 +00002363 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002364
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002365 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002366 case ICK_Integral_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002367 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
2368 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002369 break;
2370
2371 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002372 case ICK_Floating_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002373 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
2374 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002375 break;
2376
2377 case ICK_Complex_Promotion:
John McCalldaa8e4e2010-11-15 09:13:47 +00002378 case ICK_Complex_Conversion: {
2379 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2380 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2381 CastKind CK;
2382 if (FromEl->isRealFloatingType()) {
2383 if (ToEl->isRealFloatingType())
2384 CK = CK_FloatingComplexCast;
2385 else
2386 CK = CK_FloatingComplexToIntegralComplex;
2387 } else if (ToEl->isRealFloatingType()) {
2388 CK = CK_IntegralComplexToFloatingComplex;
2389 } else {
2390 CK = CK_IntegralComplexCast;
2391 }
Richard Smithc8d7f582011-11-29 22:48:16 +00002392 From = ImpCastExprToType(From, ToType, CK,
2393 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002394 break;
John McCalldaa8e4e2010-11-15 09:13:47 +00002395 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00002396
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002397 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00002398 if (ToType->isRealFloatingType())
Richard Smithc8d7f582011-11-29 22:48:16 +00002399 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
2400 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002401 else
Richard Smithc8d7f582011-11-29 22:48:16 +00002402 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
2403 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002404 break;
2405
Douglas Gregorf9201e02009-02-11 23:02:49 +00002406 case ICK_Compatible_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002407 From = ImpCastExprToType(From, ToType, CK_NoOp,
2408 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002409 break;
2410
John McCallf85e1932011-06-15 23:02:42 +00002411 case ICK_Writeback_Conversion:
Anders Carlsson61faec12009-09-12 04:46:44 +00002412 case ICK_Pointer_Conversion: {
Douglas Gregora3998bd2010-12-02 21:47:04 +00002413 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor45920e82008-12-19 17:40:08 +00002414 // Diagnose incompatible Objective-C conversions
Douglas Gregor8cf0d222011-06-11 04:42:12 +00002415 if (Action == AA_Initializing || Action == AA_Assigning)
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002416 Diag(From->getSourceRange().getBegin(),
2417 diag::ext_typecheck_convert_incompatible_pointer)
2418 << ToType << From->getType() << Action
Anna Zaks67221552011-07-28 19:51:27 +00002419 << From->getSourceRange() << 0;
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002420 else
2421 Diag(From->getSourceRange().getBegin(),
2422 diag::ext_typecheck_convert_incompatible_pointer)
2423 << From->getType() << ToType << Action
Anna Zaks67221552011-07-28 19:51:27 +00002424 << From->getSourceRange() << 0;
John McCallf85e1932011-06-15 23:02:42 +00002425
Douglas Gregor926df6c2011-06-11 01:09:30 +00002426 if (From->getType()->isObjCObjectPointerType() &&
2427 ToType->isObjCObjectPointerType())
2428 EmitRelatedResultTypeNote(From);
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002429 }
2430 else if (getLangOptions().ObjCAutoRefCount &&
2431 !CheckObjCARCUnavailableWeakConversion(ToType,
2432 From->getType())) {
John McCall7f3a6d32011-09-09 06:12:06 +00002433 if (Action == AA_Initializing)
2434 Diag(From->getSourceRange().getBegin(),
2435 diag::err_arc_weak_unavailable_assign);
2436 else
2437 Diag(From->getSourceRange().getBegin(),
2438 diag::err_arc_convesion_of_weak_unavailable)
2439 << (Action == AA_Casting) << From->getType() << ToType
2440 << From->getSourceRange();
2441 }
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002442
John McCalldaa8e4e2010-11-15 09:13:47 +00002443 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002444 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002445 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002446 return ExprError();
John McCalldc05b112011-09-10 01:16:55 +00002447
2448 // Make sure we extend blocks if necessary.
2449 // FIXME: doing this here is really ugly.
2450 if (Kind == CK_BlockPointerToObjCPointerCast) {
2451 ExprResult E = From;
2452 (void) PrepareCastToObjCObjectPointer(E);
2453 From = E.take();
2454 }
2455
Richard Smithc8d7f582011-11-29 22:48:16 +00002456 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2457 .take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002458 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00002459 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002460
Anders Carlsson61faec12009-09-12 04:46:44 +00002461 case ICK_Pointer_Member: {
John McCalldaa8e4e2010-11-15 09:13:47 +00002462 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002463 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002464 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002465 return ExprError();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002466 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002467 return ExprError();
Richard Smithc8d7f582011-11-29 22:48:16 +00002468 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2469 .take();
Anders Carlsson61faec12009-09-12 04:46:44 +00002470 break;
2471 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002472
Abramo Bagnara737d5442011-04-07 09:26:19 +00002473 case ICK_Boolean_Conversion:
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00002474 // Perform half-to-boolean conversion via float.
2475 if (From->getType()->isHalfType()) {
2476 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).take();
2477 FromType = Context.FloatTy;
2478 }
2479
Richard Smithc8d7f582011-11-29 22:48:16 +00002480 From = ImpCastExprToType(From, Context.BoolTy,
2481 ScalarTypeToBooleanCastKind(FromType),
2482 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002483 break;
2484
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002485 case ICK_Derived_To_Base: {
John McCallf871d0c2010-08-07 06:22:56 +00002486 CXXCastPath BasePath;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002487 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002488 ToType.getNonReferenceType(),
2489 From->getLocStart(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002490 From->getSourceRange(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002491 &BasePath,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002492 CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002493 return ExprError();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002494
Richard Smithc8d7f582011-11-29 22:48:16 +00002495 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
2496 CK_DerivedToBase, From->getValueKind(),
2497 &BasePath, CCK).take();
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002498 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002499 }
2500
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002501 case ICK_Vector_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002502 From = ImpCastExprToType(From, ToType, CK_BitCast,
2503 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002504 break;
2505
2506 case ICK_Vector_Splat:
Richard Smithc8d7f582011-11-29 22:48:16 +00002507 From = ImpCastExprToType(From, ToType, CK_VectorSplat,
2508 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002509 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002510
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002511 case ICK_Complex_Real:
John McCalldaa8e4e2010-11-15 09:13:47 +00002512 // Case 1. x -> _Complex y
2513 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2514 QualType ElType = ToComplex->getElementType();
2515 bool isFloatingComplex = ElType->isRealFloatingType();
2516
2517 // x -> y
2518 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2519 // do nothing
2520 } else if (From->getType()->isRealFloatingType()) {
Richard Smithc8d7f582011-11-29 22:48:16 +00002521 From = ImpCastExprToType(From, ElType,
2522 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002523 } else {
2524 assert(From->getType()->isIntegerType());
Richard Smithc8d7f582011-11-29 22:48:16 +00002525 From = ImpCastExprToType(From, ElType,
2526 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002527 }
2528 // y -> _Complex y
Richard Smithc8d7f582011-11-29 22:48:16 +00002529 From = ImpCastExprToType(From, ToType,
2530 isFloatingComplex ? CK_FloatingRealToComplex
2531 : CK_IntegralRealToComplex).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002532
2533 // Case 2. _Complex x -> y
2534 } else {
2535 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2536 assert(FromComplex);
2537
2538 QualType ElType = FromComplex->getElementType();
2539 bool isFloatingComplex = ElType->isRealFloatingType();
2540
2541 // _Complex x -> x
Richard Smithc8d7f582011-11-29 22:48:16 +00002542 From = ImpCastExprToType(From, ElType,
2543 isFloatingComplex ? CK_FloatingComplexToReal
2544 : CK_IntegralComplexToReal,
2545 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002546
2547 // x -> y
2548 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2549 // do nothing
2550 } else if (ToType->isRealFloatingType()) {
Richard Smithc8d7f582011-11-29 22:48:16 +00002551 From = ImpCastExprToType(From, ToType,
2552 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
2553 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002554 } else {
2555 assert(ToType->isIntegerType());
Richard Smithc8d7f582011-11-29 22:48:16 +00002556 From = ImpCastExprToType(From, ToType,
2557 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
2558 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002559 }
2560 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002561 break;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002562
2563 case ICK_Block_Pointer_Conversion: {
Richard Smithc8d7f582011-11-29 22:48:16 +00002564 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
2565 VK_RValue, /*BasePath=*/0, CCK).take();
John McCallf85e1932011-06-15 23:02:42 +00002566 break;
2567 }
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002568
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002569 case ICK_TransparentUnionConversion: {
John Wiegley429bb272011-04-08 18:41:53 +00002570 ExprResult FromRes = Owned(From);
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002571 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00002572 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
2573 if (FromRes.isInvalid())
2574 return ExprError();
2575 From = FromRes.take();
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002576 assert ((ConvTy == Sema::Compatible) &&
2577 "Improper transparent union conversion");
2578 (void)ConvTy;
2579 break;
2580 }
2581
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002582 case ICK_Lvalue_To_Rvalue:
2583 case ICK_Array_To_Pointer:
2584 case ICK_Function_To_Pointer:
2585 case ICK_Qualification:
2586 case ICK_Num_Conversion_Kinds:
David Blaikieb219cfc2011-09-23 05:06:16 +00002587 llvm_unreachable("Improper second standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002588 }
2589
2590 switch (SCS.Third) {
2591 case ICK_Identity:
2592 // Nothing to do.
2593 break;
2594
Sebastian Redl906082e2010-07-20 04:20:21 +00002595 case ICK_Qualification: {
2596 // The qualification keeps the category of the inner expression, unless the
2597 // target type isn't a reference.
John McCall5baba9d2010-08-25 10:28:54 +00002598 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00002599 From->getValueKind() : VK_RValue;
Richard Smithc8d7f582011-11-29 22:48:16 +00002600 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
2601 CK_NoOp, VK, /*BasePath=*/0, CCK).take();
Douglas Gregora9bff302010-02-28 18:30:25 +00002602
Douglas Gregor069a6da2011-03-14 16:13:32 +00002603 if (SCS.DeprecatedStringLiteralToCharPtr &&
2604 !getLangOptions().WritableStrings)
Douglas Gregora9bff302010-02-28 18:30:25 +00002605 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2606 << ToType.getNonReferenceType();
2607
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002608 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002609 }
2610
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002611 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002612 llvm_unreachable("Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002613 }
2614
John Wiegley429bb272011-04-08 18:41:53 +00002615 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002616}
2617
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002618ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002619 SourceLocation KWLoc,
2620 ParsedType Ty,
2621 SourceLocation RParen) {
2622 TypeSourceInfo *TSInfo;
2623 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002624
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002625 if (!TSInfo)
2626 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002627 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002628}
2629
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002630/// \brief Check the completeness of a type in a unary type trait.
2631///
2632/// If the particular type trait requires a complete type, tries to complete
2633/// it. If completing the type fails, a diagnostic is emitted and false
2634/// returned. If completing the type succeeds or no completion was required,
2635/// returns true.
2636static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S,
2637 UnaryTypeTrait UTT,
2638 SourceLocation Loc,
2639 QualType ArgTy) {
2640 // C++0x [meta.unary.prop]p3:
2641 // For all of the class templates X declared in this Clause, instantiating
2642 // that template with a template argument that is a class template
2643 // specialization may result in the implicit instantiation of the template
2644 // argument if and only if the semantics of X require that the argument
2645 // must be a complete type.
2646 // We apply this rule to all the type trait expressions used to implement
2647 // these class templates. We also try to follow any GCC documented behavior
2648 // in these expressions to ensure portability of standard libraries.
2649 switch (UTT) {
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002650 // is_complete_type somewhat obviously cannot require a complete type.
2651 case UTT_IsCompleteType:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002652 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002653
2654 // These traits are modeled on the type predicates in C++0x
2655 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
2656 // requiring a complete type, as whether or not they return true cannot be
2657 // impacted by the completeness of the type.
2658 case UTT_IsVoid:
2659 case UTT_IsIntegral:
2660 case UTT_IsFloatingPoint:
2661 case UTT_IsArray:
2662 case UTT_IsPointer:
2663 case UTT_IsLvalueReference:
2664 case UTT_IsRvalueReference:
2665 case UTT_IsMemberFunctionPointer:
2666 case UTT_IsMemberObjectPointer:
2667 case UTT_IsEnum:
2668 case UTT_IsUnion:
2669 case UTT_IsClass:
2670 case UTT_IsFunction:
2671 case UTT_IsReference:
2672 case UTT_IsArithmetic:
2673 case UTT_IsFundamental:
2674 case UTT_IsObject:
2675 case UTT_IsScalar:
2676 case UTT_IsCompound:
2677 case UTT_IsMemberPointer:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002678 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002679
2680 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
2681 // which requires some of its traits to have the complete type. However,
2682 // the completeness of the type cannot impact these traits' semantics, and
2683 // so they don't require it. This matches the comments on these traits in
2684 // Table 49.
2685 case UTT_IsConst:
2686 case UTT_IsVolatile:
2687 case UTT_IsSigned:
2688 case UTT_IsUnsigned:
2689 return true;
2690
2691 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002692 // applied to a complete type.
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002693 case UTT_IsTrivial:
Sean Huntfeb375d2011-05-13 00:31:07 +00002694 case UTT_IsTriviallyCopyable:
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002695 case UTT_IsStandardLayout:
2696 case UTT_IsPOD:
2697 case UTT_IsLiteral:
2698 case UTT_IsEmpty:
2699 case UTT_IsPolymorphic:
2700 case UTT_IsAbstract:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002701 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002702
Douglas Gregor5e9392b2011-12-03 18:14:24 +00002703 // These traits require a complete type.
2704 case UTT_IsFinal:
2705
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002706 // These trait expressions are designed to help implement predicates in
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002707 // [meta.unary.prop] despite not being named the same. They are specified
2708 // by both GCC and the Embarcadero C++ compiler, and require the complete
2709 // type due to the overarching C++0x type predicates being implemented
2710 // requiring the complete type.
2711 case UTT_HasNothrowAssign:
2712 case UTT_HasNothrowConstructor:
2713 case UTT_HasNothrowCopy:
2714 case UTT_HasTrivialAssign:
Sean Hunt023df372011-05-09 18:22:59 +00002715 case UTT_HasTrivialDefaultConstructor:
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002716 case UTT_HasTrivialCopy:
2717 case UTT_HasTrivialDestructor:
2718 case UTT_HasVirtualDestructor:
2719 // Arrays of unknown bound are expressly allowed.
2720 QualType ElTy = ArgTy;
2721 if (ArgTy->isIncompleteArrayType())
2722 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
2723
2724 // The void type is expressly allowed.
2725 if (ElTy->isVoidType())
2726 return true;
2727
2728 return !S.RequireCompleteType(
2729 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleycf566412011-04-28 02:06:46 +00002730 }
Chandler Carruth73e0a912011-05-01 07:23:17 +00002731 llvm_unreachable("Type trait not handled by switch");
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002732}
2733
2734static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT,
2735 SourceLocation KeyLoc, QualType T) {
Chandler Carruthd064c702011-05-01 08:41:10 +00002736 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleycf566412011-04-28 02:06:46 +00002737
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002738 ASTContext &C = Self.Context;
2739 switch(UTT) {
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002740 // Type trait expressions corresponding to the primary type category
2741 // predicates in C++0x [meta.unary.cat].
2742 case UTT_IsVoid:
2743 return T->isVoidType();
2744 case UTT_IsIntegral:
2745 return T->isIntegralType(C);
2746 case UTT_IsFloatingPoint:
2747 return T->isFloatingType();
2748 case UTT_IsArray:
2749 return T->isArrayType();
2750 case UTT_IsPointer:
2751 return T->isPointerType();
2752 case UTT_IsLvalueReference:
2753 return T->isLValueReferenceType();
2754 case UTT_IsRvalueReference:
2755 return T->isRValueReferenceType();
2756 case UTT_IsMemberFunctionPointer:
2757 return T->isMemberFunctionPointerType();
2758 case UTT_IsMemberObjectPointer:
2759 return T->isMemberDataPointerType();
2760 case UTT_IsEnum:
2761 return T->isEnumeralType();
Chandler Carruth28eeb382011-05-01 06:11:03 +00002762 case UTT_IsUnion:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002763 return T->isUnionType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002764 case UTT_IsClass:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002765 return T->isClassType() || T->isStructureType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002766 case UTT_IsFunction:
2767 return T->isFunctionType();
2768
2769 // Type trait expressions which correspond to the convenient composition
2770 // predicates in C++0x [meta.unary.comp].
2771 case UTT_IsReference:
2772 return T->isReferenceType();
2773 case UTT_IsArithmetic:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002774 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002775 case UTT_IsFundamental:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002776 return T->isFundamentalType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002777 case UTT_IsObject:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002778 return T->isObjectType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002779 case UTT_IsScalar:
John McCallf85e1932011-06-15 23:02:42 +00002780 // Note: semantic analysis depends on Objective-C lifetime types to be
2781 // considered scalar types. However, such types do not actually behave
2782 // like scalar types at run time (since they may require retain/release
2783 // operations), so we report them as non-scalar.
2784 if (T->isObjCLifetimeType()) {
2785 switch (T.getObjCLifetime()) {
2786 case Qualifiers::OCL_None:
2787 case Qualifiers::OCL_ExplicitNone:
2788 return true;
2789
2790 case Qualifiers::OCL_Strong:
2791 case Qualifiers::OCL_Weak:
2792 case Qualifiers::OCL_Autoreleasing:
2793 return false;
2794 }
2795 }
2796
Chandler Carruthcec0ced2011-05-01 09:29:55 +00002797 return T->isScalarType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002798 case UTT_IsCompound:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002799 return T->isCompoundType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002800 case UTT_IsMemberPointer:
2801 return T->isMemberPointerType();
2802
2803 // Type trait expressions which correspond to the type property predicates
2804 // in C++0x [meta.unary.prop].
2805 case UTT_IsConst:
2806 return T.isConstQualified();
2807 case UTT_IsVolatile:
2808 return T.isVolatileQualified();
2809 case UTT_IsTrivial:
John McCallf85e1932011-06-15 23:02:42 +00002810 return T.isTrivialType(Self.Context);
Sean Huntfeb375d2011-05-13 00:31:07 +00002811 case UTT_IsTriviallyCopyable:
John McCallf85e1932011-06-15 23:02:42 +00002812 return T.isTriviallyCopyableType(Self.Context);
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002813 case UTT_IsStandardLayout:
2814 return T->isStandardLayoutType();
2815 case UTT_IsPOD:
John McCallf85e1932011-06-15 23:02:42 +00002816 return T.isPODType(Self.Context);
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002817 case UTT_IsLiteral:
2818 return T->isLiteralType();
2819 case UTT_IsEmpty:
2820 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2821 return !RD->isUnion() && RD->isEmpty();
2822 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002823 case UTT_IsPolymorphic:
Chandler Carruth28eeb382011-05-01 06:11:03 +00002824 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2825 return RD->isPolymorphic();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002826 return false;
2827 case UTT_IsAbstract:
Chandler Carruth28eeb382011-05-01 06:11:03 +00002828 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2829 return RD->isAbstract();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002830 return false;
Douglas Gregor5e9392b2011-12-03 18:14:24 +00002831 case UTT_IsFinal:
2832 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2833 return RD->hasAttr<FinalAttr>();
2834 return false;
John Wiegley20c0da72011-04-27 23:09:49 +00002835 case UTT_IsSigned:
2836 return T->isSignedIntegerType();
John Wiegley20c0da72011-04-27 23:09:49 +00002837 case UTT_IsUnsigned:
2838 return T->isUnsignedIntegerType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002839
2840 // Type trait expressions which query classes regarding their construction,
2841 // destruction, and copying. Rather than being based directly on the
2842 // related type predicates in the standard, they are specified by both
2843 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
2844 // specifications.
2845 //
2846 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
2847 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Sean Hunt023df372011-05-09 18:22:59 +00002848 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002849 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2850 // If __is_pod (type) is true then the trait is true, else if type is
2851 // a cv class or union type (or array thereof) with a trivial default
2852 // constructor ([class.ctor]) then the trait is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00002853 if (T.isPODType(Self.Context))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002854 return true;
2855 if (const RecordType *RT =
2856 C.getBaseElementType(T)->getAs<RecordType>())
Sean Hunt023df372011-05-09 18:22:59 +00002857 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDefaultConstructor();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002858 return false;
2859 case UTT_HasTrivialCopy:
2860 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2861 // If __is_pod (type) is true or type is a reference type then
2862 // the trait is true, else if type is a cv class or union type
2863 // with a trivial copy constructor ([class.copy]) then the trait
2864 // is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00002865 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002866 return true;
2867 if (const RecordType *RT = T->getAs<RecordType>())
2868 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2869 return false;
2870 case UTT_HasTrivialAssign:
2871 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2872 // If type is const qualified or is a reference type then the
2873 // trait is false. Otherwise if __is_pod (type) is true then the
2874 // trait is true, else if type is a cv class or union type with
2875 // a trivial copy assignment ([class.copy]) then the trait is
2876 // true, else it is false.
2877 // Note: the const and reference restrictions are interesting,
2878 // given that const and reference members don't prevent a class
2879 // from having a trivial copy assignment operator (but do cause
2880 // errors if the copy assignment operator is actually used, q.v.
2881 // [class.copy]p12).
2882
2883 if (C.getBaseElementType(T).isConstQualified())
2884 return false;
John McCallf85e1932011-06-15 23:02:42 +00002885 if (T.isPODType(Self.Context))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002886 return true;
2887 if (const RecordType *RT = T->getAs<RecordType>())
2888 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2889 return false;
2890 case UTT_HasTrivialDestructor:
2891 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2892 // If __is_pod (type) is true or type is a reference type
2893 // then the trait is true, else if type is a cv class or union
2894 // type (or array thereof) with a trivial destructor
2895 // ([class.dtor]) then the trait is true, else it is
2896 // false.
John McCallf85e1932011-06-15 23:02:42 +00002897 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002898 return true;
John McCallf85e1932011-06-15 23:02:42 +00002899
2900 // Objective-C++ ARC: autorelease types don't require destruction.
2901 if (T->isObjCLifetimeType() &&
2902 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
2903 return true;
2904
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002905 if (const RecordType *RT =
2906 C.getBaseElementType(T)->getAs<RecordType>())
2907 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2908 return false;
2909 // TODO: Propagate nothrowness for implicitly declared special members.
2910 case UTT_HasNothrowAssign:
2911 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2912 // If type is const qualified or is a reference type then the
2913 // trait is false. Otherwise if __has_trivial_assign (type)
2914 // is true then the trait is true, else if type is a cv class
2915 // or union type with copy assignment operators that are known
2916 // not to throw an exception then the trait is true, else it is
2917 // false.
2918 if (C.getBaseElementType(T).isConstQualified())
2919 return false;
2920 if (T->isReferenceType())
2921 return false;
John McCallf85e1932011-06-15 23:02:42 +00002922 if (T.isPODType(Self.Context) || T->isObjCLifetimeType())
2923 return true;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002924 if (const RecordType *RT = T->getAs<RecordType>()) {
2925 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2926 if (RD->hasTrivialCopyAssignment())
2927 return true;
2928
2929 bool FoundAssign = false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002930 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redlf8aca862010-09-14 23:40:14 +00002931 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2932 Sema::LookupOrdinaryName);
2933 if (Self.LookupQualifiedName(Res, RD)) {
Douglas Gregord41679d2011-10-12 15:40:49 +00002934 Res.suppressDiagnostics();
Sebastian Redlf8aca862010-09-14 23:40:14 +00002935 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2936 Op != OpEnd; ++Op) {
Douglas Gregord41679d2011-10-12 15:40:49 +00002937 if (isa<FunctionTemplateDecl>(*Op))
2938 continue;
2939
Sebastian Redlf8aca862010-09-14 23:40:14 +00002940 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2941 if (Operator->isCopyAssignmentOperator()) {
2942 FoundAssign = true;
2943 const FunctionProtoType *CPT
2944 = Operator->getType()->getAs<FunctionProtoType>();
Richard Smith7a614d82011-06-11 17:19:42 +00002945 if (CPT->getExceptionSpecType() == EST_Delayed)
2946 return false;
2947 if (!CPT->isNothrow(Self.Context))
2948 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002949 }
2950 }
2951 }
Douglas Gregord41679d2011-10-12 15:40:49 +00002952
Richard Smith7a614d82011-06-11 17:19:42 +00002953 return FoundAssign;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002954 }
2955 return false;
2956 case UTT_HasNothrowCopy:
2957 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2958 // If __has_trivial_copy (type) is true then the trait is true, else
2959 // if type is a cv class or union type with copy constructors that are
2960 // known not to throw an exception then the trait is true, else it is
2961 // false.
John McCallf85e1932011-06-15 23:02:42 +00002962 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002963 return true;
2964 if (const RecordType *RT = T->getAs<RecordType>()) {
2965 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2966 if (RD->hasTrivialCopyConstructor())
2967 return true;
2968
2969 bool FoundConstructor = false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002970 unsigned FoundTQs;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002971 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl5f4e8992010-09-13 21:10:20 +00002972 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002973 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002974 // A template constructor is never a copy constructor.
2975 // FIXME: However, it may actually be selected at the actual overload
2976 // resolution point.
2977 if (isa<FunctionTemplateDecl>(*Con))
2978 continue;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002979 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2980 if (Constructor->isCopyConstructor(FoundTQs)) {
2981 FoundConstructor = true;
2982 const FunctionProtoType *CPT
2983 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smith7a614d82011-06-11 17:19:42 +00002984 if (CPT->getExceptionSpecType() == EST_Delayed)
2985 return false;
Sebastian Redl60618fa2011-03-12 11:50:43 +00002986 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redl751025d2010-09-13 22:02:47 +00002987 // For now, we'll be conservative and assume that they can throw.
Richard Smith7a614d82011-06-11 17:19:42 +00002988 if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1)
2989 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002990 }
2991 }
2992
Richard Smith7a614d82011-06-11 17:19:42 +00002993 return FoundConstructor;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002994 }
2995 return false;
2996 case UTT_HasNothrowConstructor:
2997 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2998 // If __has_trivial_constructor (type) is true then the trait is
2999 // true, else if type is a cv class or union type (or array
3000 // thereof) with a default constructor that is known not to
3001 // throw an exception then the trait is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00003002 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003003 return true;
3004 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
3005 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Hunt023df372011-05-09 18:22:59 +00003006 if (RD->hasTrivialDefaultConstructor())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003007 return true;
3008
Sebastian Redl751025d2010-09-13 22:02:47 +00003009 DeclContext::lookup_const_iterator Con, ConEnd;
3010 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
3011 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00003012 // FIXME: In C++0x, a constructor template can be a default constructor.
3013 if (isa<FunctionTemplateDecl>(*Con))
3014 continue;
Sebastian Redl751025d2010-09-13 22:02:47 +00003015 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3016 if (Constructor->isDefaultConstructor()) {
3017 const FunctionProtoType *CPT
3018 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smith7a614d82011-06-11 17:19:42 +00003019 if (CPT->getExceptionSpecType() == EST_Delayed)
3020 return false;
Sebastian Redl751025d2010-09-13 22:02:47 +00003021 // TODO: check whether evaluating default arguments can throw.
3022 // For now, we'll be conservative and assume that they can throw.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00003023 return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
Sebastian Redl751025d2010-09-13 22:02:47 +00003024 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003025 }
3026 }
3027 return false;
3028 case UTT_HasVirtualDestructor:
3029 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3030 // If type is a class type with a virtual destructor ([class.dtor])
3031 // then the trait is true, else it is false.
3032 if (const RecordType *Record = T->getAs<RecordType>()) {
3033 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redlf8aca862010-09-14 23:40:14 +00003034 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003035 return Destructor->isVirtual();
3036 }
3037 return false;
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003038
3039 // These type trait expressions are modeled on the specifications for the
3040 // Embarcadero C++0x type trait functions:
3041 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
3042 case UTT_IsCompleteType:
3043 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
3044 // Returns True if and only if T is a complete type at the point of the
3045 // function call.
3046 return !T->isIncompleteType();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003047 }
Chandler Carruth83f563c2011-05-01 07:44:17 +00003048 llvm_unreachable("Type trait not covered by switch");
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003049}
3050
3051ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00003052 SourceLocation KWLoc,
3053 TypeSourceInfo *TSInfo,
3054 SourceLocation RParen) {
3055 QualType T = TSInfo->getType();
Chandler Carrutheb65a102011-04-30 10:07:32 +00003056 if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T))
3057 return ExprError();
Sebastian Redl64b45f72009-01-05 20:52:13 +00003058
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003059 bool Value = false;
3060 if (!T->isDependentType())
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00003061 Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003062
3063 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson3292d5c2009-07-07 19:06:02 +00003064 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00003065}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003066
Francois Pichet6ad6f282010-12-07 00:08:36 +00003067ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
3068 SourceLocation KWLoc,
3069 ParsedType LhsTy,
3070 ParsedType RhsTy,
3071 SourceLocation RParen) {
3072 TypeSourceInfo *LhsTSInfo;
3073 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
3074 if (!LhsTSInfo)
3075 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
3076
3077 TypeSourceInfo *RhsTSInfo;
3078 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
3079 if (!RhsTSInfo)
3080 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
3081
3082 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
3083}
3084
3085static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
3086 QualType LhsT, QualType RhsT,
3087 SourceLocation KeyLoc) {
Chandler Carruthd064c702011-05-01 08:41:10 +00003088 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
3089 "Cannot evaluate traits of dependent types");
Francois Pichet6ad6f282010-12-07 00:08:36 +00003090
3091 switch(BTT) {
John McCalld89d30f2011-01-28 22:02:36 +00003092 case BTT_IsBaseOf: {
Francois Pichet6ad6f282010-12-07 00:08:36 +00003093 // C++0x [meta.rel]p2
John McCalld89d30f2011-01-28 22:02:36 +00003094 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet6ad6f282010-12-07 00:08:36 +00003095 // Base and Derived are not unions and name the same class type without
3096 // regard to cv-qualifiers.
Francois Pichet6ad6f282010-12-07 00:08:36 +00003097
John McCalld89d30f2011-01-28 22:02:36 +00003098 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
3099 if (!lhsRecord) return false;
3100
3101 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
3102 if (!rhsRecord) return false;
3103
3104 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
3105 == (lhsRecord == rhsRecord));
3106
3107 if (lhsRecord == rhsRecord)
3108 return !lhsRecord->getDecl()->isUnion();
3109
3110 // C++0x [meta.rel]p2:
3111 // If Base and Derived are class types and are different types
3112 // (ignoring possible cv-qualifiers) then Derived shall be a
3113 // complete type.
3114 if (Self.RequireCompleteType(KeyLoc, RhsT,
3115 diag::err_incomplete_type_used_in_type_trait_expr))
3116 return false;
3117
3118 return cast<CXXRecordDecl>(rhsRecord->getDecl())
3119 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
3120 }
John Wiegley20c0da72011-04-27 23:09:49 +00003121 case BTT_IsSame:
3122 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichetf1872372010-12-08 22:35:30 +00003123 case BTT_TypeCompatible:
3124 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
3125 RhsT.getUnqualifiedType());
John Wiegley20c0da72011-04-27 23:09:49 +00003126 case BTT_IsConvertible:
Douglas Gregor9f361132011-01-27 20:28:01 +00003127 case BTT_IsConvertibleTo: {
3128 // C++0x [meta.rel]p4:
3129 // Given the following function prototype:
3130 //
3131 // template <class T>
3132 // typename add_rvalue_reference<T>::type create();
3133 //
3134 // the predicate condition for a template specialization
3135 // is_convertible<From, To> shall be satisfied if and only if
3136 // the return expression in the following code would be
3137 // well-formed, including any implicit conversions to the return
3138 // type of the function:
3139 //
3140 // To test() {
3141 // return create<From>();
3142 // }
3143 //
3144 // Access checking is performed as if in a context unrelated to To and
3145 // From. Only the validity of the immediate context of the expression
3146 // of the return-statement (including conversions to the return type)
3147 // is considered.
3148 //
3149 // We model the initialization as a copy-initialization of a temporary
3150 // of the appropriate type, which for this expression is identical to the
3151 // return statement (since NRVO doesn't apply).
3152 if (LhsT->isObjectType() || LhsT->isFunctionType())
3153 LhsT = Self.Context.getRValueReferenceType(LhsT);
3154
3155 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorb608b982011-01-28 02:26:04 +00003156 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor9f361132011-01-27 20:28:01 +00003157 Expr::getValueKindForType(LhsT));
3158 Expr *FromPtr = &From;
3159 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
3160 SourceLocation()));
3161
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00003162 // Perform the initialization within a SFINAE trap at translation unit
3163 // scope.
3164 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3165 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Douglas Gregor9f361132011-01-27 20:28:01 +00003166 InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003167 if (Init.Failed())
Douglas Gregor9f361132011-01-27 20:28:01 +00003168 return false;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00003169
Douglas Gregor9f361132011-01-27 20:28:01 +00003170 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
3171 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
3172 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00003173 }
3174 llvm_unreachable("Unknown type trait or not implemented");
3175}
3176
3177ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
3178 SourceLocation KWLoc,
3179 TypeSourceInfo *LhsTSInfo,
3180 TypeSourceInfo *RhsTSInfo,
3181 SourceLocation RParen) {
3182 QualType LhsT = LhsTSInfo->getType();
3183 QualType RhsT = RhsTSInfo->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003184
John McCalld89d30f2011-01-28 22:02:36 +00003185 if (BTT == BTT_TypeCompatible) {
Francois Pichetf1872372010-12-08 22:35:30 +00003186 if (getLangOptions().CPlusPlus) {
3187 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
3188 << SourceRange(KWLoc, RParen);
3189 return ExprError();
3190 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00003191 }
3192
3193 bool Value = false;
3194 if (!LhsT->isDependentType() && !RhsT->isDependentType())
3195 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
3196
Francois Pichetf1872372010-12-08 22:35:30 +00003197 // Select trait result type.
3198 QualType ResultType;
3199 switch (BTT) {
Francois Pichetf1872372010-12-08 22:35:30 +00003200 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
John Wiegley20c0da72011-04-27 23:09:49 +00003201 case BTT_IsConvertible: ResultType = Context.BoolTy; break;
3202 case BTT_IsSame: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00003203 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
Douglas Gregor9f361132011-01-27 20:28:01 +00003204 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00003205 }
3206
Francois Pichet6ad6f282010-12-07 00:08:36 +00003207 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
3208 RhsTSInfo, Value, RParen,
Francois Pichetf1872372010-12-08 22:35:30 +00003209 ResultType));
Francois Pichet6ad6f282010-12-07 00:08:36 +00003210}
3211
John Wiegley21ff2e52011-04-28 00:16:57 +00003212ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3213 SourceLocation KWLoc,
3214 ParsedType Ty,
3215 Expr* DimExpr,
3216 SourceLocation RParen) {
3217 TypeSourceInfo *TSInfo;
3218 QualType T = GetTypeFromParser(Ty, &TSInfo);
3219 if (!TSInfo)
3220 TSInfo = Context.getTrivialTypeSourceInfo(T);
3221
3222 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
3223}
3224
3225static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
3226 QualType T, Expr *DimExpr,
3227 SourceLocation KeyLoc) {
Chandler Carruthd064c702011-05-01 08:41:10 +00003228 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley21ff2e52011-04-28 00:16:57 +00003229
3230 switch(ATT) {
3231 case ATT_ArrayRank:
3232 if (T->isArrayType()) {
3233 unsigned Dim = 0;
3234 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3235 ++Dim;
3236 T = AT->getElementType();
3237 }
3238 return Dim;
John Wiegley21ff2e52011-04-28 00:16:57 +00003239 }
John Wiegleycf566412011-04-28 02:06:46 +00003240 return 0;
3241
John Wiegley21ff2e52011-04-28 00:16:57 +00003242 case ATT_ArrayExtent: {
3243 llvm::APSInt Value;
3244 uint64_t Dim;
John Wiegleycf566412011-04-28 02:06:46 +00003245 if (DimExpr->isIntegerConstantExpr(Value, Self.Context, 0, false)) {
3246 if (Value < llvm::APSInt(Value.getBitWidth(), Value.isUnsigned())) {
3247 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
3248 DimExpr->getSourceRange();
3249 return false;
3250 }
John Wiegley21ff2e52011-04-28 00:16:57 +00003251 Dim = Value.getLimitedValue();
John Wiegleycf566412011-04-28 02:06:46 +00003252 } else {
3253 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
3254 DimExpr->getSourceRange();
3255 return false;
3256 }
John Wiegley21ff2e52011-04-28 00:16:57 +00003257
3258 if (T->isArrayType()) {
3259 unsigned D = 0;
3260 bool Matched = false;
3261 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3262 if (Dim == D) {
3263 Matched = true;
3264 break;
3265 }
3266 ++D;
3267 T = AT->getElementType();
3268 }
3269
John Wiegleycf566412011-04-28 02:06:46 +00003270 if (Matched && T->isArrayType()) {
3271 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
3272 return CAT->getSize().getLimitedValue();
3273 }
John Wiegley21ff2e52011-04-28 00:16:57 +00003274 }
John Wiegleycf566412011-04-28 02:06:46 +00003275 return 0;
John Wiegley21ff2e52011-04-28 00:16:57 +00003276 }
3277 }
3278 llvm_unreachable("Unknown type trait or not implemented");
3279}
3280
3281ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
3282 SourceLocation KWLoc,
3283 TypeSourceInfo *TSInfo,
3284 Expr* DimExpr,
3285 SourceLocation RParen) {
3286 QualType T = TSInfo->getType();
John Wiegley21ff2e52011-04-28 00:16:57 +00003287
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003288 // FIXME: This should likely be tracked as an APInt to remove any host
3289 // assumptions about the width of size_t on the target.
Chandler Carruthd064c702011-05-01 08:41:10 +00003290 uint64_t Value = 0;
3291 if (!T->isDependentType())
3292 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
3293
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003294 // While the specification for these traits from the Embarcadero C++
3295 // compiler's documentation says the return type is 'unsigned int', Clang
3296 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
3297 // compiler, there is no difference. On several other platforms this is an
3298 // important distinction.
John Wiegley21ff2e52011-04-28 00:16:57 +00003299 return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value,
Chandler Carruth06207f62011-05-01 07:49:26 +00003300 DimExpr, RParen,
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003301 Context.getSizeType()));
John Wiegley21ff2e52011-04-28 00:16:57 +00003302}
3303
John Wiegley55262202011-04-25 06:54:41 +00003304ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003305 SourceLocation KWLoc,
3306 Expr *Queried,
3307 SourceLocation RParen) {
John Wiegley55262202011-04-25 06:54:41 +00003308 // If error parsing the expression, ignore.
3309 if (!Queried)
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003310 return ExprError();
John Wiegley55262202011-04-25 06:54:41 +00003311
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003312 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegley55262202011-04-25 06:54:41 +00003313
3314 return move(Result);
3315}
3316
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003317static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
3318 switch (ET) {
3319 case ET_IsLValueExpr: return E->isLValue();
3320 case ET_IsRValueExpr: return E->isRValue();
3321 }
3322 llvm_unreachable("Expression trait not covered by switch");
3323}
3324
John Wiegley55262202011-04-25 06:54:41 +00003325ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003326 SourceLocation KWLoc,
3327 Expr *Queried,
3328 SourceLocation RParen) {
John Wiegley55262202011-04-25 06:54:41 +00003329 if (Queried->isTypeDependent()) {
3330 // Delay type-checking for type-dependent expressions.
3331 } else if (Queried->getType()->isPlaceholderType()) {
3332 ExprResult PE = CheckPlaceholderExpr(Queried);
3333 if (PE.isInvalid()) return ExprError();
3334 return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen);
3335 }
3336
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003337 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf7ef0002011-05-01 08:48:19 +00003338
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003339 return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value,
3340 RParen, Context.BoolTy));
John Wiegley55262202011-04-25 06:54:41 +00003341}
3342
Richard Trieudd225092011-09-15 21:56:47 +00003343QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCallf89e55a2010-11-18 06:31:45 +00003344 ExprValueKind &VK,
3345 SourceLocation Loc,
3346 bool isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003347 assert(!LHS.get()->getType()->isPlaceholderType() &&
3348 !RHS.get()->getType()->isPlaceholderType() &&
John McCallea4aba02011-06-30 17:15:34 +00003349 "placeholders should have been weeded out by now");
3350
3351 // The LHS undergoes lvalue conversions if this is ->*.
3352 if (isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003353 LHS = DefaultLvalueConversion(LHS.take());
3354 if (LHS.isInvalid()) return QualType();
John McCallea4aba02011-06-30 17:15:34 +00003355 }
3356
3357 // The RHS always undergoes lvalue conversions.
Richard Trieudd225092011-09-15 21:56:47 +00003358 RHS = DefaultLvalueConversion(RHS.take());
3359 if (RHS.isInvalid()) return QualType();
John McCallea4aba02011-06-30 17:15:34 +00003360
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003361 const char *OpSpelling = isIndirect ? "->*" : ".*";
3362 // C++ 5.5p2
3363 // The binary operator .* [p3: ->*] binds its second operand, which shall
3364 // be of type "pointer to member of T" (where T is a completely-defined
3365 // class type) [...]
Richard Trieudd225092011-09-15 21:56:47 +00003366 QualType RHSType = RHS.get()->getType();
3367 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00003368 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003369 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieudd225092011-09-15 21:56:47 +00003370 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003371 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00003372 }
Douglas Gregore7450f52009-03-24 19:52:54 +00003373
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003374 QualType Class(MemPtr->getClass(), 0);
3375
Douglas Gregor7d520ba2010-10-13 20:41:14 +00003376 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
3377 // member pointer points must be completely-defined. However, there is no
3378 // reason for this semantic distinction, and the rule is not enforced by
3379 // other compilers. Therefore, we do not check this property, as it is
3380 // likely to be considered a defect.
Sebastian Redl59fc2692010-04-10 10:14:54 +00003381
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003382 // C++ 5.5p2
3383 // [...] to its first operand, which shall be of class T or of a class of
3384 // which T is an unambiguous and accessible base class. [p3: a pointer to
3385 // such a class]
Richard Trieudd225092011-09-15 21:56:47 +00003386 QualType LHSType = LHS.get()->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003387 if (isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003388 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
3389 LHSType = Ptr->getPointeeType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003390 else {
3391 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieudd225092011-09-15 21:56:47 +00003392 << OpSpelling << 1 << LHSType
Douglas Gregor849b2432010-03-31 17:46:05 +00003393 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003394 return QualType();
3395 }
3396 }
3397
Richard Trieudd225092011-09-15 21:56:47 +00003398 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00003399 // If we want to check the hierarchy, we need a complete type.
Richard Trieudd225092011-09-15 21:56:47 +00003400 if (RequireCompleteType(Loc, LHSType, PDiag(diag::err_bad_memptr_lhs)
Sebastian Redl17e1d352010-04-23 17:18:26 +00003401 << OpSpelling << (int)isIndirect)) {
3402 return QualType();
3403 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003404 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00003405 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00003406 // FIXME: Would it be useful to print full ambiguity paths, or is that
3407 // overkill?
Richard Trieudd225092011-09-15 21:56:47 +00003408 if (!IsDerivedFrom(LHSType, Class, Paths) ||
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003409 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
3410 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieudd225092011-09-15 21:56:47 +00003411 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003412 return QualType();
3413 }
Eli Friedman3005efe2010-01-16 00:00:48 +00003414 // Cast LHS to type of use.
3415 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00003416 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Sebastian Redl906082e2010-07-20 04:20:21 +00003417
John McCallf871d0c2010-08-07 06:22:56 +00003418 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003419 BuildBasePathArray(Paths, BasePath);
Richard Trieudd225092011-09-15 21:56:47 +00003420 LHS = ImpCastExprToType(LHS.take(), UseType, CK_DerivedToBase, VK,
3421 &BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003422 }
3423
Richard Trieudd225092011-09-15 21:56:47 +00003424 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00003425 // Diagnose use of pointer-to-member type which when used as
3426 // the functional cast in a pointer-to-member expression.
3427 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
3428 return QualType();
3429 }
John McCallf89e55a2010-11-18 06:31:45 +00003430
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003431 // C++ 5.5p2
3432 // The result is an object or a function of the type specified by the
3433 // second operand.
3434 // The cv qualifiers are the union of those in the pointer and the left side,
3435 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003436 QualType Result = MemPtr->getPointeeType();
Richard Trieudd225092011-09-15 21:56:47 +00003437 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCallf89e55a2010-11-18 06:31:45 +00003438
Douglas Gregor6b4df912011-01-26 16:40:18 +00003439 // C++0x [expr.mptr.oper]p6:
3440 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003441 // ill-formed if the second operand is a pointer to member function with
3442 // ref-qualifier &. In a ->* expression or in a .* expression whose object
3443 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor6b4df912011-01-26 16:40:18 +00003444 // is a pointer to member function with ref-qualifier &&.
3445 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
3446 switch (Proto->getRefQualifier()) {
3447 case RQ_None:
3448 // Do nothing
3449 break;
3450
3451 case RQ_LValue:
Richard Trieudd225092011-09-15 21:56:47 +00003452 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
Douglas Gregor6b4df912011-01-26 16:40:18 +00003453 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieudd225092011-09-15 21:56:47 +00003454 << RHSType << 1 << LHS.get()->getSourceRange();
Douglas Gregor6b4df912011-01-26 16:40:18 +00003455 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003456
Douglas Gregor6b4df912011-01-26 16:40:18 +00003457 case RQ_RValue:
Richard Trieudd225092011-09-15 21:56:47 +00003458 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor6b4df912011-01-26 16:40:18 +00003459 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieudd225092011-09-15 21:56:47 +00003460 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor6b4df912011-01-26 16:40:18 +00003461 break;
3462 }
3463 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003464
John McCallf89e55a2010-11-18 06:31:45 +00003465 // C++ [expr.mptr.oper]p6:
3466 // The result of a .* expression whose second operand is a pointer
3467 // to a data member is of the same value category as its
3468 // first operand. The result of a .* expression whose second
3469 // operand is a pointer to a member function is a prvalue. The
3470 // result of an ->* expression is an lvalue if its second operand
3471 // is a pointer to data member and a prvalue otherwise.
John McCall864c0412011-04-26 20:42:42 +00003472 if (Result->isFunctionType()) {
John McCallf89e55a2010-11-18 06:31:45 +00003473 VK = VK_RValue;
John McCall864c0412011-04-26 20:42:42 +00003474 return Context.BoundMemberTy;
3475 } else if (isIndirect) {
John McCallf89e55a2010-11-18 06:31:45 +00003476 VK = VK_LValue;
John McCall864c0412011-04-26 20:42:42 +00003477 } else {
Richard Trieudd225092011-09-15 21:56:47 +00003478 VK = LHS.get()->getValueKind();
John McCall864c0412011-04-26 20:42:42 +00003479 }
John McCallf89e55a2010-11-18 06:31:45 +00003480
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003481 return Result;
3482}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003483
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003484/// \brief Try to convert a type to another according to C++0x 5.16p3.
3485///
3486/// This is part of the parameter validation for the ? operator. If either
3487/// value operand is a class type, the two operands are attempted to be
3488/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003489/// It returns true if the program is ill-formed and has already been diagnosed
3490/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003491static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
3492 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00003493 bool &HaveConversion,
3494 QualType &ToType) {
3495 HaveConversion = false;
3496 ToType = To->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003497
3498 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00003499 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003500 // C++0x 5.16p3
3501 // The process for determining whether an operand expression E1 of type T1
3502 // can be converted to match an operand expression E2 of type T2 is defined
3503 // as follows:
3504 // -- If E2 is an lvalue:
John McCall7eb0a9e2010-11-24 05:12:34 +00003505 bool ToIsLvalue = To->isLValue();
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00003506 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003507 // E1 can be converted to match E2 if E1 can be implicitly converted to
3508 // type "lvalue reference to T2", subject to the constraint that in the
3509 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003510 QualType T = Self.Context.getLValueReferenceType(ToType);
3511 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003512
Douglas Gregorb70cf442010-03-26 20:14:36 +00003513 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3514 if (InitSeq.isDirectReferenceBinding()) {
3515 ToType = T;
3516 HaveConversion = true;
3517 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003518 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003519
Douglas Gregorb70cf442010-03-26 20:14:36 +00003520 if (InitSeq.isAmbiguous())
3521 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003522 }
John McCallb1bdc622010-02-25 01:37:24 +00003523
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003524 // -- If E2 is an rvalue, or if the conversion above cannot be done:
3525 // -- if E1 and E2 have class type, and the underlying class types are
3526 // the same or one is a base class of the other:
3527 QualType FTy = From->getType();
3528 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003529 const RecordType *FRec = FTy->getAs<RecordType>();
3530 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003531 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00003532 Self.IsDerivedFrom(FTy, TTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003533 if (FRec && TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00003534 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003535 // E1 can be converted to match E2 if the class of T2 is the
3536 // same type as, or a base class of, the class of T1, and
3537 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00003538 if (FRec == TRec || FDerivedFromT) {
3539 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003540 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3541 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003542 if (InitSeq) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003543 HaveConversion = true;
3544 return false;
3545 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003546
Douglas Gregorb70cf442010-03-26 20:14:36 +00003547 if (InitSeq.isAmbiguous())
3548 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003549 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003550 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003551
Douglas Gregorb70cf442010-03-26 20:14:36 +00003552 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003553 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003554
Douglas Gregorb70cf442010-03-26 20:14:36 +00003555 // -- Otherwise: E1 can be converted to match E2 if E1 can be
3556 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003557 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00003558 // an rvalue).
3559 //
3560 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
3561 // to the array-to-pointer or function-to-pointer conversions.
3562 if (!TTy->getAs<TagType>())
3563 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003564
Douglas Gregorb70cf442010-03-26 20:14:36 +00003565 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3566 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003567 HaveConversion = !InitSeq.Failed();
Douglas Gregorb70cf442010-03-26 20:14:36 +00003568 ToType = TTy;
3569 if (InitSeq.isAmbiguous())
3570 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3571
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003572 return false;
3573}
3574
3575/// \brief Try to find a common type for two according to C++0x 5.16p5.
3576///
3577/// This is part of the parameter validation for the ? operator. If either
3578/// value operand is a class type, overload resolution is used to find a
3579/// conversion to a common type.
John Wiegley429bb272011-04-08 18:41:53 +00003580static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth82214a82011-02-18 23:54:50 +00003581 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00003582 Expr *Args[2] = { LHS.get(), RHS.get() };
Chandler Carruth82214a82011-02-18 23:54:50 +00003583 OverloadCandidateSet CandidateSet(QuestionLoc);
3584 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
3585 CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003586
3587 OverloadCandidateSet::iterator Best;
Chandler Carruth82214a82011-02-18 23:54:50 +00003588 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley429bb272011-04-08 18:41:53 +00003589 case OR_Success: {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003590 // We found a match. Perform the conversions on the arguments and move on.
John Wiegley429bb272011-04-08 18:41:53 +00003591 ExprResult LHSRes =
3592 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
3593 Best->Conversions[0], Sema::AA_Converting);
3594 if (LHSRes.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003595 break;
John Wiegley429bb272011-04-08 18:41:53 +00003596 LHS = move(LHSRes);
3597
3598 ExprResult RHSRes =
3599 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
3600 Best->Conversions[1], Sema::AA_Converting);
3601 if (RHSRes.isInvalid())
3602 break;
3603 RHS = move(RHSRes);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003604 if (Best->Function)
3605 Self.MarkDeclarationReferenced(QuestionLoc, Best->Function);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003606 return false;
John Wiegley429bb272011-04-08 18:41:53 +00003607 }
3608
Douglas Gregor20093b42009-12-09 23:02:17 +00003609 case OR_No_Viable_Function:
Chandler Carruth82214a82011-02-18 23:54:50 +00003610
3611 // Emit a better diagnostic if one of the expressions is a null pointer
3612 // constant and the other is a pointer type. In this case, the user most
3613 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00003614 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00003615 return true;
3616
3617 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00003618 << LHS.get()->getType() << RHS.get()->getType()
3619 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003620 return true;
3621
Douglas Gregor20093b42009-12-09 23:02:17 +00003622 case OR_Ambiguous:
Chandler Carruth82214a82011-02-18 23:54:50 +00003623 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley429bb272011-04-08 18:41:53 +00003624 << LHS.get()->getType() << RHS.get()->getType()
3625 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00003626 // FIXME: Print the possible common types by printing the return types of
3627 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003628 break;
3629
Douglas Gregor20093b42009-12-09 23:02:17 +00003630 case OR_Deleted:
David Blaikieb219cfc2011-09-23 05:06:16 +00003631 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003632 }
3633 return true;
3634}
3635
Sebastian Redl76458502009-04-17 16:30:52 +00003636/// \brief Perform an "extended" implicit conversion as returned by
3637/// TryClassUnification.
John Wiegley429bb272011-04-08 18:41:53 +00003638static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003639 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley429bb272011-04-08 18:41:53 +00003640 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00003641 SourceLocation());
John Wiegley429bb272011-04-08 18:41:53 +00003642 Expr *Arg = E.take();
3643 InitializationSequence InitSeq(Self, Entity, Kind, &Arg, 1);
3644 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&Arg, 1));
Douglas Gregorb70cf442010-03-26 20:14:36 +00003645 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00003646 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003647
John Wiegley429bb272011-04-08 18:41:53 +00003648 E = Result;
Sebastian Redl76458502009-04-17 16:30:52 +00003649 return false;
3650}
3651
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003652/// \brief Check the operands of ?: under C++ semantics.
3653///
3654/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
3655/// extension. In this case, LHS == Cond. (But they're not aliases.)
John Wiegley429bb272011-04-08 18:41:53 +00003656QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCall56ca35d2011-02-17 10:25:35 +00003657 ExprValueKind &VK, ExprObjectKind &OK,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003658 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00003659 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
3660 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003661
3662 // C++0x 5.16p1
3663 // The first expression is contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00003664 if (!Cond.get()->isTypeDependent()) {
3665 ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
3666 if (CondRes.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003667 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003668 Cond = move(CondRes);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003669 }
3670
John McCallf89e55a2010-11-18 06:31:45 +00003671 // Assume r-value.
3672 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00003673 OK = OK_Ordinary;
John McCallf89e55a2010-11-18 06:31:45 +00003674
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003675 // Either of the arguments dependent?
John Wiegley429bb272011-04-08 18:41:53 +00003676 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003677 return Context.DependentTy;
3678
3679 // C++0x 5.16p2
3680 // If either the second or the third operand has type (cv) void, ...
John Wiegley429bb272011-04-08 18:41:53 +00003681 QualType LTy = LHS.get()->getType();
3682 QualType RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003683 bool LVoid = LTy->isVoidType();
3684 bool RVoid = RTy->isVoidType();
3685 if (LVoid || RVoid) {
3686 // ... then the [l2r] conversions are performed on the second and third
3687 // operands ...
John Wiegley429bb272011-04-08 18:41:53 +00003688 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3689 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3690 if (LHS.isInvalid() || RHS.isInvalid())
3691 return QualType();
3692 LTy = LHS.get()->getType();
3693 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003694
3695 // ... and one of the following shall hold:
3696 // -- The second or the third operand (but not both) is a throw-
3697 // expression; the result is of the type of the other and is an rvalue.
John Wiegley429bb272011-04-08 18:41:53 +00003698 bool LThrow = isa<CXXThrowExpr>(LHS.get());
3699 bool RThrow = isa<CXXThrowExpr>(RHS.get());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003700 if (LThrow && !RThrow)
3701 return RTy;
3702 if (RThrow && !LThrow)
3703 return LTy;
3704
3705 // -- Both the second and third operands have type void; the result is of
3706 // type void and is an rvalue.
3707 if (LVoid && RVoid)
3708 return Context.VoidTy;
3709
3710 // Neither holds, error.
3711 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
3712 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley429bb272011-04-08 18:41:53 +00003713 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003714 return QualType();
3715 }
3716
3717 // Neither is void.
3718
3719 // C++0x 5.16p3
3720 // Otherwise, if the second and third operand have different types, and
3721 // either has (cv) class type, and attempt is made to convert each of those
3722 // operands to the other.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003723 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003724 (LTy->isRecordType() || RTy->isRecordType())) {
3725 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
3726 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003727 QualType L2RType, R2LType;
3728 bool HaveL2R, HaveR2L;
John Wiegley429bb272011-04-08 18:41:53 +00003729 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003730 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003731 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003732 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003733
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003734 // If both can be converted, [...] the program is ill-formed.
3735 if (HaveL2R && HaveR2L) {
3736 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley429bb272011-04-08 18:41:53 +00003737 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003738 return QualType();
3739 }
3740
3741 // If exactly one conversion is possible, that conversion is applied to
3742 // the chosen operand and the converted operands are used in place of the
3743 // original operands for the remainder of this section.
3744 if (HaveL2R) {
John Wiegley429bb272011-04-08 18:41:53 +00003745 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003746 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003747 LTy = LHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003748 } else if (HaveR2L) {
John Wiegley429bb272011-04-08 18:41:53 +00003749 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003750 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003751 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003752 }
3753 }
3754
3755 // C++0x 5.16p4
John McCallf89e55a2010-11-18 06:31:45 +00003756 // If the second and third operands are glvalues of the same value
3757 // category and have the same type, the result is of that type and
3758 // value category and it is a bit-field if the second or the third
3759 // operand is a bit-field, or if both are bit-fields.
John McCall09431682010-11-18 19:01:18 +00003760 // We only extend this to bitfields, not to the crazy other kinds of
3761 // l-values.
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003762 bool Same = Context.hasSameType(LTy, RTy);
John McCallf89e55a2010-11-18 06:31:45 +00003763 if (Same &&
John Wiegley429bb272011-04-08 18:41:53 +00003764 LHS.get()->isGLValue() &&
3765 LHS.get()->getValueKind() == RHS.get()->getValueKind() &&
3766 LHS.get()->isOrdinaryOrBitFieldObject() &&
3767 RHS.get()->isOrdinaryOrBitFieldObject()) {
3768 VK = LHS.get()->getValueKind();
3769 if (LHS.get()->getObjectKind() == OK_BitField ||
3770 RHS.get()->getObjectKind() == OK_BitField)
John McCall09431682010-11-18 19:01:18 +00003771 OK = OK_BitField;
John McCallf89e55a2010-11-18 06:31:45 +00003772 return LTy;
Fariborz Jahanian3911a1a2010-09-25 01:08:05 +00003773 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003774
3775 // C++0x 5.16p5
3776 // Otherwise, the result is an rvalue. If the second and third operands
3777 // do not have the same type, and either has (cv) class type, ...
3778 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
3779 // ... overload resolution is used to determine the conversions (if any)
3780 // to be applied to the operands. If the overload resolution fails, the
3781 // program is ill-formed.
3782 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
3783 return QualType();
3784 }
3785
3786 // C++0x 5.16p6
3787 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
3788 // conversions are performed on the second and third operands.
John Wiegley429bb272011-04-08 18:41:53 +00003789 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3790 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3791 if (LHS.isInvalid() || RHS.isInvalid())
3792 return QualType();
3793 LTy = LHS.get()->getType();
3794 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003795
3796 // After those conversions, one of the following shall hold:
3797 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00003798 // is of that type. If the operands have class type, the result
3799 // is a prvalue temporary of the result type, which is
3800 // copy-initialized from either the second operand or the third
3801 // operand depending on the value of the first operand.
3802 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
3803 if (LTy->isRecordType()) {
3804 // The operands have class type. Make a temporary copy.
3805 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003806 ExprResult LHSCopy = PerformCopyInitialization(Entity,
3807 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00003808 LHS);
Douglas Gregorb65a4582010-05-19 23:40:50 +00003809 if (LHSCopy.isInvalid())
3810 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003811
3812 ExprResult RHSCopy = PerformCopyInitialization(Entity,
3813 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00003814 RHS);
Douglas Gregorb65a4582010-05-19 23:40:50 +00003815 if (RHSCopy.isInvalid())
3816 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003817
John Wiegley429bb272011-04-08 18:41:53 +00003818 LHS = LHSCopy;
3819 RHS = RHSCopy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00003820 }
3821
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003822 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00003823 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003824
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003825 // Extension: conditional operator involving vector types.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003826 if (LTy->isVectorType() || RTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00003827 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003828
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003829 // -- The second and third operands have arithmetic or enumeration type;
3830 // the usual arithmetic conversions are performed to bring them to a
3831 // common type, and the result is of that type.
3832 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
3833 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00003834 if (LHS.isInvalid() || RHS.isInvalid())
3835 return QualType();
3836 return LHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003837 }
3838
3839 // -- The second and third operands have pointer type, or one has pointer
3840 // type and the other is a null pointer constant; pointer conversions
3841 // and qualification conversions are performed to bring them to their
3842 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00003843 // -- The second and third operands have pointer to member type, or one has
3844 // pointer to member type and the other is a null pointer constant;
3845 // pointer to member conversions and qualification conversions are
3846 // performed to bring them to a common type, whose cv-qualification
3847 // shall match the cv-qualification of either the second or the third
3848 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003849 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003850 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003851 isSFINAEContext()? 0 : &NonStandardCompositeType);
3852 if (!Composite.isNull()) {
3853 if (NonStandardCompositeType)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003854 Diag(QuestionLoc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003855 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
3856 << LTy << RTy << Composite
John Wiegley429bb272011-04-08 18:41:53 +00003857 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003858
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003859 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003860 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003861
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003862 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00003863 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
3864 if (!Composite.isNull())
3865 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003866
Chandler Carruth7ef93242011-02-19 00:13:59 +00003867 // Check if we are using a null with a non-pointer type.
John Wiegley429bb272011-04-08 18:41:53 +00003868 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth7ef93242011-02-19 00:13:59 +00003869 return QualType();
3870
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003871 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00003872 << LHS.get()->getType() << RHS.get()->getType()
3873 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003874 return QualType();
3875}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003876
3877/// \brief Find a merged pointer type and convert the two expressions to it.
3878///
Douglas Gregor20b3e992009-08-24 17:42:35 +00003879/// This finds the composite pointer type (or member pointer type) for @p E1
3880/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
3881/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003882/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003883///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003884/// \param Loc The location of the operator requiring these two expressions to
3885/// be converted to the composite pointer type.
3886///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003887/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
3888/// a non-standard (but still sane) composite type to which both expressions
3889/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
3890/// will be set true.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003891QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003892 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003893 bool *NonStandardCompositeType) {
3894 if (NonStandardCompositeType)
3895 *NonStandardCompositeType = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003896
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003897 assert(getLangOptions().CPlusPlus && "This function assumes C++");
3898 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003899
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00003900 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
3901 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00003902 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003903
3904 // C++0x 5.9p2
3905 // Pointer conversions and qualification conversions are performed on
3906 // pointer operands to bring them to their composite pointer type. If
3907 // one operand is a null pointer constant, the composite pointer type is
3908 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00003909 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003910 if (T2->isMemberPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00003911 E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003912 else
John Wiegley429bb272011-04-08 18:41:53 +00003913 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003914 return T2;
3915 }
Douglas Gregorce940492009-09-25 04:25:58 +00003916 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003917 if (T1->isMemberPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00003918 E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003919 else
John Wiegley429bb272011-04-08 18:41:53 +00003920 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003921 return T1;
3922 }
Mike Stump1eb44332009-09-09 15:08:12 +00003923
Douglas Gregor20b3e992009-08-24 17:42:35 +00003924 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003925 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
3926 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003927 return QualType();
3928
3929 // Otherwise, of one of the operands has type "pointer to cv1 void," then
3930 // the other has type "pointer to cv2 T" and the composite pointer type is
3931 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
3932 // Otherwise, the composite pointer type is a pointer type similar to the
3933 // type of one of the operands, with a cv-qualification signature that is
3934 // the union of the cv-qualification signatures of the operand types.
3935 // In practice, the first part here is redundant; it's subsumed by the second.
3936 // What we do here is, we build the two possible composite types, and try the
3937 // conversions in both directions. If only one works, or if the two composite
3938 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00003939 // FIXME: extended qualifiers?
Chris Lattner5f9e2722011-07-23 10:55:15 +00003940 typedef SmallVector<unsigned, 4> QualifierVector;
Sebastian Redla439e6f2009-11-16 21:03:45 +00003941 QualifierVector QualifierUnion;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003942 typedef SmallVector<std::pair<const Type *, const Type *>, 4>
Sebastian Redla439e6f2009-11-16 21:03:45 +00003943 ContainingClassVector;
3944 ContainingClassVector MemberOfClass;
3945 QualType Composite1 = Context.getCanonicalType(T1),
3946 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003947 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00003948 do {
3949 const PointerType *Ptr1, *Ptr2;
3950 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3951 (Ptr2 = Composite2->getAs<PointerType>())) {
3952 Composite1 = Ptr1->getPointeeType();
3953 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003954
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003955 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003956 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003957 if (NonStandardCompositeType &&
3958 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3959 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003960
Douglas Gregor20b3e992009-08-24 17:42:35 +00003961 QualifierUnion.push_back(
3962 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3963 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3964 continue;
3965 }
Mike Stump1eb44332009-09-09 15:08:12 +00003966
Douglas Gregor20b3e992009-08-24 17:42:35 +00003967 const MemberPointerType *MemPtr1, *MemPtr2;
3968 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3969 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3970 Composite1 = MemPtr1->getPointeeType();
3971 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003972
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003973 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003974 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003975 if (NonStandardCompositeType &&
3976 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3977 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003978
Douglas Gregor20b3e992009-08-24 17:42:35 +00003979 QualifierUnion.push_back(
3980 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3981 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
3982 MemPtr2->getClass()));
3983 continue;
3984 }
Mike Stump1eb44332009-09-09 15:08:12 +00003985
Douglas Gregor20b3e992009-08-24 17:42:35 +00003986 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00003987
Douglas Gregor20b3e992009-08-24 17:42:35 +00003988 // Cannot unwrap any more types.
3989 break;
3990 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00003991
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003992 if (NeedConstBefore && NonStandardCompositeType) {
3993 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003994 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003995 // requirements of C++ [conv.qual]p4 bullet 3.
3996 for (unsigned I = 0; I != NeedConstBefore; ++I) {
3997 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
3998 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
3999 *NonStandardCompositeType = true;
4000 }
4001 }
4002 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004003
Douglas Gregor20b3e992009-08-24 17:42:35 +00004004 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00004005 ContainingClassVector::reverse_iterator MOC
4006 = MemberOfClass.rbegin();
4007 for (QualifierVector::reverse_iterator
4008 I = QualifierUnion.rbegin(),
4009 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00004010 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00004011 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00004012 if (MOC->first && MOC->second) {
4013 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00004014 Composite1 = Context.getMemberPointerType(
4015 Context.getQualifiedType(Composite1, Quals),
4016 MOC->first);
4017 Composite2 = Context.getMemberPointerType(
4018 Context.getQualifiedType(Composite2, Quals),
4019 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00004020 } else {
4021 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00004022 Composite1
4023 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
4024 Composite2
4025 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00004026 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004027 }
4028
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004029 // Try to convert to the first composite pointer type.
4030 InitializedEntity Entity1
4031 = InitializedEntity::InitializeTemporary(Composite1);
4032 InitializationKind Kind
4033 = InitializationKind::CreateCopy(Loc, SourceLocation());
4034 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
4035 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00004036
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004037 if (E1ToC1 && E2ToC1) {
4038 // Conversion to Composite1 is viable.
4039 if (!Context.hasSameType(Composite1, Composite2)) {
4040 // Composite2 is a different type from Composite1. Check whether
4041 // Composite2 is also viable.
4042 InitializedEntity Entity2
4043 = InitializedEntity::InitializeTemporary(Composite2);
4044 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4045 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4046 if (E1ToC2 && E2ToC2) {
4047 // Both Composite1 and Composite2 are viable and are different;
4048 // this is an ambiguity.
4049 return QualType();
4050 }
4051 }
4052
4053 // Convert E1 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00004054 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00004055 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004056 if (E1Result.isInvalid())
4057 return QualType();
4058 E1 = E1Result.takeAs<Expr>();
4059
4060 // Convert E2 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00004061 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00004062 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004063 if (E2Result.isInvalid())
4064 return QualType();
4065 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004066
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004067 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004068 }
4069
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004070 // Check whether Composite2 is viable.
4071 InitializedEntity Entity2
4072 = InitializedEntity::InitializeTemporary(Composite2);
4073 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4074 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4075 if (!E1ToC2 || !E2ToC2)
4076 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004077
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004078 // Convert E1 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00004079 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00004080 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004081 if (E1Result.isInvalid())
4082 return QualType();
4083 E1 = E1Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004084
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004085 // Convert E2 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00004086 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00004087 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004088 if (E2Result.isInvalid())
4089 return QualType();
4090 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004091
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004092 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004093}
Anders Carlsson165a0a02009-05-17 18:41:29 +00004094
John McCall60d7b3a2010-08-24 06:29:42 +00004095ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor19cc1c72010-11-01 21:10:29 +00004096 if (!E)
4097 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004098
John McCallf85e1932011-06-15 23:02:42 +00004099 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
4100
4101 // If the result is a glvalue, we shouldn't bind it.
4102 if (!E->isRValue())
Anders Carlsson089c2602009-08-15 23:41:35 +00004103 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004104
John McCallf85e1932011-06-15 23:02:42 +00004105 // In ARC, calls that return a retainable type can return retained,
4106 // in which case we have to insert a consuming cast.
4107 if (getLangOptions().ObjCAutoRefCount &&
4108 E->getType()->isObjCRetainableType()) {
4109
4110 bool ReturnsRetained;
4111
4112 // For actual calls, we compute this by examining the type of the
4113 // called value.
4114 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
4115 Expr *Callee = Call->getCallee()->IgnoreParens();
4116 QualType T = Callee->getType();
4117
4118 if (T == Context.BoundMemberTy) {
4119 // Handle pointer-to-members.
4120 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
4121 T = BinOp->getRHS()->getType();
4122 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
4123 T = Mem->getMemberDecl()->getType();
4124 }
4125
4126 if (const PointerType *Ptr = T->getAs<PointerType>())
4127 T = Ptr->getPointeeType();
4128 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
4129 T = Ptr->getPointeeType();
4130 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
4131 T = MemPtr->getPointeeType();
4132
4133 const FunctionType *FTy = T->getAs<FunctionType>();
4134 assert(FTy && "call to value not of function type?");
4135 ReturnsRetained = FTy->getExtInfo().getProducesResult();
4136
4137 // ActOnStmtExpr arranges things so that StmtExprs of retainable
4138 // type always produce a +1 object.
4139 } else if (isa<StmtExpr>(E)) {
4140 ReturnsRetained = true;
4141
4142 // For message sends and property references, we try to find an
4143 // actual method. FIXME: we should infer retention by selector in
4144 // cases where we don't have an actual method.
4145 } else {
John McCallfc4b1912011-08-03 07:02:44 +00004146 ObjCMethodDecl *D = 0;
John McCallf85e1932011-06-15 23:02:42 +00004147 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
4148 D = Send->getMethodDecl();
John McCallf85e1932011-06-15 23:02:42 +00004149 }
4150
4151 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCallfc4b1912011-08-03 07:02:44 +00004152
4153 // Don't do reclaims on performSelector calls; despite their
4154 // return type, the invoked method doesn't necessarily actually
4155 // return an object.
4156 if (!ReturnsRetained &&
4157 D && D->getMethodFamily() == OMF_performSelector)
4158 return Owned(E);
John McCallf85e1932011-06-15 23:02:42 +00004159 }
4160
John McCall567c5862011-11-14 19:53:16 +00004161 // Don't reclaim an object of Class type.
4162 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
4163 return Owned(E);
4164
John McCall7e5e5f42011-07-07 06:58:02 +00004165 ExprNeedsCleanups = true;
4166
John McCall33e56f32011-09-10 06:18:15 +00004167 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
4168 : CK_ARCReclaimReturnedObject);
John McCall7e5e5f42011-07-07 06:58:02 +00004169 return Owned(ImplicitCastExpr::Create(Context, E->getType(), ck, E, 0,
4170 VK_RValue));
John McCallf85e1932011-06-15 23:02:42 +00004171 }
4172
4173 if (!getLangOptions().CPlusPlus)
4174 return Owned(E);
Douglas Gregor51326552009-12-24 18:51:59 +00004175
Peter Collingbournebceb7552011-11-27 22:09:28 +00004176 QualType ET = Context.getBaseElementType(E->getType());
4177 const RecordType *RT = ET->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00004178 if (!RT)
4179 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004180
John McCall86ff3082010-02-04 22:26:26 +00004181 // That should be enough to guarantee that this type is complete.
4182 // If it has a trivial destructor, we can avoid the extra copy.
Jeffrey Yasskinb7ee2e52011-01-27 19:17:54 +00004183 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall507384f2010-08-12 02:40:37 +00004184 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall86ff3082010-02-04 22:26:26 +00004185 return Owned(E);
4186
John McCallf85e1932011-06-15 23:02:42 +00004187 CXXDestructorDecl *Destructor = LookupDestructor(RD);
4188
4189 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
4190 if (Destructor) {
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00004191 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00004192 CheckDestructorAccess(E->getExprLoc(), Destructor,
4193 PDiag(diag::err_access_dtor_temp)
4194 << E->getType());
John McCallf85e1932011-06-15 23:02:42 +00004195
John McCall80ee6e82011-11-10 05:35:25 +00004196 // We need a cleanup, but we don't need to remember the temporary.
John McCallf85e1932011-06-15 23:02:42 +00004197 ExprNeedsCleanups = true;
John McCallc91cc662010-04-07 00:41:46 +00004198 }
Anders Carlssondef11992009-05-30 20:36:53 +00004199 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
4200}
4201
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004202ExprResult
John McCall4765fa02010-12-06 08:20:24 +00004203Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregor90f93822009-12-22 22:17:25 +00004204 if (SubExpr.isInvalid())
4205 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004206
John McCall4765fa02010-12-06 08:20:24 +00004207 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregor90f93822009-12-22 22:17:25 +00004208}
4209
John McCall80ee6e82011-11-10 05:35:25 +00004210Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
4211 assert(SubExpr && "sub expression can't be null!");
4212
4213 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
4214 assert(ExprCleanupObjects.size() >= FirstCleanup);
4215 assert(ExprNeedsCleanups || ExprCleanupObjects.size() == FirstCleanup);
4216 if (!ExprNeedsCleanups)
4217 return SubExpr;
4218
4219 ArrayRef<ExprWithCleanups::CleanupObject> Cleanups
4220 = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
4221 ExprCleanupObjects.size() - FirstCleanup);
4222
4223 Expr *E = ExprWithCleanups::Create(Context, SubExpr, Cleanups);
4224 DiscardCleanupsInEvaluationContext();
4225
4226 return E;
4227}
4228
John McCall4765fa02010-12-06 08:20:24 +00004229Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004230 assert(SubStmt && "sub statement can't be null!");
4231
John McCallf85e1932011-06-15 23:02:42 +00004232 if (!ExprNeedsCleanups)
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004233 return SubStmt;
4234
4235 // FIXME: In order to attach the temporaries, wrap the statement into
4236 // a StmtExpr; currently this is only used for asm statements.
4237 // This is hacky, either create a new CXXStmtWithTemporaries statement or
4238 // a new AsmStmtWithTemporaries.
4239 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
4240 SourceLocation(),
4241 SourceLocation());
4242 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
4243 SourceLocation());
John McCall4765fa02010-12-06 08:20:24 +00004244 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004245}
4246
John McCall60d7b3a2010-08-24 06:29:42 +00004247ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004248Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallb3d87482010-08-24 05:47:05 +00004249 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00004250 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004251 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004252 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00004253 if (Result.isInvalid()) return ExprError();
4254 Base = Result.get();
Mike Stump1eb44332009-09-09 15:08:12 +00004255
John McCall3c3b7f92011-10-25 17:37:35 +00004256 Result = CheckPlaceholderExpr(Base);
4257 if (Result.isInvalid()) return ExprError();
4258 Base = Result.take();
4259
John McCall9ae2f072010-08-23 23:25:46 +00004260 QualType BaseType = Base->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00004261 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004262 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00004263 // If we have a pointer to a dependent type and are using the -> operator,
4264 // the object type is the type that the pointer points to. We might still
4265 // have enough information about that type to do something useful.
4266 if (OpKind == tok::arrow)
4267 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4268 BaseType = Ptr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004269
John McCallb3d87482010-08-24 05:47:05 +00004270 ObjectType = ParsedType::make(BaseType);
Douglas Gregord4dca082010-02-24 18:44:31 +00004271 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00004272 return Owned(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004273 }
Mike Stump1eb44332009-09-09 15:08:12 +00004274
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004275 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00004276 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004277 // returned, with the original second operand.
4278 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00004279 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00004280 llvm::SmallPtrSet<CanQualType,8> CTypes;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004281 SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00004282 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004283
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004284 while (BaseType->isRecordType()) {
John McCall9ae2f072010-08-23 23:25:46 +00004285 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
4286 if (Result.isInvalid())
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004287 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00004288 Base = Result.get();
4289 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonde699e52009-10-13 22:55:59 +00004290 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCall9ae2f072010-08-23 23:25:46 +00004291 BaseType = Base->getType();
John McCallc4e83212009-09-30 01:01:30 +00004292 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00004293 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00004294 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00004295 for (unsigned i = 0; i < Locations.size(); i++)
4296 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00004297 return ExprError();
4298 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004299 }
Mike Stump1eb44332009-09-09 15:08:12 +00004300
Douglas Gregor31658df2009-11-20 19:58:21 +00004301 if (BaseType->isPointerType())
4302 BaseType = BaseType->getPointeeType();
4303 }
Mike Stump1eb44332009-09-09 15:08:12 +00004304
4305 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004306 // vector types or Objective-C interfaces. Just return early and let
4307 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00004308 if (!BaseType->isRecordType()) {
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.
Douglas Gregord4dca082010-02-24 18:44:31 +00004313 //
4314 // This also indicates that we should be parsing a
4315 // pseudo-destructor-name.
John McCallb3d87482010-08-24 05:47:05 +00004316 ObjectType = ParsedType();
Douglas Gregord4dca082010-02-24 18:44:31 +00004317 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00004318 return Owned(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00004319 }
Mike Stump1eb44332009-09-09 15:08:12 +00004320
Douglas Gregor03c57052009-11-17 05:17:33 +00004321 // The object type must be complete (or dependent).
4322 if (!BaseType->isDependentType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004323 RequireCompleteType(OpLoc, BaseType,
Douglas Gregor03c57052009-11-17 05:17:33 +00004324 PDiag(diag::err_incomplete_member_access)))
4325 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004326
Douglas Gregorc68afe22009-09-03 21:38:09 +00004327 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004328 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00004329 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00004330 // type C (or of pointer to a class type C), the unqualified-id is looked
4331 // up in the scope of class C. [...]
John McCallb3d87482010-08-24 05:47:05 +00004332 ObjectType = ParsedType::make(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00004333 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004334}
4335
John McCall60d7b3a2010-08-24 06:29:42 +00004336ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCall9ae2f072010-08-23 23:25:46 +00004337 Expr *MemExpr) {
Douglas Gregor77549082010-02-24 21:29:12 +00004338 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCall9ae2f072010-08-23 23:25:46 +00004339 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
4340 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregor849b2432010-03-31 17:46:05 +00004341 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004342
Douglas Gregor77549082010-02-24 21:29:12 +00004343 return ActOnCallExpr(/*Scope*/ 0,
John McCall9ae2f072010-08-23 23:25:46 +00004344 MemExpr,
Douglas Gregor77549082010-02-24 21:29:12 +00004345 /*LPLoc*/ ExpectedLParenLoc,
John McCallf312b1e2010-08-26 23:41:50 +00004346 MultiExprArg(),
Douglas Gregor77549082010-02-24 21:29:12 +00004347 /*RPLoc*/ ExpectedLParenLoc);
4348}
Douglas Gregord4dca082010-02-24 18:44:31 +00004349
David Blaikie91ec7892011-12-16 16:03:09 +00004350static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *Base,
4351 tok::TokenKind& OpKind, SourceLocation OpLoc) {
4352 // C++ [expr.pseudo]p2:
4353 // The left-hand side of the dot operator shall be of scalar type. The
4354 // left-hand side of the arrow operator shall be of pointer to scalar type.
4355 // This scalar type is the object type.
4356 if (OpKind == tok::arrow) {
4357 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4358 ObjectType = Ptr->getPointeeType();
4359 } else if (!Base->isTypeDependent()) {
4360 // The user wrote "p->" when she probably meant "p."; fix it.
4361 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4362 << ObjectType << true
4363 << FixItHint::CreateReplacement(OpLoc, ".");
4364 if (S.isSFINAEContext())
4365 return true;
4366
4367 OpKind = tok::period;
4368 }
4369 }
4370
4371 return false;
4372}
4373
John McCall60d7b3a2010-08-24 06:29:42 +00004374ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00004375 SourceLocation OpLoc,
4376 tok::TokenKind OpKind,
4377 const CXXScopeSpec &SS,
4378 TypeSourceInfo *ScopeTypeInfo,
4379 SourceLocation CCLoc,
4380 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004381 PseudoDestructorTypeStorage Destructed,
John McCall2d9f5fa2011-02-25 05:21:17 +00004382 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004383 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004384
John McCall9ae2f072010-08-23 23:25:46 +00004385 QualType ObjectType = Base->getType();
David Blaikie91ec7892011-12-16 16:03:09 +00004386 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4387 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004388
Douglas Gregorb57fb492010-02-24 22:38:50 +00004389 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
4390 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
John McCall9ae2f072010-08-23 23:25:46 +00004391 << ObjectType << Base->getSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00004392 return ExprError();
4393 }
4394
4395 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004396 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb57fb492010-02-24 22:38:50 +00004397 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004398 if (DestructedTypeInfo) {
4399 QualType DestructedType = DestructedTypeInfo->getType();
4400 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004401 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCallf85e1932011-06-15 23:02:42 +00004402 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
4403 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
4404 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
4405 << ObjectType << DestructedType << Base->getSourceRange()
4406 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004407
John McCallf85e1932011-06-15 23:02:42 +00004408 // Recover by setting the destructed type to the object type.
4409 DestructedType = ObjectType;
4410 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004411 DestructedTypeStart);
John McCallf85e1932011-06-15 23:02:42 +00004412 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4413 } else if (DestructedType.getObjCLifetime() !=
4414 ObjectType.getObjCLifetime()) {
4415
4416 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
4417 // Okay: just pretend that the user provided the correctly-qualified
4418 // type.
4419 } else {
4420 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
4421 << ObjectType << DestructedType << Base->getSourceRange()
4422 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
4423 }
4424
4425 // Recover by setting the destructed type to the object type.
4426 DestructedType = ObjectType;
4427 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
4428 DestructedTypeStart);
4429 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4430 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004431 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00004432 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004433
Douglas Gregorb57fb492010-02-24 22:38:50 +00004434 // C++ [expr.pseudo]p2:
4435 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
4436 // form
4437 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004438 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb57fb492010-02-24 22:38:50 +00004439 //
4440 // shall designate the same scalar type.
4441 if (ScopeTypeInfo) {
4442 QualType ScopeType = ScopeTypeInfo->getType();
4443 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00004444 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004445
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004446 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00004447 diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00004448 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004449 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004450
Douglas Gregorb57fb492010-02-24 22:38:50 +00004451 ScopeType = QualType();
4452 ScopeTypeInfo = 0;
4453 }
4454 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004455
John McCall9ae2f072010-08-23 23:25:46 +00004456 Expr *Result
4457 = new (Context) CXXPseudoDestructorExpr(Context, Base,
4458 OpKind == tok::arrow, OpLoc,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00004459 SS.getWithLocInContext(Context),
John McCall9ae2f072010-08-23 23:25:46 +00004460 ScopeTypeInfo,
4461 CCLoc,
4462 TildeLoc,
4463 Destructed);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004464
Douglas Gregorb57fb492010-02-24 22:38:50 +00004465 if (HasTrailingLParen)
John McCall9ae2f072010-08-23 23:25:46 +00004466 return Owned(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004467
John McCall9ae2f072010-08-23 23:25:46 +00004468 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor77549082010-02-24 21:29:12 +00004469}
4470
John McCall60d7b3a2010-08-24 06:29:42 +00004471ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00004472 SourceLocation OpLoc,
4473 tok::TokenKind OpKind,
4474 CXXScopeSpec &SS,
4475 UnqualifiedId &FirstTypeName,
4476 SourceLocation CCLoc,
4477 SourceLocation TildeLoc,
4478 UnqualifiedId &SecondTypeName,
4479 bool HasTrailingLParen) {
Douglas Gregor77549082010-02-24 21:29:12 +00004480 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4481 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4482 "Invalid first type name in pseudo-destructor");
4483 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4484 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4485 "Invalid second type name in pseudo-destructor");
4486
John McCall9ae2f072010-08-23 23:25:46 +00004487 QualType ObjectType = Base->getType();
David Blaikie91ec7892011-12-16 16:03:09 +00004488 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4489 return ExprError();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004490
4491 // Compute the object type that we should use for name lookup purposes. Only
4492 // record types and dependent types matter.
John McCallb3d87482010-08-24 05:47:05 +00004493 ParsedType ObjectTypePtrForLookup;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004494 if (!SS.isSet()) {
John McCall2d9f5fa2011-02-25 05:21:17 +00004495 if (ObjectType->isRecordType())
4496 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallb3d87482010-08-24 05:47:05 +00004497 else if (ObjectType->isDependentType())
4498 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004499 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004500
4501 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb57fb492010-02-24 22:38:50 +00004502 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00004503 QualType DestructedType;
4504 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004505 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00004506 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004507 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00004508 SecondTypeName.StartLocation,
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +00004509 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004510 if (!T &&
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004511 ((SS.isSet() && !computeDeclContext(SS, false)) ||
4512 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004513 // The name of the type being destroyed is a dependent name, and we
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004514 // couldn't find anything useful in scope. Just store the identifier and
4515 // it's location, and we'll perform (qualified) name lookup again at
4516 // template instantiation time.
4517 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
4518 SecondTypeName.StartLocation);
4519 } else if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004520 Diag(SecondTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00004521 diag::err_pseudo_dtor_destructor_non_type)
4522 << SecondTypeName.Identifier << ObjectType;
4523 if (isSFINAEContext())
4524 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004525
Douglas Gregor77549082010-02-24 21:29:12 +00004526 // Recover by assuming we had the right type all along.
4527 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004528 } else
Douglas Gregor77549082010-02-24 21:29:12 +00004529 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004530 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00004531 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00004532 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004533 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4534 TemplateId->getTemplateArgs(),
4535 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00004536 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4537 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004538 TemplateId->TemplateNameLoc,
4539 TemplateId->LAngleLoc,
4540 TemplateArgsPtr,
4541 TemplateId->RAngleLoc);
4542 if (T.isInvalid() || !T.get()) {
4543 // Recover by assuming we had the right type all along.
4544 DestructedType = ObjectType;
4545 } else
4546 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004547 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004548
4549 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb57fb492010-02-24 22:38:50 +00004550 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004551 if (!DestructedType.isNull()) {
4552 if (!DestructedTypeInfo)
4553 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004554 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004555 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4556 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004557
Douglas Gregorb57fb492010-02-24 22:38:50 +00004558 // Convert the name of the scope type (the type prior to '::') into a type.
4559 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00004560 QualType ScopeType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004561 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor77549082010-02-24 21:29:12 +00004562 FirstTypeName.Identifier) {
4563 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004564 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00004565 FirstTypeName.StartLocation,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00004566 S, &SS, true, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00004567 if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004568 Diag(FirstTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00004569 diag::err_pseudo_dtor_destructor_non_type)
4570 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004571
Douglas Gregorb57fb492010-02-24 22:38:50 +00004572 if (isSFINAEContext())
4573 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004574
Douglas Gregorb57fb492010-02-24 22:38:50 +00004575 // Just drop this type. It's unnecessary anyway.
4576 ScopeType = QualType();
4577 } else
4578 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004579 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00004580 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00004581 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004582 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4583 TemplateId->getTemplateArgs(),
4584 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00004585 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4586 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004587 TemplateId->TemplateNameLoc,
4588 TemplateId->LAngleLoc,
4589 TemplateArgsPtr,
4590 TemplateId->RAngleLoc);
4591 if (T.isInvalid() || !T.get()) {
4592 // Recover by dropping this type.
4593 ScopeType = QualType();
4594 } else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004595 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004596 }
4597 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004598
Douglas Gregorb4a418f2010-02-24 23:02:30 +00004599 if (!ScopeType.isNull() && !ScopeTypeInfo)
4600 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
4601 FirstTypeName.StartLocation);
4602
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004603
John McCall9ae2f072010-08-23 23:25:46 +00004604 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00004605 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004606 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00004607}
4608
David Blaikie91ec7892011-12-16 16:03:09 +00004609ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4610 SourceLocation OpLoc,
4611 tok::TokenKind OpKind,
4612 SourceLocation TildeLoc,
4613 const DeclSpec& DS,
4614 bool HasTrailingLParen) {
4615
4616 QualType ObjectType = Base->getType();
4617 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4618 return ExprError();
4619
4620 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
4621
4622 TypeLocBuilder TLB;
4623 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
4624 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
4625 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
4626 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
4627
4628 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
4629 0, SourceLocation(), TildeLoc,
4630 Destructed, HasTrailingLParen);
4631}
4632
John Wiegley429bb272011-04-08 18:41:53 +00004633ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004634 CXXMethodDecl *Method,
4635 bool HadMultipleCandidates) {
John Wiegley429bb272011-04-08 18:41:53 +00004636 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
4637 FoundDecl, Method);
4638 if (Exp.isInvalid())
Douglas Gregorf2ae5262011-01-20 00:18:04 +00004639 return true;
Eli Friedman772fffa2009-12-09 04:53:56 +00004640
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004641 MemberExpr *ME =
John Wiegley429bb272011-04-08 18:41:53 +00004642 new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
Abramo Bagnara960809e2011-11-16 22:46:05 +00004643 SourceLocation(), Context.BoundMemberTy,
John McCallf89e55a2010-11-18 06:31:45 +00004644 VK_RValue, OK_Ordinary);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004645 if (HadMultipleCandidates)
4646 ME->setHadMultipleCandidates(true);
4647
John McCallf89e55a2010-11-18 06:31:45 +00004648 QualType ResultType = Method->getResultType();
4649 ExprValueKind VK = Expr::getValueKindForType(ResultType);
4650 ResultType = ResultType.getNonLValueExprType(Context);
4651
John Wiegley429bb272011-04-08 18:41:53 +00004652 MarkDeclarationReferenced(Exp.get()->getLocStart(), Method);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004653 CXXMemberCallExpr *CE =
John McCallf89e55a2010-11-18 06:31:45 +00004654 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
John Wiegley429bb272011-04-08 18:41:53 +00004655 Exp.get()->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00004656 return CE;
4657}
4658
Sebastian Redl2e156222010-09-10 20:55:43 +00004659ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4660 SourceLocation RParen) {
Sebastian Redl2e156222010-09-10 20:55:43 +00004661 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
4662 Operand->CanThrow(Context),
4663 KeyLoc, RParen));
4664}
4665
4666ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
4667 Expr *Operand, SourceLocation RParen) {
4668 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl02bc21a2010-09-10 20:55:37 +00004669}
4670
John McCallf6a16482010-12-04 03:47:34 +00004671/// Perform the conversions required for an expression used in a
4672/// context that ignores the result.
John Wiegley429bb272011-04-08 18:41:53 +00004673ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall3c3b7f92011-10-25 17:37:35 +00004674 if (E->hasPlaceholderType()) {
4675 ExprResult result = CheckPlaceholderExpr(E);
4676 if (result.isInvalid()) return Owned(E);
4677 E = result.take();
4678 }
4679
John McCalla878cda2010-12-02 02:07:15 +00004680 // C99 6.3.2.1:
4681 // [Except in specific positions,] an lvalue that does not have
4682 // array type is converted to the value stored in the
4683 // designated object (and is no longer an lvalue).
John McCalle6d134b2011-06-27 21:24:11 +00004684 if (E->isRValue()) {
4685 // In C, function designators (i.e. expressions of function type)
4686 // are r-values, but we still want to do function-to-pointer decay
4687 // on them. This is both technically correct and convenient for
4688 // some clients.
4689 if (!getLangOptions().CPlusPlus && E->getType()->isFunctionType())
4690 return DefaultFunctionArrayConversion(E);
4691
4692 return Owned(E);
4693 }
John McCalla878cda2010-12-02 02:07:15 +00004694
John McCallf6a16482010-12-04 03:47:34 +00004695 // Otherwise, this rule does not apply in C++, at least not for the moment.
John Wiegley429bb272011-04-08 18:41:53 +00004696 if (getLangOptions().CPlusPlus) return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004697
4698 // GCC seems to also exclude expressions of incomplete enum type.
4699 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
4700 if (!T->getDecl()->isComplete()) {
4701 // FIXME: stupid workaround for a codegen bug!
John Wiegley429bb272011-04-08 18:41:53 +00004702 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
4703 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004704 }
4705 }
4706
John Wiegley429bb272011-04-08 18:41:53 +00004707 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
4708 if (Res.isInvalid())
4709 return Owned(E);
4710 E = Res.take();
4711
John McCall85515d62010-12-04 12:29:11 +00004712 if (!E->getType()->isVoidType())
4713 RequireCompleteType(E->getExprLoc(), E->getType(),
4714 diag::err_incomplete_type);
John Wiegley429bb272011-04-08 18:41:53 +00004715 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004716}
4717
John Wiegley429bb272011-04-08 18:41:53 +00004718ExprResult Sema::ActOnFinishFullExpr(Expr *FE) {
4719 ExprResult FullExpr = Owned(FE);
4720
4721 if (!FullExpr.get())
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00004722 return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00004723
John Wiegley429bb272011-04-08 18:41:53 +00004724 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregord0937222010-12-13 22:49:22 +00004725 return ExprError();
4726
Douglas Gregor5e3a8be2011-12-15 00:53:32 +00004727 // Top-level message sends default to 'id' when we're in a debugger.
4728 if (getLangOptions().DebuggerSupport &&
4729 FullExpr.get()->getType() == Context.UnknownAnyTy &&
4730 isa<ObjCMessageExpr>(FullExpr.get())) {
4731 FullExpr = forceUnknownAnyToType(FullExpr.take(), Context.getObjCIdType());
4732 if (FullExpr.isInvalid())
4733 return ExprError();
4734 }
4735
John McCallfb8721c2011-04-10 19:13:55 +00004736 FullExpr = CheckPlaceholderExpr(FullExpr.take());
4737 if (FullExpr.isInvalid())
4738 return ExprError();
Douglas Gregor353ee242011-03-07 02:05:23 +00004739
John Wiegley429bb272011-04-08 18:41:53 +00004740 FullExpr = IgnoredValueConversions(FullExpr.take());
4741 if (FullExpr.isInvalid())
4742 return ExprError();
4743
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004744 CheckImplicitConversions(FullExpr.get(), FullExpr.get()->getExprLoc());
John McCall4765fa02010-12-06 08:20:24 +00004745 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson165a0a02009-05-17 18:41:29 +00004746}
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004747
4748StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
4749 if (!FullStmt) return StmtError();
4750
John McCall4765fa02010-12-06 08:20:24 +00004751 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004752}
Francois Pichet1e862692011-05-06 20:48:22 +00004753
Douglas Gregorba0513d2011-10-25 01:33:02 +00004754Sema::IfExistsResult
4755Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
4756 CXXScopeSpec &SS,
4757 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet1e862692011-05-06 20:48:22 +00004758 DeclarationName TargetName = TargetNameInfo.getName();
4759 if (!TargetName)
Douglas Gregor3896fc52011-10-24 22:31:10 +00004760 return IER_DoesNotExist;
Douglas Gregorba0513d2011-10-25 01:33:02 +00004761
Douglas Gregor3896fc52011-10-24 22:31:10 +00004762 // If the name itself is dependent, then the result is dependent.
4763 if (TargetName.isDependentName())
4764 return IER_Dependent;
Douglas Gregorba0513d2011-10-25 01:33:02 +00004765
Francois Pichet1e862692011-05-06 20:48:22 +00004766 // Do the redeclaration lookup in the current scope.
4767 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
4768 Sema::NotForRedeclaration);
Douglas Gregor3896fc52011-10-24 22:31:10 +00004769 LookupParsedName(R, S, &SS);
Francois Pichet1e862692011-05-06 20:48:22 +00004770 R.suppressDiagnostics();
Douglas Gregor3896fc52011-10-24 22:31:10 +00004771
4772 switch (R.getResultKind()) {
4773 case LookupResult::Found:
4774 case LookupResult::FoundOverloaded:
4775 case LookupResult::FoundUnresolvedValue:
4776 case LookupResult::Ambiguous:
4777 return IER_Exists;
4778
4779 case LookupResult::NotFound:
4780 return IER_DoesNotExist;
4781
4782 case LookupResult::NotFoundInCurrentInstantiation:
4783 return IER_Dependent;
4784 }
4785
Douglas Gregorba0513d2011-10-25 01:33:02 +00004786 return IER_DoesNotExist;
Francois Pichet1e862692011-05-06 20:48:22 +00004787}
Douglas Gregorba0513d2011-10-25 01:33:02 +00004788
Douglas Gregor65019ac2011-10-25 03:44:56 +00004789Sema::IfExistsResult
4790Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4791 bool IsIfExists, CXXScopeSpec &SS,
4792 UnqualifiedId &Name) {
Douglas Gregorba0513d2011-10-25 01:33:02 +00004793 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Douglas Gregor65019ac2011-10-25 03:44:56 +00004794
4795 // Check for unexpanded parameter packs.
4796 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
4797 collectUnexpandedParameterPacks(SS, Unexpanded);
4798 collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
4799 if (!Unexpanded.empty()) {
4800 DiagnoseUnexpandedParameterPacks(KeywordLoc,
4801 IsIfExists? UPPC_IfExists
4802 : UPPC_IfNotExists,
4803 Unexpanded);
4804 return IER_Error;
4805 }
4806
Douglas Gregorba0513d2011-10-25 01:33:02 +00004807 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
4808}
4809
Eli Friedmandc3b7232012-01-04 02:40:39 +00004810//===----------------------------------------------------------------------===//
4811// Lambdas.
4812//===----------------------------------------------------------------------===//
4813
Eli Friedmanec9ea722012-01-05 03:35:19 +00004814void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
4815 Declarator &ParamInfo,
4816 Scope *CurScope) {
4817 DeclContext *DC = CurContext;
Eli Friedman906a7e12012-01-06 03:05:34 +00004818 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
Eli Friedmanec9ea722012-01-05 03:35:19 +00004819 DC = DC->getParent();
Eli Friedmandc3b7232012-01-04 02:40:39 +00004820
Eli Friedmanec9ea722012-01-05 03:35:19 +00004821 // Start constructing the lambda class.
4822 CXXRecordDecl *Class = CXXRecordDecl::Create(Context, TTK_Class, DC,
4823 Intro.Range.getBegin(),
4824 /*IdLoc=*/SourceLocation(),
4825 /*Id=*/0);
4826 Class->startDefinition();
Eli Friedman72899c32012-01-07 04:59:52 +00004827 Class->setLambda(true);
Eli Friedmanec9ea722012-01-05 03:35:19 +00004828 CurContext->addDecl(Class);
Eli Friedmandc3b7232012-01-04 02:40:39 +00004829
Eli Friedmane81d7e92012-01-07 01:08:17 +00004830 QualType ThisCaptureType;
Eli Friedman72899c32012-01-07 04:59:52 +00004831 llvm::SmallVector<LambdaScopeInfo::Capture, 4> Captures;
Eli Friedmane81d7e92012-01-07 01:08:17 +00004832 llvm::DenseMap<const IdentifierInfo*, SourceLocation> CapturesSoFar;
4833 for (llvm::SmallVector<LambdaCapture, 4>::const_iterator
4834 C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E; ++C) {
4835 if (C->Kind == LCK_This) {
4836 if (!ThisCaptureType.isNull()) {
4837 Diag(C->Loc, diag::err_capture_more_than_once) << "'this'";
4838 continue;
4839 }
4840
4841 if (Intro.Default == LCD_ByCopy) {
4842 Diag(C->Loc, diag::err_this_capture_with_copy_default);
4843 continue;
4844 }
4845
4846 ThisCaptureType = getCurrentThisType();
Eli Friedmane81d7e92012-01-07 01:08:17 +00004847 if (ThisCaptureType.isNull()) {
4848 Diag(C->Loc, diag::err_invalid_this_use);
4849 continue;
4850 }
Eli Friedman72899c32012-01-07 04:59:52 +00004851 CheckCXXThisCapture(C->Loc);
4852
4853 Captures.push_back(LambdaScopeInfo::Capture::ThisCapture);
Eli Friedmane81d7e92012-01-07 01:08:17 +00004854 continue;
4855 }
4856
4857 assert(C->Id && "missing identifier for capture");
4858
4859 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
4860 Diag(C->Loc, diag::err_reference_capture_with_reference_default);
4861 continue;
4862 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
4863 Diag(C->Loc, diag::err_copy_capture_with_copy_default);
4864 continue;
4865 }
4866
4867 llvm::DenseMap<const IdentifierInfo*, SourceLocation>::iterator Appearance;
4868 bool IsFirstAppearance;
4869 llvm::tie(Appearance, IsFirstAppearance)
4870 = CapturesSoFar.insert(std::make_pair(C->Id, C->Loc));
4871
4872 if (!IsFirstAppearance) {
4873 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
4874 continue;
4875 }
4876
4877 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
4893 if (!Var->hasLocalStorage()) {
4894 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
4895 continue;
4896 }
4897
4898 // FIXME: Actually capturing a variable is much more complicated than this
4899 // in the general case; see shouldCaptureValueReference.
4900 // FIXME: Should we be building a DeclRefExpr here? We don't really need
4901 // it until the point where we're actually building the LambdaExpr.
Eli Friedman72899c32012-01-07 04:59:52 +00004902 Captures.push_back(LambdaScopeInfo::Capture(Var, C->Kind));
Eli Friedmane81d7e92012-01-07 01:08:17 +00004903 }
4904
Eli Friedmanec9ea722012-01-05 03:35:19 +00004905 // Build the call operator; we don't really have all the relevant information
4906 // at this point, but we need something to attach child declarations to.
Eli Friedman906a7e12012-01-06 03:05:34 +00004907 QualType MethodTy;
Eli Friedmanf88c4002012-01-04 04:41:38 +00004908 TypeSourceInfo *MethodTyInfo;
Eli Friedman906a7e12012-01-06 03:05:34 +00004909 if (ParamInfo.getNumTypeObjects() == 0) {
4910 FunctionProtoType::ExtProtoInfo EPI;
4911 EPI.TypeQuals |= DeclSpec::TQ_const;
4912 MethodTy = Context.getFunctionType(Context.DependentTy,
4913 /*Args=*/0, /*NumArgs=*/0, EPI);
4914 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
4915 } else {
4916 assert(ParamInfo.isFunctionDeclarator() &&
4917 "lambda-declarator is a function");
4918 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
4919 if (!FTI.hasMutableQualifier())
4920 FTI.TypeQuals |= DeclSpec::TQ_const;
4921 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
4922 // FIXME: Can these asserts actually fail?
4923 assert(MethodTyInfo && "no type from lambda-declarator");
4924 MethodTy = MethodTyInfo->getType();
4925 assert(!MethodTy.isNull() && "no type from lambda declarator");
4926 }
Eli Friedmanf88c4002012-01-04 04:41:38 +00004927
Eli Friedmanec9ea722012-01-05 03:35:19 +00004928 DeclarationName MethodName
4929 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
4930 CXXMethodDecl *Method
4931 = CXXMethodDecl::Create(Context,
4932 Class,
4933 ParamInfo.getSourceRange().getEnd(),
4934 DeclarationNameInfo(MethodName,
4935 /*NameLoc=*/SourceLocation()),
Eli Friedman906a7e12012-01-06 03:05:34 +00004936 MethodTy,
Eli Friedmanec9ea722012-01-05 03:35:19 +00004937 MethodTyInfo,
4938 /*isStatic=*/false,
4939 SC_None,
4940 /*isInline=*/true,
4941 /*isConstExpr=*/false,
4942 ParamInfo.getSourceRange().getEnd());
4943 Method->setAccess(AS_public);
4944 Class->addDecl(Method);
4945 Method->setLexicalDeclContext(DC); // FIXME: Is this really correct?
4946
Eli Friedmanec9ea722012-01-05 03:35:19 +00004947 ProcessDeclAttributes(CurScope, Method, ParamInfo);
4948
Eli Friedmanec9ea722012-01-05 03:35:19 +00004949 // Enter a new evaluation context to insulate the block from any
4950 // cleanups from the enclosing full-expression.
4951 PushExpressionEvaluationContext(PotentiallyEvaluated);
4952
4953 PushDeclContext(CurScope, Method);
Eli Friedman906a7e12012-01-06 03:05:34 +00004954
Eli Friedman906a7e12012-01-06 03:05:34 +00004955 // Set the parameters on the decl, if specified.
4956 if (isa<FunctionProtoTypeLoc>(MethodTyInfo->getTypeLoc())) {
4957 FunctionProtoTypeLoc Proto =
4958 cast<FunctionProtoTypeLoc>(MethodTyInfo->getTypeLoc());
4959 Method->setParams(Proto.getParams());
4960 CheckParmsForFunctionDef(Method->param_begin(),
4961 Method->param_end(),
4962 /*CheckParameterNames=*/false);
4963
4964 // Introduce our parameters into the function scope
4965 for (unsigned p = 0, NumParams = Method->getNumParams(); p < NumParams; ++p) {
4966 ParmVarDecl *Param = Method->getParamDecl(p);
4967 Param->setOwningFunction(Method);
4968
4969 // If this has an identifier, add it to the scope stack.
4970 if (Param->getIdentifier()) {
4971 CheckShadow(CurScope, Param);
4972
4973 PushOnScopeChains(Param, CurScope);
4974 }
4975 }
4976 }
4977
Eli Friedman72899c32012-01-07 04:59:52 +00004978 // Introduce the lambda scope.
4979 PushLambdaScope(Class);
4980
4981 LambdaScopeInfo *LSI = getCurLambda();
4982 LSI->Default = Intro.Default;
4983 if (!ThisCaptureType.isNull())
4984 LSI->CapturesCXXThis = true;
4985 std::swap(LSI->Captures, Captures);
4986
Eli Friedman906a7e12012-01-06 03:05:34 +00004987 const FunctionType *Fn = MethodTy->getAs<FunctionType>();
4988 QualType RetTy = Fn->getResultType();
4989 if (RetTy != Context.DependentTy) {
4990 LSI->ReturnType = RetTy;
4991 LSI->HasImplicitReturnType = true;
4992 }
4993
4994 // FIXME: Check return type is complete, !isObjCObjectType
4995
Eli Friedmandc3b7232012-01-04 02:40:39 +00004996}
4997
4998void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope) {
4999 // Leave the expression-evaluation context.
5000 DiscardCleanupsInEvaluationContext();
5001 PopExpressionEvaluationContext();
5002
5003 // Leave the context of the lambda.
Eli Friedmanec9ea722012-01-05 03:35:19 +00005004 PopDeclContext();
5005 PopFunctionScopeInfo();
Eli Friedmandc3b7232012-01-04 02:40:39 +00005006}
5007
5008ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc,
5009 Stmt *Body, Scope *CurScope) {
5010 // FIXME: Implement
5011 Diag(StartLoc, diag::err_lambda_unsupported);
5012 ActOnLambdaError(StartLoc, CurScope);
5013 return ExprError();
5014}