blob: ee25591529d774b8455b988a9c4c91be2d869709 [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--) {
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000683 if (CapturingScopeInfo *CSI =
684 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
685 if (CSI->CXXThisCaptureIndex != 0) {
686 // 'this' is already being captured; there isn't anything more to do.
Eli Friedman72899c32012-01-07 04:59:52 +0000687 break;
688 }
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000689 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
690 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block) {
691 // This closure can implicitly capture 'this'; continue looking upwards.
Eli Friedman72899c32012-01-07 04:59:52 +0000692 // FIXME: Is this check correct? The rules in the standard are a bit
693 // unclear.
694 NumClosures++;
695 continue;
696 }
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000697 // This context can't implicitly capture 'this'; fail out.
Eli Friedman72899c32012-01-07 04:59:52 +0000698 // (We need to delay the diagnostic in the
699 // PotentiallyPotentiallyEvaluated case because it doesn't apply to
700 // unevaluated contexts.)
701 if (ExprEvalContexts.back().Context == PotentiallyPotentiallyEvaluated)
702 ExprEvalContexts.back()
703 .addDiagnostic(Loc, PDiag(diag::err_implicit_this_capture));
704 else
705 Diag(Loc, diag::err_implicit_this_capture);
706 return;
707 }
Eli Friedman72899c32012-01-07 04:59:52 +0000708 break;
709 }
710
711 // Mark that we're implicitly capturing 'this' in all the scopes we skipped.
712 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
713 // contexts.
714 for (unsigned idx = FunctionScopes.size() - 1;
715 NumClosures; --idx, --NumClosures) {
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000716 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
717 bool isNested = NumClosures > 1;
718 CSI->AddThisCapture(isNested);
Eli Friedman72899c32012-01-07 04:59:52 +0000719 }
720}
721
Richard Smith7a614d82011-06-11 17:19:42 +0000722ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCall5808ce42011-02-03 08:15:49 +0000723 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
724 /// is a non-lvalue expression whose value is the address of the object for
725 /// which the function is called.
726
Douglas Gregor341350e2011-10-18 16:47:30 +0000727 QualType ThisTy = getCurrentThisType();
Richard Smith7a614d82011-06-11 17:19:42 +0000728 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCall5808ce42011-02-03 08:15:49 +0000729
Eli Friedman72899c32012-01-07 04:59:52 +0000730 CheckCXXThisCapture(Loc);
Richard Smith7a614d82011-06-11 17:19:42 +0000731 return Owned(new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000732}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000733
John McCall60d7b3a2010-08-24 06:29:42 +0000734ExprResult
Douglas Gregorab6677e2010-09-08 00:15:04 +0000735Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000736 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000737 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000738 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000739 if (!TypeRep)
740 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000741
John McCall9d125032010-01-15 18:39:57 +0000742 TypeSourceInfo *TInfo;
743 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
744 if (!TInfo)
745 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregorab6677e2010-09-08 00:15:04 +0000746
747 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
748}
749
750/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
751/// Can be interpreted either as function-style casting ("int(x)")
752/// or class type construction ("ClassType(x,y,z)")
753/// or creation of a value-initialized type ("int()").
754ExprResult
755Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
756 SourceLocation LParenLoc,
757 MultiExprArg exprs,
758 SourceLocation RParenLoc) {
759 QualType Ty = TInfo->getType();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000760 unsigned NumExprs = exprs.size();
761 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000762 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000763 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
764
Sebastian Redlf53597f2009-03-15 17:47:39 +0000765 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000766 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000767 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000768
Douglas Gregorab6677e2010-09-08 00:15:04 +0000769 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000770 LParenLoc,
771 Exprs, NumExprs,
772 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000773 }
774
Anders Carlssonbb60a502009-08-27 03:53:50 +0000775 if (Ty->isArrayType())
776 return ExprError(Diag(TyBeginLoc,
777 diag::err_value_init_for_array_type) << FullRange);
778 if (!Ty->isVoidType() &&
779 RequireCompleteType(TyBeginLoc, Ty,
780 PDiag(diag::err_invalid_incomplete_type_use)
781 << FullRange))
782 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000783
Anders Carlssonbb60a502009-08-27 03:53:50 +0000784 if (RequireNonAbstractType(TyBeginLoc, Ty,
785 diag::err_allocation_of_abstract_type))
786 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000787
788
Douglas Gregor506ae412009-01-16 18:33:17 +0000789 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000790 // If the expression list is a single expression, the type conversion
791 // expression is equivalent (in definedness, and if defined in meaning) to the
792 // corresponding cast expression.
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000793 if (NumExprs == 1) {
John McCallb45ae252011-10-05 07:41:44 +0000794 Expr *Arg = Exprs[0];
Anders Carlsson0aebc812009-09-09 21:33:21 +0000795 exprs.release();
John McCallb45ae252011-10-05 07:41:44 +0000796 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000797 }
798
Douglas Gregor19311e72010-09-08 21:40:08 +0000799 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
800 InitializationKind Kind
801 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
802 LParenLoc, RParenLoc)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000803 : InitializationKind::CreateValue(TyBeginLoc,
Douglas Gregor19311e72010-09-08 21:40:08 +0000804 LParenLoc, RParenLoc);
805 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
806 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redlf53597f2009-03-15 17:47:39 +0000807
Douglas Gregor19311e72010-09-08 21:40:08 +0000808 // FIXME: Improve AST representation?
809 return move(Result);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000810}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000811
John McCall6ec278d2011-01-27 09:37:56 +0000812/// doesUsualArrayDeleteWantSize - Answers whether the usual
813/// operator delete[] for the given type has a size_t parameter.
814static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
815 QualType allocType) {
816 const RecordType *record =
817 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
818 if (!record) return false;
819
820 // Try to find an operator delete[] in class scope.
821
822 DeclarationName deleteName =
823 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
824 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
825 S.LookupQualifiedName(ops, record->getDecl());
826
827 // We're just doing this for information.
828 ops.suppressDiagnostics();
829
830 // Very likely: there's no operator delete[].
831 if (ops.empty()) return false;
832
833 // If it's ambiguous, it should be illegal to call operator delete[]
834 // on this thing, so it doesn't matter if we allocate extra space or not.
835 if (ops.isAmbiguous()) return false;
836
837 LookupResult::Filter filter = ops.makeFilter();
838 while (filter.hasNext()) {
839 NamedDecl *del = filter.next()->getUnderlyingDecl();
840
841 // C++0x [basic.stc.dynamic.deallocation]p2:
842 // A template instance is never a usual deallocation function,
843 // regardless of its signature.
844 if (isa<FunctionTemplateDecl>(del)) {
845 filter.erase();
846 continue;
847 }
848
849 // C++0x [basic.stc.dynamic.deallocation]p2:
850 // If class T does not declare [an operator delete[] with one
851 // parameter] but does declare a member deallocation function
852 // named operator delete[] with exactly two parameters, the
853 // second of which has type std::size_t, then this function
854 // is a usual deallocation function.
855 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
856 filter.erase();
857 continue;
858 }
859 }
860 filter.done();
861
862 if (!ops.isSingleResult()) return false;
863
864 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
865 return (del->getNumParams() == 2);
866}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000867
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000868/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
869/// @code new (memory) int[size][4] @endcode
870/// or
871/// @code ::new Foo(23, "hello") @endcode
872/// For the interpretation of this heap of arguments, consult the base version.
John McCall60d7b3a2010-08-24 06:29:42 +0000873ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000874Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000875 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000876 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000877 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000878 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000879 SourceLocation ConstructorRParen) {
Richard Smith34b41d92011-02-20 03:19:35 +0000880 bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
881
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000882 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000883 // If the specified type is an array, unwrap it and save the expression.
884 if (D.getNumTypeObjects() > 0 &&
885 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
886 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smith34b41d92011-02-20 03:19:35 +0000887 if (TypeContainsAuto)
888 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
889 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000890 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000891 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
892 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000893 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000894 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
895 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000896
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000897 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000898 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000899 }
900
Douglas Gregor043cad22009-09-11 00:18:58 +0000901 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000902 if (ArraySize) {
903 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000904 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
905 break;
906
907 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
908 if (Expr *NumElts = (Expr *)Array.NumElts) {
909 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
910 !NumElts->isIntegerConstantExpr(Context)) {
911 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
912 << NumElts->getSourceRange();
913 return ExprError();
914 }
915 }
916 }
917 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000918
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +0000919 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
John McCallbf1a0282010-06-04 23:28:52 +0000920 QualType AllocType = TInfo->getType();
Chris Lattnereaaebc72009-04-25 08:06:05 +0000921 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000922 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000923
Mike Stump1eb44332009-09-09 15:08:12 +0000924 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000925 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000926 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000927 PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000928 TypeIdParens,
Mike Stump1eb44332009-09-09 15:08:12 +0000929 AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000930 TInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000931 ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000932 ConstructorLParen,
933 move(ConstructorArgs),
Richard Smith34b41d92011-02-20 03:19:35 +0000934 ConstructorRParen,
935 TypeContainsAuto);
Douglas Gregor3433cf72009-05-21 00:00:09 +0000936}
937
John McCall60d7b3a2010-08-24 06:29:42 +0000938ExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000939Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
940 SourceLocation PlacementLParen,
941 MultiExprArg PlacementArgs,
942 SourceLocation PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000943 SourceRange TypeIdParens,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000944 QualType AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000945 TypeSourceInfo *AllocTypeInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000946 Expr *ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000947 SourceLocation ConstructorLParen,
948 MultiExprArg ConstructorArgs,
Richard Smith34b41d92011-02-20 03:19:35 +0000949 SourceLocation ConstructorRParen,
950 bool TypeMayContainAuto) {
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000951 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000952
Richard Smith34b41d92011-02-20 03:19:35 +0000953 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
954 if (TypeMayContainAuto && AllocType->getContainedAutoType()) {
955 if (ConstructorArgs.size() == 0)
956 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
957 << AllocType << TypeRange);
958 if (ConstructorArgs.size() != 1) {
959 Expr *FirstBad = ConstructorArgs.get()[1];
960 return ExprError(Diag(FirstBad->getSourceRange().getBegin(),
961 diag::err_auto_new_ctor_multiple_expressions)
962 << AllocType << TypeRange);
963 }
Richard Smitha085da82011-03-17 16:11:59 +0000964 TypeSourceInfo *DeducedType = 0;
965 if (!DeduceAutoType(AllocTypeInfo, ConstructorArgs.get()[0], DeducedType))
Richard Smith34b41d92011-02-20 03:19:35 +0000966 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
967 << AllocType
968 << ConstructorArgs.get()[0]->getType()
969 << TypeRange
970 << ConstructorArgs.get()[0]->getSourceRange());
Richard Smitha085da82011-03-17 16:11:59 +0000971 if (!DeducedType)
972 return ExprError();
Richard Smith34b41d92011-02-20 03:19:35 +0000973
Richard Smitha085da82011-03-17 16:11:59 +0000974 AllocTypeInfo = DeducedType;
975 AllocType = AllocTypeInfo->getType();
Richard Smith34b41d92011-02-20 03:19:35 +0000976 }
977
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000978 // Per C++0x [expr.new]p5, the type being constructed may be a
979 // typedef of an array type.
John McCall9ae2f072010-08-23 23:25:46 +0000980 if (!ArraySize) {
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000981 if (const ConstantArrayType *Array
982 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000983 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
984 Context.getSizeType(),
985 TypeRange.getEnd());
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000986 AllocType = Array->getElementType();
987 }
988 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000989
Douglas Gregora0750762010-10-06 16:00:31 +0000990 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
991 return ExprError();
992
John McCallf85e1932011-06-15 23:02:42 +0000993 // In ARC, infer 'retaining' for the allocated
994 if (getLangOptions().ObjCAutoRefCount &&
995 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
996 AllocType->isObjCLifetimeType()) {
997 AllocType = Context.getLifetimeQualifiedType(AllocType,
998 AllocType->getObjCARCImplicitLifetime());
999 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001000
John McCallf85e1932011-06-15 23:02:42 +00001001 QualType ResultType = Context.getPointerType(AllocType);
1002
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001003 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
1004 // or enumeration type with a non-negative value."
Sebastian Redl28507842009-02-26 14:39:58 +00001005 if (ArraySize && !ArraySize->isTypeDependent()) {
John McCall806054d2012-01-11 00:14:46 +00001006 // Eliminate placeholders.
1007 ExprResult ConvertedSize = CheckPlaceholderExpr(ArraySize);
1008 if (ConvertedSize.isInvalid())
1009 return ExprError();
1010 ArraySize = ConvertedSize.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001011
John McCall806054d2012-01-11 00:14:46 +00001012 ConvertedSize = ConvertToIntegralOrEnumerationType(
Richard Smithebaf0e62011-10-18 20:49:44 +00001013 StartLoc, ArraySize,
1014 PDiag(diag::err_array_size_not_integral),
1015 PDiag(diag::err_array_size_incomplete_type)
1016 << ArraySize->getSourceRange(),
1017 PDiag(diag::err_array_size_explicit_conversion),
1018 PDiag(diag::note_array_size_conversion),
1019 PDiag(diag::err_array_size_ambiguous_conversion),
1020 PDiag(diag::note_array_size_conversion),
1021 PDiag(getLangOptions().CPlusPlus0x ?
1022 diag::warn_cxx98_compat_array_size_conversion :
1023 diag::ext_array_size_conversion));
Douglas Gregor6bc574d2010-06-30 00:20:43 +00001024 if (ConvertedSize.isInvalid())
1025 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001026
John McCall9ae2f072010-08-23 23:25:46 +00001027 ArraySize = ConvertedSize.take();
John McCall806054d2012-01-11 00:14:46 +00001028 QualType SizeType = ArraySize->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001029 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor6bc574d2010-06-30 00:20:43 +00001030 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001031
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001032 // Let's see if this is a constant < 0. If so, we reject it out of hand.
1033 // We don't care about special rules, so we tell the machinery it's not
1034 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +00001035 if (!ArraySize->isValueDependent()) {
1036 llvm::APSInt Value;
1037 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
1038 if (Value < llvm::APSInt(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001039 llvm::APInt::getNullValue(Value.getBitWidth()),
Anders Carlssonac18b2e2009-09-23 00:37:25 +00001040 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +00001041 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +00001042 diag::err_typecheck_negative_array_size)
Sebastian Redlf53597f2009-03-15 17:47:39 +00001043 << ArraySize->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001044
Douglas Gregor2767ce22010-08-18 00:39:00 +00001045 if (!AllocType->isDependentType()) {
1046 unsigned ActiveSizeBits
1047 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1048 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001049 Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +00001050 diag::err_array_too_large)
1051 << Value.toString(10)
1052 << ArraySize->getSourceRange();
1053 return ExprError();
1054 }
1055 }
Douglas Gregor4bd40312010-07-13 15:54:32 +00001056 } else if (TypeIdParens.isValid()) {
1057 // Can't have dynamic array size when the type-id is in parentheses.
1058 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1059 << ArraySize->getSourceRange()
1060 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1061 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001062
Douglas Gregor4bd40312010-07-13 15:54:32 +00001063 TypeIdParens = SourceRange();
Sebastian Redl28507842009-02-26 14:39:58 +00001064 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001065 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001066
John McCallf85e1932011-06-15 23:02:42 +00001067 // ARC: warn about ABI issues.
1068 if (getLangOptions().ObjCAutoRefCount) {
1069 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1070 if (BaseAllocType.hasStrongOrWeakObjCLifetime())
1071 Diag(StartLoc, diag::warn_err_new_delete_object_array)
1072 << 0 << BaseAllocType;
1073 }
1074
John McCall7d166272011-05-15 07:14:44 +00001075 // Note that we do *not* convert the argument in any way. It can
1076 // be signed, larger than size_t, whatever.
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001077 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001078
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001079 FunctionDecl *OperatorNew = 0;
1080 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +00001081 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
1082 unsigned NumPlaceArgs = PlacementArgs.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001083
Sebastian Redl28507842009-02-26 14:39:58 +00001084 if (!AllocType->isDependentType() &&
1085 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
1086 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +00001087 SourceRange(PlacementLParen, PlacementRParen),
1088 UseGlobal, AllocType, ArraySize, PlaceArgs,
1089 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +00001090 return ExprError();
John McCall6ec278d2011-01-27 09:37:56 +00001091
1092 // If this is an array allocation, compute whether the usual array
1093 // deallocation function for the type has a size_t parameter.
1094 bool UsualArrayDeleteWantsSize = false;
1095 if (ArraySize && !AllocType->isDependentType())
1096 UsualArrayDeleteWantsSize
1097 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1098
Chris Lattner5f9e2722011-07-23 10:55:15 +00001099 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001100 if (OperatorNew) {
1101 // Add default arguments, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001102 const FunctionProtoType *Proto =
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001103 OperatorNew->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001104 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00001105 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001106
Anders Carlsson28e94832010-05-03 02:07:56 +00001107 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001108 Proto, 1, PlaceArgs, NumPlaceArgs,
Anders Carlsson28e94832010-05-03 02:07:56 +00001109 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001110 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001111
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001112 NumPlaceArgs = AllPlaceArgs.size();
1113 if (NumPlaceArgs > 0)
1114 PlaceArgs = &AllPlaceArgs[0];
1115 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001116
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001117 bool Init = ConstructorLParen.isValid();
1118 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001119 CXXConstructorDecl *Constructor = 0;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001120 bool HadMultipleCandidates = false;
Sebastian Redlf53597f2009-03-15 17:47:39 +00001121 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
1122 unsigned NumConsArgs = ConstructorArgs.size();
John McCallca0408f2010-08-23 06:44:23 +00001123 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmana8ce9ec2009-11-08 22:15:39 +00001124
Anders Carlsson48c95012010-05-03 15:45:23 +00001125 // Array 'new' can't have any initializers.
Anders Carlsson55cbd6e2010-05-16 16:24:20 +00001126 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlsson48c95012010-05-03 15:45:23 +00001127 SourceRange InitRange(ConsArgs[0]->getLocStart(),
1128 ConsArgs[NumConsArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001129
Anders Carlsson48c95012010-05-03 15:45:23 +00001130 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1131 return ExprError();
1132 }
1133
Douglas Gregor99a2e602009-12-16 01:38:02 +00001134 if (!AllocType->isDependentType() &&
1135 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
1136 // C++0x [expr.new]p15:
1137 // A new-expression that creates an object of type T initializes that
1138 // object as follows:
1139 InitializationKind Kind
1140 // - If the new-initializer is omitted, the object is default-
1141 // initialized (8.5); if no initialization is performed,
1142 // the object has indeterminate value
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001143 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001144 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor99a2e602009-12-16 01:38:02 +00001145 // initialization rules of 8.5 for direct-initialization.
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001146 : InitializationKind::CreateDirect(TypeRange.getBegin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001147 ConstructorLParen,
Douglas Gregor99a2e602009-12-16 01:38:02 +00001148 ConstructorRParen);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001149
Douglas Gregor99a2e602009-12-16 01:38:02 +00001150 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00001151 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001152 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001153 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor99a2e602009-12-16 01:38:02 +00001154 move(ConstructorArgs));
1155 if (FullInit.isInvalid())
1156 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001157
1158 // FullInit is our initializer; walk through it to determine if it's a
Douglas Gregor99a2e602009-12-16 01:38:02 +00001159 // constructor call, which CXXNewExpr handles directly.
1160 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
1161 if (CXXBindTemporaryExpr *Binder
1162 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
1163 FullInitExpr = Binder->getSubExpr();
1164 if (CXXConstructExpr *Construct
1165 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
1166 Constructor = Construct->getConstructor();
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001167 HadMultipleCandidates = Construct->hadMultipleCandidates();
Douglas Gregor99a2e602009-12-16 01:38:02 +00001168 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
1169 AEnd = Construct->arg_end();
1170 A != AEnd; ++A)
John McCall3fa5cae2010-10-26 07:05:15 +00001171 ConvertedConstructorArgs.push_back(*A);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001172 } else {
1173 // Take the converted initializer.
1174 ConvertedConstructorArgs.push_back(FullInit.release());
1175 }
1176 } else {
1177 // No initialization required.
1178 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001179
Douglas Gregor99a2e602009-12-16 01:38:02 +00001180 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +00001181 NumConsArgs = ConvertedConstructorArgs.size();
1182 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001183 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001184
Douglas Gregor6d908702010-02-26 05:06:18 +00001185 // Mark the new and delete operators as referenced.
1186 if (OperatorNew)
1187 MarkDeclarationReferenced(StartLoc, OperatorNew);
1188 if (OperatorDelete)
1189 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1190
John McCall84ff0fc2011-07-13 20:12:57 +00001191 // C++0x [expr.new]p17:
1192 // If the new expression creates an array of objects of class type,
1193 // access and ambiguity control are done for the destructor.
1194 if (ArraySize && Constructor) {
1195 if (CXXDestructorDecl *dtor = LookupDestructor(Constructor->getParent())) {
1196 MarkDeclarationReferenced(StartLoc, dtor);
1197 CheckDestructorAccess(StartLoc, dtor,
1198 PDiag(diag::err_access_dtor)
1199 << Context.getBaseElementType(AllocType));
1200 }
1201 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001202
Sebastian Redlf53597f2009-03-15 17:47:39 +00001203 PlacementArgs.release();
1204 ConstructorArgs.release();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001205
Ted Kremenekad7fe862010-02-11 22:51:03 +00001206 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregor4bd40312010-07-13 15:54:32 +00001207 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001208 ArraySize, Constructor, Init,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001209 ConsArgs, NumConsArgs,
1210 HadMultipleCandidates,
1211 OperatorDelete,
John McCall6ec278d2011-01-27 09:37:56 +00001212 UsualArrayDeleteWantsSize,
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001213 ResultType, AllocTypeInfo,
1214 StartLoc,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001215 Init ? ConstructorRParen :
Chandler Carruth428edaf2010-10-25 08:47:36 +00001216 TypeRange.getEnd(),
1217 ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001218}
1219
1220/// CheckAllocatedType - Checks that a type is suitable as the allocated type
1221/// in a new-expression.
1222/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +00001223bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00001224 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001225 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1226 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +00001227 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001228 return Diag(Loc, diag::err_bad_new_type)
1229 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001230 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001231 return Diag(Loc, diag::err_bad_new_type)
1232 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001233 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +00001234 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001235 PDiag(diag::err_new_incomplete_type)
1236 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001237 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +00001238 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +00001239 diag::err_allocation_of_abstract_type))
1240 return true;
Douglas Gregora0750762010-10-06 16:00:31 +00001241 else if (AllocType->isVariablyModifiedType())
1242 return Diag(Loc, diag::err_variably_modified_new_type)
1243 << AllocType;
Douglas Gregor5666d362011-04-15 19:46:20 +00001244 else if (unsigned AddressSpace = AllocType.getAddressSpace())
1245 return Diag(Loc, diag::err_address_space_qualified_new)
1246 << AllocType.getUnqualifiedType() << AddressSpace;
John McCallf85e1932011-06-15 23:02:42 +00001247 else if (getLangOptions().ObjCAutoRefCount) {
1248 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
1249 QualType BaseAllocType = Context.getBaseElementType(AT);
1250 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1251 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001252 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001253 << BaseAllocType;
1254 }
1255 }
Douglas Gregor5666d362011-04-15 19:46:20 +00001256
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001257 return false;
1258}
1259
Douglas Gregor6d908702010-02-26 05:06:18 +00001260/// \brief Determine whether the given function is a non-placement
1261/// deallocation function.
1262static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1263 if (FD->isInvalidDecl())
1264 return false;
1265
1266 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1267 return Method->isUsualDeallocationFunction();
1268
1269 return ((FD->getOverloadedOperator() == OO_Delete ||
1270 FD->getOverloadedOperator() == OO_Array_Delete) &&
1271 FD->getNumParams() == 1);
1272}
1273
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001274/// FindAllocationFunctions - Finds the overloads of operator new and delete
1275/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001276bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1277 bool UseGlobal, QualType AllocType,
1278 bool IsArray, Expr **PlaceArgs,
1279 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001280 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +00001281 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001282 // --- Choosing an allocation function ---
1283 // C++ 5.3.4p8 - 14 & 18
1284 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1285 // in the scope of the allocated class.
1286 // 2) If an array size is given, look for operator new[], else look for
1287 // operator new.
1288 // 3) The first argument is always size_t. Append the arguments from the
1289 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001290
Chris Lattner5f9e2722011-07-23 10:55:15 +00001291 SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001292 // We don't care about the actual value of this argument.
1293 // FIXME: Should the Sema create the expression and embed it in the syntax
1294 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00001295 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001296 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssond67c4c32009-08-16 20:29:29 +00001297 Context.getSizeType(),
1298 SourceLocation());
1299 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001300 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1301
Douglas Gregor6d908702010-02-26 05:06:18 +00001302 // C++ [expr.new]p8:
1303 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001304 // function's name is operator new and the deallocation function's
Douglas Gregor6d908702010-02-26 05:06:18 +00001305 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001306 // type, the allocation function's name is operator new[] and the
1307 // deallocation function's name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001308 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1309 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +00001310 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1311 IsArray ? OO_Array_Delete : OO_Delete);
1312
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001313 QualType AllocElemType = Context.getBaseElementType(AllocType);
1314
1315 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +00001316 CXXRecordDecl *Record
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001317 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +00001318 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001319 AllocArgs.size(), Record, /*AllowMissing=*/true,
1320 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001321 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001322 }
1323 if (!OperatorNew) {
1324 // Didn't find a member overload. Look for a global one.
1325 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +00001326 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +00001327 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001328 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1329 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001330 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001331 }
1332
John McCall9c82afc2010-04-20 02:18:25 +00001333 // We don't need an operator delete if we're running under
1334 // -fno-exceptions.
1335 if (!getLangOptions().Exceptions) {
1336 OperatorDelete = 0;
1337 return false;
1338 }
1339
Anders Carlssond9583892009-05-31 20:26:12 +00001340 // FindAllocationOverload can change the passed in arguments, so we need to
1341 // copy them back.
1342 if (NumPlaceArgs > 0)
1343 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001344
Douglas Gregor6d908702010-02-26 05:06:18 +00001345 // C++ [expr.new]p19:
1346 //
1347 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001348 // deallocation function's name is looked up in the global
Douglas Gregor6d908702010-02-26 05:06:18 +00001349 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001350 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6d908702010-02-26 05:06:18 +00001351 // the scope of T. If this lookup fails to find the name, or if
1352 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001353 // deallocation function's name is looked up in the global scope.
Douglas Gregor6d908702010-02-26 05:06:18 +00001354 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001355 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001356 CXXRecordDecl *RD
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001357 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6d908702010-02-26 05:06:18 +00001358 LookupQualifiedName(FoundDelete, RD);
1359 }
John McCall90c8c572010-03-18 08:19:33 +00001360 if (FoundDelete.isAmbiguous())
1361 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +00001362
1363 if (FoundDelete.empty()) {
1364 DeclareGlobalNewDelete();
1365 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1366 }
1367
1368 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +00001369
Chris Lattner5f9e2722011-07-23 10:55:15 +00001370 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCall9aa472c2010-03-19 07:35:19 +00001371
John McCalledeb6c92010-09-14 21:34:24 +00001372 // Whether we're looking for a placement operator delete is dictated
1373 // by whether we selected a placement operator new, not by whether
1374 // we had explicit placement arguments. This matters for things like
1375 // struct A { void *operator new(size_t, int = 0); ... };
1376 // A *a = new A()
1377 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1378
1379 if (isPlacementNew) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001380 // C++ [expr.new]p20:
1381 // A declaration of a placement deallocation function matches the
1382 // declaration of a placement allocation function if it has the
1383 // same number of parameters and, after parameter transformations
1384 // (8.3.5), all parameter types except the first are
1385 // identical. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001386 //
Douglas Gregor6d908702010-02-26 05:06:18 +00001387 // To perform this comparison, we compute the function type that
1388 // the deallocation function should have, and use that type both
1389 // for template argument deduction and for comparison purposes.
John McCalle23cf432010-12-14 08:05:40 +00001390 //
1391 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6d908702010-02-26 05:06:18 +00001392 QualType ExpectedFunctionType;
1393 {
1394 const FunctionProtoType *Proto
1395 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00001396
Chris Lattner5f9e2722011-07-23 10:55:15 +00001397 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001398 ArgTypes.push_back(Context.VoidPtrTy);
Douglas Gregor6d908702010-02-26 05:06:18 +00001399 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1400 ArgTypes.push_back(Proto->getArgType(I));
1401
John McCalle23cf432010-12-14 08:05:40 +00001402 FunctionProtoType::ExtProtoInfo EPI;
1403 EPI.Variadic = Proto->isVariadic();
1404
Douglas Gregor6d908702010-02-26 05:06:18 +00001405 ExpectedFunctionType
1406 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
John McCalle23cf432010-12-14 08:05:40 +00001407 ArgTypes.size(), EPI);
Douglas Gregor6d908702010-02-26 05:06:18 +00001408 }
1409
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001410 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001411 DEnd = FoundDelete.end();
1412 D != DEnd; ++D) {
1413 FunctionDecl *Fn = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001414 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6d908702010-02-26 05:06:18 +00001415 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1416 // Perform template argument deduction to try to match the
1417 // expected function type.
1418 TemplateDeductionInfo Info(Context, StartLoc);
1419 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1420 continue;
1421 } else
1422 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1423
1424 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001425 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001426 }
1427 } else {
1428 // C++ [expr.new]p20:
1429 // [...] Any non-placement deallocation function matches a
1430 // non-placement allocation function. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001431 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001432 DEnd = FoundDelete.end();
1433 D != DEnd; ++D) {
1434 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1435 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001436 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001437 }
1438 }
1439
1440 // C++ [expr.new]p20:
1441 // [...] If the lookup finds a single matching deallocation
1442 // function, that function will be called; otherwise, no
1443 // deallocation function will be called.
1444 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001445 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001446
1447 // C++0x [expr.new]p20:
1448 // If the lookup finds the two-parameter form of a usual
1449 // deallocation function (3.7.4.2) and that function, considered
1450 // as a placement deallocation function, would have been
1451 // selected as a match for the allocation function, the program
1452 // is ill-formed.
1453 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1454 isNonPlacementDeallocationFunction(OperatorDelete)) {
1455 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001456 << SourceRange(PlaceArgs[0]->getLocStart(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001457 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1458 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1459 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001460 } else {
1461 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001462 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001463 }
1464 }
1465
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001466 return false;
1467}
1468
Sebastian Redl7f662392008-12-04 22:20:51 +00001469/// FindAllocationOverload - Find an fitting overload for the allocation
1470/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001471bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1472 DeclarationName Name, Expr** Args,
1473 unsigned NumArgs, DeclContext *Ctx,
Sean Hunt2be7e902011-05-12 22:46:29 +00001474 bool AllowMissing, FunctionDecl *&Operator,
1475 bool Diagnose) {
John McCalla24dc2e2009-11-17 02:14:36 +00001476 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1477 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001478 if (R.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001479 if (AllowMissing || !Diagnose)
Sebastian Redl7f662392008-12-04 22:20:51 +00001480 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001481 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001482 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001483 }
1484
John McCall90c8c572010-03-18 08:19:33 +00001485 if (R.isAmbiguous())
1486 return true;
1487
1488 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001489
John McCall5769d612010-02-08 23:07:23 +00001490 OverloadCandidateSet Candidates(StartLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001491 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001492 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001493 // Even member operator new/delete are implicitly treated as
1494 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001495 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001496
John McCall9aa472c2010-03-19 07:35:19 +00001497 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1498 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001499 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1500 Candidates,
1501 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001502 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001503 }
1504
John McCall9aa472c2010-03-19 07:35:19 +00001505 FunctionDecl *Fn = cast<FunctionDecl>(D);
1506 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001507 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001508 }
1509
1510 // Do the resolution.
1511 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00001512 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001513 case OR_Success: {
1514 // Got one!
1515 FunctionDecl *FnDecl = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00001516 MarkDeclarationReferenced(StartLoc, FnDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001517 // The first argument is size_t, and the first parameter must be size_t,
1518 // too. This is checked on declaration and can be assumed. (It can't be
1519 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001520 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001521 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1522 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001523 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1524 FnDecl->getParamDecl(i));
1525
1526 if (!Diagnose && !CanPerformCopyInitialization(Entity, Owned(Args[i])))
1527 return true;
1528
John McCall60d7b3a2010-08-24 06:29:42 +00001529 ExprResult Result
Sean Hunt2be7e902011-05-12 22:46:29 +00001530 = PerformCopyInitialization(Entity, SourceLocation(), Owned(Args[i]));
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001531 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001532 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001533
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001534 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001535 }
1536 Operator = FnDecl;
Sean Hunt2be7e902011-05-12 22:46:29 +00001537 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl,
1538 Diagnose);
Sebastian Redl7f662392008-12-04 22:20:51 +00001539 return false;
1540 }
1541
1542 case OR_No_Viable_Function:
Chandler Carruth361d3802011-06-08 10:26:03 +00001543 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001544 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1545 << Name << Range;
Chandler Carruth361d3802011-06-08 10:26:03 +00001546 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1547 }
Sebastian Redl7f662392008-12-04 22:20:51 +00001548 return true;
1549
1550 case OR_Ambiguous:
Chandler Carruth361d3802011-06-08 10:26:03 +00001551 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001552 Diag(StartLoc, diag::err_ovl_ambiguous_call)
1553 << Name << Range;
Chandler Carruth361d3802011-06-08 10:26:03 +00001554 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
1555 }
Sebastian Redl7f662392008-12-04 22:20:51 +00001556 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001557
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001558 case OR_Deleted: {
Chandler Carruth361d3802011-06-08 10:26:03 +00001559 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001560 Diag(StartLoc, diag::err_ovl_deleted_call)
1561 << Best->Function->isDeleted()
1562 << Name
1563 << getDeletedOrUnavailableSuffix(Best->Function)
1564 << Range;
Chandler Carruth361d3802011-06-08 10:26:03 +00001565 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1566 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001567 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001568 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001569 }
David Blaikieb219cfc2011-09-23 05:06:16 +00001570 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Sebastian Redl7f662392008-12-04 22:20:51 +00001571}
1572
1573
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001574/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1575/// delete. These are:
1576/// @code
Sebastian Redl8999fe12011-03-14 18:08:30 +00001577/// // C++03:
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001578/// void* operator new(std::size_t) throw(std::bad_alloc);
1579/// void* operator new[](std::size_t) throw(std::bad_alloc);
1580/// void operator delete(void *) throw();
1581/// void operator delete[](void *) throw();
Sebastian Redl8999fe12011-03-14 18:08:30 +00001582/// // C++0x:
1583/// void* operator new(std::size_t);
1584/// void* operator new[](std::size_t);
1585/// void operator delete(void *);
1586/// void operator delete[](void *);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001587/// @endcode
Sebastian Redl8999fe12011-03-14 18:08:30 +00001588/// C++0x operator delete is implicitly noexcept.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001589/// Note that the placement and nothrow forms of new are *not* implicitly
1590/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001591void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001592 if (GlobalNewDeleteDeclared)
1593 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001594
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001595 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001596 // [...] The following allocation and deallocation functions (18.4) are
1597 // implicitly declared in global scope in each translation unit of a
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001598 // program
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001599 //
Sebastian Redl8999fe12011-03-14 18:08:30 +00001600 // C++03:
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001601 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001602 // void* operator new[](std::size_t) throw(std::bad_alloc);
1603 // void operator delete(void*) throw();
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001604 // void operator delete[](void*) throw();
Sebastian Redl8999fe12011-03-14 18:08:30 +00001605 // C++0x:
1606 // void* operator new(std::size_t);
1607 // void* operator new[](std::size_t);
1608 // void operator delete(void*);
1609 // void operator delete[](void*);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001610 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001611 // These implicit declarations introduce only the function names operator
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001612 // new, operator new[], operator delete, operator delete[].
1613 //
1614 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1615 // "std" or "bad_alloc" as necessary to form the exception specification.
1616 // However, we do not make these implicit declarations visible to name
1617 // lookup.
Sebastian Redl8999fe12011-03-14 18:08:30 +00001618 // Note that the C++0x versions of operator delete are deallocation functions,
1619 // and thus are implicitly noexcept.
1620 if (!StdBadAlloc && !getLangOptions().CPlusPlus0x) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001621 // The "std::bad_alloc" class has not yet been declared, so build it
1622 // implicitly.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001623 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1624 getOrCreateStdNamespace(),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001625 SourceLocation(), SourceLocation(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001626 &PP.getIdentifierTable().get("bad_alloc"),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001627 0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001628 getStdBadAlloc()->setImplicit(true);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001629 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001630
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001631 GlobalNewDeleteDeclared = true;
1632
1633 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1634 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001635 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001636
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001637 DeclareGlobalAllocationFunction(
1638 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001639 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001640 DeclareGlobalAllocationFunction(
1641 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001642 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001643 DeclareGlobalAllocationFunction(
1644 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1645 Context.VoidTy, VoidPtr);
1646 DeclareGlobalAllocationFunction(
1647 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1648 Context.VoidTy, VoidPtr);
1649}
1650
1651/// DeclareGlobalAllocationFunction - Declares a single implicit global
1652/// allocation function if it doesn't already exist.
1653void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001654 QualType Return, QualType Argument,
1655 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001656 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1657
1658 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001659 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001660 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001661 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001662 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001663 // Only look at non-template functions, as it is the predefined,
1664 // non-templated allocation function we are trying to declare here.
1665 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1666 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001667 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001668 Func->getParamDecl(0)->getType().getUnqualifiedType());
1669 // FIXME: Do we need to check for default arguments here?
Douglas Gregor7b868622010-08-18 15:06:25 +00001670 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1671 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00001672 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001673 return;
Douglas Gregor7b868622010-08-18 15:06:25 +00001674 }
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001675 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001676 }
1677 }
1678
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001679 QualType BadAllocType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001680 bool HasBadAllocExceptionSpec
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001681 = (Name.getCXXOverloadedOperator() == OO_New ||
1682 Name.getCXXOverloadedOperator() == OO_Array_New);
Sebastian Redl8999fe12011-03-14 18:08:30 +00001683 if (HasBadAllocExceptionSpec && !getLangOptions().CPlusPlus0x) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001684 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001685 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001686 }
John McCalle23cf432010-12-14 08:05:40 +00001687
1688 FunctionProtoType::ExtProtoInfo EPI;
John McCalle23cf432010-12-14 08:05:40 +00001689 if (HasBadAllocExceptionSpec) {
Sebastian Redl8999fe12011-03-14 18:08:30 +00001690 if (!getLangOptions().CPlusPlus0x) {
1691 EPI.ExceptionSpecType = EST_Dynamic;
1692 EPI.NumExceptions = 1;
1693 EPI.Exceptions = &BadAllocType;
1694 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00001695 } else {
Sebastian Redl8999fe12011-03-14 18:08:30 +00001696 EPI.ExceptionSpecType = getLangOptions().CPlusPlus0x ?
1697 EST_BasicNoexcept : EST_DynamicNone;
John McCalle23cf432010-12-14 08:05:40 +00001698 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001699
John McCalle23cf432010-12-14 08:05:40 +00001700 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001701 FunctionDecl *Alloc =
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001702 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
1703 SourceLocation(), Name,
John McCalld931b082010-08-26 03:08:43 +00001704 FnType, /*TInfo=*/0, SC_None,
1705 SC_None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001706 Alloc->setImplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001707
Nuno Lopesfc284482009-12-16 16:59:22 +00001708 if (AddMallocAttr)
Sean Huntcf807c42010-08-18 23:23:40 +00001709 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001710
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001711 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001712 SourceLocation(), 0,
1713 Argument, /*TInfo=*/0,
1714 SC_None, SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00001715 Alloc->setParams(Param);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001716
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001717 // FIXME: Also add this declaration to the IdentifierResolver, but
1718 // make sure it is at the end of the chain to coincide with the
1719 // global scope.
John McCall5f1e0942010-08-24 08:50:51 +00001720 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001721}
1722
Anders Carlsson78f74552009-11-15 18:45:20 +00001723bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1724 DeclarationName Name,
Sean Hunt2be7e902011-05-12 22:46:29 +00001725 FunctionDecl* &Operator, bool Diagnose) {
John McCalla24dc2e2009-11-17 02:14:36 +00001726 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001727 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001728 LookupQualifiedName(Found, RD);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001729
John McCalla24dc2e2009-11-17 02:14:36 +00001730 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001731 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001732
Chandler Carruth23893242010-06-28 00:30:51 +00001733 Found.suppressDiagnostics();
1734
Chris Lattner5f9e2722011-07-23 10:55:15 +00001735 SmallVector<DeclAccessPair,4> Matches;
Anders Carlsson78f74552009-11-15 18:45:20 +00001736 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1737 F != FEnd; ++F) {
Chandler Carruth09556fd2010-08-08 07:04:00 +00001738 NamedDecl *ND = (*F)->getUnderlyingDecl();
1739
1740 // Ignore template operator delete members from the check for a usual
1741 // deallocation function.
1742 if (isa<FunctionTemplateDecl>(ND))
1743 continue;
1744
1745 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall046a7462010-08-04 00:31:26 +00001746 Matches.push_back(F.getPair());
1747 }
1748
1749 // There's exactly one suitable operator; pick it.
1750 if (Matches.size() == 1) {
1751 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
Sean Hunt2be7e902011-05-12 22:46:29 +00001752
1753 if (Operator->isDeleted()) {
1754 if (Diagnose) {
1755 Diag(StartLoc, diag::err_deleted_function_use);
1756 Diag(Operator->getLocation(), diag::note_unavailable_here) << true;
1757 }
1758 return true;
1759 }
1760
John McCall046a7462010-08-04 00:31:26 +00001761 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Sean Hunt2be7e902011-05-12 22:46:29 +00001762 Matches[0], Diagnose);
John McCall046a7462010-08-04 00:31:26 +00001763 return false;
1764
1765 // We found multiple suitable operators; complain about the ambiguity.
1766 } else if (!Matches.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001767 if (Diagnose) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00001768 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1769 << Name << RD;
John McCall046a7462010-08-04 00:31:26 +00001770
Chris Lattner5f9e2722011-07-23 10:55:15 +00001771 for (SmallVectorImpl<DeclAccessPair>::iterator
Sean Huntcb45a0f2011-05-12 22:46:25 +00001772 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1773 Diag((*F)->getUnderlyingDecl()->getLocation(),
1774 diag::note_member_declared_here) << Name;
1775 }
John McCall046a7462010-08-04 00:31:26 +00001776 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001777 }
1778
1779 // We did find operator delete/operator delete[] declarations, but
1780 // none of them were suitable.
1781 if (!Found.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001782 if (Diagnose) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00001783 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1784 << Name << RD;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001785
Sean Huntcb45a0f2011-05-12 22:46:25 +00001786 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1787 F != FEnd; ++F)
1788 Diag((*F)->getUnderlyingDecl()->getLocation(),
1789 diag::note_member_declared_here) << Name;
1790 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001791 return true;
1792 }
1793
1794 // Look for a global declaration.
1795 DeclareGlobalNewDelete();
1796 DeclContext *TUDecl = Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001797
Anders Carlsson78f74552009-11-15 18:45:20 +00001798 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1799 Expr* DeallocArgs[1];
1800 DeallocArgs[0] = &Null;
1801 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
Sean Hunt2be7e902011-05-12 22:46:29 +00001802 DeallocArgs, 1, TUDecl, !Diagnose,
1803 Operator, Diagnose))
Anders Carlsson78f74552009-11-15 18:45:20 +00001804 return true;
1805
1806 assert(Operator && "Did not find a deallocation function!");
1807 return false;
1808}
1809
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001810/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1811/// @code ::delete ptr; @endcode
1812/// or
1813/// @code delete [] ptr; @endcode
John McCall60d7b3a2010-08-24 06:29:42 +00001814ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001815Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley429bb272011-04-08 18:41:53 +00001816 bool ArrayForm, Expr *ExE) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001817 // C++ [expr.delete]p1:
1818 // The operand shall have a pointer type, or a class type having a single
1819 // conversion function to a pointer type. The result has type void.
1820 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001821 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1822
John Wiegley429bb272011-04-08 18:41:53 +00001823 ExprResult Ex = Owned(ExE);
Anders Carlssond67c4c32009-08-16 20:29:29 +00001824 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001825 bool ArrayFormAsWritten = ArrayForm;
John McCall6ec278d2011-01-27 09:37:56 +00001826 bool UsualArrayDeleteWantsSize = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001827
John Wiegley429bb272011-04-08 18:41:53 +00001828 if (!Ex.get()->isTypeDependent()) {
1829 QualType Type = Ex.get()->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001830
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001831 if (const RecordType *Record = Type->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001832 if (RequireCompleteType(StartLoc, Type,
Douglas Gregor254a9422010-07-29 14:44:35 +00001833 PDiag(diag::err_delete_incomplete_class_type)))
1834 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001835
Chris Lattner5f9e2722011-07-23 10:55:15 +00001836 SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
John McCall32daa422010-03-31 01:36:47 +00001837
Fariborz Jahanian53462782009-09-11 21:44:33 +00001838 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001839 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001840 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001841 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001842 NamedDecl *D = I.getDecl();
1843 if (isa<UsingShadowDecl>(D))
1844 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1845
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001846 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001847 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001848 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001849
John McCall32daa422010-03-31 01:36:47 +00001850 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001851
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001852 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1853 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedman13578692010-08-05 02:49:48 +00001854 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001855 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001856 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001857 if (ObjectPtrConversions.size() == 1) {
1858 // We have a single conversion to a pointer-to-object type. Perform
1859 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001860 // TODO: don't redo the conversion calculation.
John Wiegley429bb272011-04-08 18:41:53 +00001861 ExprResult Res =
1862 PerformImplicitConversion(Ex.get(),
John McCall32daa422010-03-31 01:36:47 +00001863 ObjectPtrConversions.front()->getConversionType(),
John Wiegley429bb272011-04-08 18:41:53 +00001864 AA_Converting);
1865 if (Res.isUsable()) {
1866 Ex = move(Res);
1867 Type = Ex.get()->getType();
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001868 }
1869 }
1870 else if (ObjectPtrConversions.size() > 1) {
1871 Diag(StartLoc, diag::err_ambiguous_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001872 << Type << Ex.get()->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001873 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1874 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001875 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001876 }
Sebastian Redl28507842009-02-26 14:39:58 +00001877 }
1878
Sebastian Redlf53597f2009-03-15 17:47:39 +00001879 if (!Type->isPointerType())
1880 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001881 << Type << Ex.get()->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001882
Ted Kremenek6217b802009-07-29 21:53:49 +00001883 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmane52c9142011-07-26 22:25:31 +00001884 QualType PointeeElem = Context.getBaseElementType(Pointee);
1885
1886 if (unsigned AddressSpace = Pointee.getAddressSpace())
1887 return Diag(Ex.get()->getLocStart(),
1888 diag::err_address_space_qualified_delete)
1889 << Pointee.getUnqualifiedType() << AddressSpace;
1890
1891 CXXRecordDecl *PointeeRD = 0;
Douglas Gregor94a61572010-05-24 17:01:56 +00001892 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001893 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregor94a61572010-05-24 17:01:56 +00001894 // effectively bans deletion of "void*". However, most compilers support
1895 // this, so we treat it as a warning unless we're in a SFINAE context.
1896 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001897 << Type << Ex.get()->getSourceRange();
Eli Friedmane52c9142011-07-26 22:25:31 +00001898 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00001899 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001900 << Type << Ex.get()->getSourceRange());
Eli Friedmane52c9142011-07-26 22:25:31 +00001901 } else if (!Pointee->isDependentType()) {
1902 if (!RequireCompleteType(StartLoc, Pointee,
1903 PDiag(diag::warn_delete_incomplete)
1904 << Ex.get()->getSourceRange())) {
1905 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
1906 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
1907 }
1908 }
1909
Abramo Bagnara30bb4202011-11-16 15:42:13 +00001910 // Perform lvalue-to-rvalue cast, if needed.
1911 Ex = DefaultLvalueConversion(Ex.take());
1912
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001913 // C++ [expr.delete]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001914 // [Note: a pointer to a const type can be the operand of a
1915 // delete-expression; it is not necessary to cast away the constness
1916 // (5.2.11) of the pointer expression before it is used as the operand
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001917 // of the delete-expression. ]
John McCallf85e1932011-06-15 23:02:42 +00001918 if (!Context.hasSameType(Ex.get()->getType(), Context.VoidPtrTy))
Abramo Bagnara30bb4202011-11-16 15:42:13 +00001919 Ex = Owned(ImplicitCastExpr::Create(Context, Context.VoidPtrTy,
1920 CK_BitCast, Ex.take(), 0, VK_RValue));
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001921
1922 if (Pointee->isArrayType() && !ArrayForm) {
1923 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley429bb272011-04-08 18:41:53 +00001924 << Type << Ex.get()->getSourceRange()
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001925 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1926 ArrayForm = true;
1927 }
1928
Anders Carlssond67c4c32009-08-16 20:29:29 +00001929 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1930 ArrayForm ? OO_Array_Delete : OO_Delete);
1931
Eli Friedmane52c9142011-07-26 22:25:31 +00001932 if (PointeeRD) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001933 if (!UseGlobal &&
Eli Friedmane52c9142011-07-26 22:25:31 +00001934 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
1935 OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001936 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001937
John McCall6ec278d2011-01-27 09:37:56 +00001938 // If we're allocating an array of records, check whether the
1939 // usual operator delete[] has a size_t parameter.
1940 if (ArrayForm) {
1941 // If the user specifically asked to use the global allocator,
1942 // we'll need to do the lookup into the class.
1943 if (UseGlobal)
1944 UsualArrayDeleteWantsSize =
1945 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
1946
1947 // Otherwise, the usual operator delete[] should be the
1948 // function we just found.
1949 else if (isa<CXXMethodDecl>(OperatorDelete))
1950 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
1951 }
1952
Eli Friedmane52c9142011-07-26 22:25:31 +00001953 if (!PointeeRD->hasTrivialDestructor())
1954 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001955 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001956 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor9b623632010-10-12 23:32:35 +00001957 DiagnoseUseOfDecl(Dtor, StartLoc);
1958 }
Argyrios Kyrtzidis6f0074a2011-05-24 19:53:26 +00001959
1960 // C++ [expr.delete]p3:
1961 // In the first alternative (delete object), if the static type of the
1962 // object to be deleted is different from its dynamic type, the static
1963 // type shall be a base class of the dynamic type of the object to be
1964 // deleted and the static type shall have a virtual destructor or the
1965 // behavior is undefined.
1966 //
1967 // Note: a final class cannot be derived from, no issue there
Eli Friedmanef8c79c2011-07-26 23:27:24 +00001968 if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) {
Eli Friedmane52c9142011-07-26 22:25:31 +00001969 CXXDestructorDecl *dtor = PointeeRD->getDestructor();
Eli Friedmanef8c79c2011-07-26 23:27:24 +00001970 if (dtor && !dtor->isVirtual()) {
1971 if (PointeeRD->isAbstract()) {
1972 // If the class is abstract, we warn by default, because we're
1973 // sure the code has undefined behavior.
1974 Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor)
1975 << PointeeElem;
1976 } else if (!ArrayForm) {
1977 // Otherwise, if this is not an array delete, it's a bit suspect,
1978 // but not necessarily wrong.
1979 Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
1980 }
1981 }
Argyrios Kyrtzidis6f0074a2011-05-24 19:53:26 +00001982 }
John McCallf85e1932011-06-15 23:02:42 +00001983
1984 } else if (getLangOptions().ObjCAutoRefCount &&
1985 PointeeElem->isObjCLifetimeType() &&
1986 (PointeeElem.getObjCLifetime() == Qualifiers::OCL_Strong ||
1987 PointeeElem.getObjCLifetime() == Qualifiers::OCL_Weak) &&
1988 ArrayForm) {
1989 Diag(StartLoc, diag::warn_err_new_delete_object_array)
1990 << 1 << PointeeElem;
Anders Carlssond67c4c32009-08-16 20:29:29 +00001991 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001992
Anders Carlssond67c4c32009-08-16 20:29:29 +00001993 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001994 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001995 DeclareGlobalNewDelete();
1996 DeclContext *TUDecl = Context.getTranslationUnitDecl();
John Wiegley429bb272011-04-08 18:41:53 +00001997 Expr *Arg = Ex.get();
Mike Stump1eb44332009-09-09 15:08:12 +00001998 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
John Wiegley429bb272011-04-08 18:41:53 +00001999 &Arg, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00002000 OperatorDelete))
2001 return ExprError();
2002 }
Mike Stump1eb44332009-09-09 15:08:12 +00002003
John McCall9c82afc2010-04-20 02:18:25 +00002004 MarkDeclarationReferenced(StartLoc, OperatorDelete);
John McCall6ec278d2011-01-27 09:37:56 +00002005
Douglas Gregord880f522011-02-01 15:50:11 +00002006 // Check access and ambiguity of operator delete and destructor.
Eli Friedmane52c9142011-07-26 22:25:31 +00002007 if (PointeeRD) {
2008 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
John Wiegley429bb272011-04-08 18:41:53 +00002009 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregord880f522011-02-01 15:50:11 +00002010 PDiag(diag::err_access_dtor) << PointeeElem);
2011 }
2012 }
2013
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002014 }
2015
Sebastian Redlf53597f2009-03-15 17:47:39 +00002016 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
John McCall6ec278d2011-01-27 09:37:56 +00002017 ArrayFormAsWritten,
2018 UsualArrayDeleteWantsSize,
John Wiegley429bb272011-04-08 18:41:53 +00002019 OperatorDelete, Ex.take(), StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002020}
2021
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002022/// \brief Check the use of the given variable as a C++ condition in an if,
2023/// while, do-while, or switch statement.
John McCall60d7b3a2010-08-24 06:29:42 +00002024ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCallf89e55a2010-11-18 06:31:45 +00002025 SourceLocation StmtLoc,
2026 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002027 QualType T = ConditionVar->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002028
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002029 // C++ [stmt.select]p2:
2030 // The declarator shall not specify a function or an array.
2031 if (T->isFunctionType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002032 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002033 diag::err_invalid_use_of_function_type)
2034 << ConditionVar->getSourceRange());
2035 else if (T->isArrayType())
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_array_type)
2038 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00002039
John Wiegley429bb272011-04-08 18:41:53 +00002040 ExprResult Condition =
2041 Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
Douglas Gregor40d96a62011-02-28 21:54:11 +00002042 ConditionVar,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002043 ConditionVar->getLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00002044 ConditionVar->getType().getNonReferenceType(),
John Wiegley429bb272011-04-08 18:41:53 +00002045 VK_LValue));
2046 if (ConvertToBoolean) {
2047 Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
2048 if (Condition.isInvalid())
2049 return ExprError();
2050 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002051
John Wiegley429bb272011-04-08 18:41:53 +00002052 return move(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002053}
2054
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002055/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
John Wiegley429bb272011-04-08 18:41:53 +00002056ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002057 // C++ 6.4p4:
2058 // The value of a condition that is an initialized declaration in a statement
2059 // other than a switch statement is the value of the declared variable
2060 // implicitly converted to type bool. If that conversion is ill-formed, the
2061 // program is ill-formed.
2062 // The value of a condition that is an expression is the value of the
2063 // expression, implicitly converted to bool.
2064 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002065 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002066}
Douglas Gregor77a52232008-09-12 00:47:35 +00002067
2068/// Helper function to determine whether this is the (deprecated) C++
2069/// conversion from a string literal to a pointer to non-const char or
2070/// non-const wchar_t (for narrow and wide string literals,
2071/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00002072bool
Douglas Gregor77a52232008-09-12 00:47:35 +00002073Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
2074 // Look inside the implicit cast, if it exists.
2075 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
2076 From = Cast->getSubExpr();
2077
2078 // A string literal (2.13.4) that is not a wide string literal can
2079 // be converted to an rvalue of type "pointer to char"; a wide
2080 // string literal can be converted to an rvalue of type "pointer
2081 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00002082 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00002083 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00002084 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00002085 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00002086 // This conversion is considered only when there is an
2087 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregor5cee1192011-07-27 05:40:30 +00002088 if (!ToPtrType->getPointeeType().hasQualifiers()) {
2089 switch (StrLit->getKind()) {
2090 case StringLiteral::UTF8:
2091 case StringLiteral::UTF16:
2092 case StringLiteral::UTF32:
2093 // We don't allow UTF literals to be implicitly converted
2094 break;
2095 case StringLiteral::Ascii:
2096 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
2097 ToPointeeType->getKind() == BuiltinType::Char_S);
2098 case StringLiteral::Wide:
2099 return ToPointeeType->isWideCharType();
2100 }
2101 }
Douglas Gregor77a52232008-09-12 00:47:35 +00002102 }
2103
2104 return false;
2105}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002106
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002107static ExprResult BuildCXXCastArgument(Sema &S,
John McCall2de56d12010-08-25 11:45:40 +00002108 SourceLocation CastLoc,
2109 QualType Ty,
2110 CastKind Kind,
2111 CXXMethodDecl *Method,
John McCallca82a822011-09-21 08:36:56 +00002112 DeclAccessPair FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002113 bool HadMultipleCandidates,
John McCall2de56d12010-08-25 11:45:40 +00002114 Expr *From) {
Douglas Gregorba70ab62010-04-16 22:17:36 +00002115 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002116 default: llvm_unreachable("Unhandled cast kind!");
John McCall2de56d12010-08-25 11:45:40 +00002117 case CK_ConstructorConversion: {
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002118 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
John McCallca0408f2010-08-23 06:44:23 +00002119 ASTOwningVector<Expr*> ConstructorArgs(S);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002120
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002121 if (S.CompleteConstructorCall(Constructor,
John McCallf312b1e2010-08-26 23:41:50 +00002122 MultiExprArg(&From, 1),
Douglas Gregorba70ab62010-04-16 22:17:36 +00002123 CastLoc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00002124 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002125
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002126 S.CheckConstructorAccess(CastLoc, Constructor, Constructor->getAccess(),
2127 S.PDiag(diag::err_access_ctor));
2128
2129 ExprResult Result
2130 = S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2131 move_arg(ConstructorArgs),
2132 HadMultipleCandidates, /*ZeroInit*/ false,
2133 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregorba70ab62010-04-16 22:17:36 +00002134 if (Result.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00002135 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002136
Douglas Gregorba70ab62010-04-16 22:17:36 +00002137 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
2138 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002139
John McCall2de56d12010-08-25 11:45:40 +00002140 case CK_UserDefinedConversion: {
Douglas Gregorba70ab62010-04-16 22:17:36 +00002141 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002142
Douglas Gregorba70ab62010-04-16 22:17:36 +00002143 // Create an implicit call expr that calls it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002144 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method,
2145 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00002146 if (Result.isInvalid())
2147 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00002148 // Record usage of conversion in an implicit cast.
2149 Result = S.Owned(ImplicitCastExpr::Create(S.Context,
2150 Result.get()->getType(),
2151 CK_UserDefinedConversion,
2152 Result.get(), 0,
2153 Result.get()->getValueKind()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002154
John McCallca82a822011-09-21 08:36:56 +00002155 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ 0, FoundDecl);
2156
Douglas Gregorf2ae5262011-01-20 00:18:04 +00002157 return S.MaybeBindToTemporary(Result.get());
Douglas Gregorba70ab62010-04-16 22:17:36 +00002158 }
2159 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002160}
Douglas Gregorba70ab62010-04-16 22:17:36 +00002161
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002162/// PerformImplicitConversion - Perform an implicit conversion of the
2163/// expression From to the type ToType using the pre-computed implicit
John Wiegley429bb272011-04-08 18:41:53 +00002164/// conversion sequence ICS. Returns the converted
Douglas Gregor68647482009-12-16 03:45:30 +00002165/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002166/// used in the error message.
John Wiegley429bb272011-04-08 18:41:53 +00002167ExprResult
2168Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002169 const ImplicitConversionSequence &ICS,
John McCallf85e1932011-06-15 23:02:42 +00002170 AssignmentAction Action,
2171 CheckedConversionKind CCK) {
John McCall1d318332010-01-12 00:44:57 +00002172 switch (ICS.getKind()) {
John Wiegley429bb272011-04-08 18:41:53 +00002173 case ImplicitConversionSequence::StandardConversion: {
Richard Smithc8d7f582011-11-29 22:48:16 +00002174 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
2175 Action, CCK);
John Wiegley429bb272011-04-08 18:41:53 +00002176 if (Res.isInvalid())
2177 return ExprError();
2178 From = Res.take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002179 break;
John Wiegley429bb272011-04-08 18:41:53 +00002180 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002181
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002182 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002183
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00002184 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCalldaa8e4e2010-11-15 09:13:47 +00002185 CastKind CastKind;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002186 QualType BeforeToType;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00002187 assert(FD && "FIXME: aggregate initialization from init list");
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002188 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCall2de56d12010-08-25 11:45:40 +00002189 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002190
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002191 // If the user-defined conversion is specified by a conversion function,
2192 // the initial standard conversion sequence converts the source type to
2193 // the implicit object parameter of the conversion function.
2194 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCall9ec94452010-12-04 09:57:16 +00002195 } else {
2196 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCall2de56d12010-08-25 11:45:40 +00002197 CastKind = CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002198 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00002199 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002200 // If the user-defined conversion is specified by a constructor, the
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002201 // initial standard conversion sequence converts the source type to the
2202 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00002203 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
2204 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002205 }
Douglas Gregora3998bd2010-12-02 21:47:04 +00002206 // Watch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00002207 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley429bb272011-04-08 18:41:53 +00002208 ExprResult Res =
Richard Smithc8d7f582011-11-29 22:48:16 +00002209 PerformImplicitConversion(From, BeforeToType,
2210 ICS.UserDefined.Before, AA_Converting,
2211 CCK);
John Wiegley429bb272011-04-08 18:41:53 +00002212 if (Res.isInvalid())
2213 return ExprError();
2214 From = Res.take();
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002215 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002216
2217 ExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00002218 = BuildCXXCastArgument(*this,
2219 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00002220 ToType.getNonReferenceType(),
Douglas Gregor83eecbe2011-01-20 01:32:05 +00002221 CastKind, cast<CXXMethodDecl>(FD),
2222 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002223 ICS.UserDefined.HadMultipleCandidates,
John McCall9ae2f072010-08-23 23:25:46 +00002224 From);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002225
2226 if (CastArg.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00002227 return ExprError();
Eli Friedmand8889622009-11-27 04:41:50 +00002228
John Wiegley429bb272011-04-08 18:41:53 +00002229 From = CastArg.take();
Eli Friedmand8889622009-11-27 04:41:50 +00002230
Richard Smithc8d7f582011-11-29 22:48:16 +00002231 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
2232 AA_Converting, CCK);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00002233 }
John McCall1d318332010-01-12 00:44:57 +00002234
2235 case ImplicitConversionSequence::AmbiguousConversion:
John McCall120d63c2010-08-24 20:38:10 +00002236 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall1d318332010-01-12 00:44:57 +00002237 PDiag(diag::err_typecheck_ambiguous_condition)
2238 << From->getSourceRange());
John Wiegley429bb272011-04-08 18:41:53 +00002239 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002240
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002241 case ImplicitConversionSequence::EllipsisConversion:
David Blaikieb219cfc2011-09-23 05:06:16 +00002242 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002243
2244 case ImplicitConversionSequence::BadConversion:
John Wiegley429bb272011-04-08 18:41:53 +00002245 return ExprError();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002246 }
2247
2248 // Everything went well.
John Wiegley429bb272011-04-08 18:41:53 +00002249 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002250}
2251
Richard Smithc8d7f582011-11-29 22:48:16 +00002252/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002253/// expression From to the type ToType by following the standard
John Wiegley429bb272011-04-08 18:41:53 +00002254/// conversion sequence SCS. Returns the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00002255/// expression. Flavor is the context in which we're performing this
2256/// conversion, for use in error messages.
John Wiegley429bb272011-04-08 18:41:53 +00002257ExprResult
Richard Smithc8d7f582011-11-29 22:48:16 +00002258Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00002259 const StandardConversionSequence& SCS,
John McCallf85e1932011-06-15 23:02:42 +00002260 AssignmentAction Action,
2261 CheckedConversionKind CCK) {
2262 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
2263
Mike Stump390b4cc2009-05-16 07:39:55 +00002264 // Overall FIXME: we are recomputing too many types here and doing far too
2265 // much extra work. What this means is that we need to keep track of more
2266 // information that is computed when we try the implicit conversion initially,
2267 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002268 QualType FromType = From->getType();
John McCallf85e1932011-06-15 23:02:42 +00002269
Douglas Gregor225c41e2008-11-03 19:09:14 +00002270 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00002271 // FIXME: When can ToType be a reference type?
2272 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002273 if (SCS.Second == ICK_Derived_To_Base) {
John McCallca0408f2010-08-23 06:44:23 +00002274 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002275 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCallca0408f2010-08-23 06:44:23 +00002276 MultiExprArg(*this, &From, 1),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002277 /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002278 ConstructorArgs))
John Wiegley429bb272011-04-08 18:41:53 +00002279 return ExprError();
2280 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2281 ToType, SCS.CopyConstructor,
2282 move_arg(ConstructorArgs),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002283 /*HadMultipleCandidates*/ false,
John Wiegley429bb272011-04-08 18:41:53 +00002284 /*ZeroInit*/ false,
2285 CXXConstructExpr::CK_Complete,
2286 SourceRange());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002287 }
John Wiegley429bb272011-04-08 18:41:53 +00002288 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2289 ToType, SCS.CopyConstructor,
2290 MultiExprArg(*this, &From, 1),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002291 /*HadMultipleCandidates*/ false,
John Wiegley429bb272011-04-08 18:41:53 +00002292 /*ZeroInit*/ false,
2293 CXXConstructExpr::CK_Complete,
2294 SourceRange());
Douglas Gregor225c41e2008-11-03 19:09:14 +00002295 }
2296
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002297 // Resolve overloaded function references.
2298 if (Context.hasSameType(FromType, Context.OverloadTy)) {
2299 DeclAccessPair Found;
2300 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2301 true, Found);
2302 if (!Fn)
John Wiegley429bb272011-04-08 18:41:53 +00002303 return ExprError();
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002304
2305 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
John Wiegley429bb272011-04-08 18:41:53 +00002306 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002307
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002308 From = FixOverloadedFunctionReference(From, Found, Fn);
2309 FromType = From->getType();
2310 }
2311
Richard Smithc8d7f582011-11-29 22:48:16 +00002312 // Perform the first implicit conversion.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002313 switch (SCS.First) {
2314 case ICK_Identity:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002315 // Nothing to do.
2316 break;
2317
John McCallf6a16482010-12-04 03:47:34 +00002318 case ICK_Lvalue_To_Rvalue:
John McCall3c3b7f92011-10-25 17:37:35 +00002319 assert(From->getObjectKind() != OK_ObjCProperty);
John McCallf6a16482010-12-04 03:47:34 +00002320 FromType = FromType.getUnqualifiedType();
2321 From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
2322 From, 0, VK_RValue);
2323 break;
2324
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002325 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002326 FromType = Context.getArrayDecayedType(FromType);
Richard Smithc8d7f582011-11-29 22:48:16 +00002327 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
2328 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002329 break;
2330
2331 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002332 FromType = Context.getPointerType(FromType);
Richard Smithc8d7f582011-11-29 22:48:16 +00002333 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
2334 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002335 break;
2336
2337 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002338 llvm_unreachable("Improper first standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002339 }
2340
Richard Smithc8d7f582011-11-29 22:48:16 +00002341 // Perform the second implicit conversion
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002342 switch (SCS.Second) {
2343 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002344 // If both sides are functions (or pointers/references to them), there could
2345 // be incompatible exception declarations.
2346 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002347 return ExprError();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002348 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002349 break;
2350
Douglas Gregor43c79c22009-12-09 00:47:37 +00002351 case ICK_NoReturn_Adjustment:
2352 // If both sides are functions (or pointers/references to them), there could
2353 // be incompatible exception declarations.
2354 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002355 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002356
Richard Smithc8d7f582011-11-29 22:48:16 +00002357 From = ImpCastExprToType(From, ToType, CK_NoOp,
2358 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor43c79c22009-12-09 00:47:37 +00002359 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002360
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002361 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002362 case ICK_Integral_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002363 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
2364 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002365 break;
2366
2367 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002368 case ICK_Floating_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002369 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
2370 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002371 break;
2372
2373 case ICK_Complex_Promotion:
John McCalldaa8e4e2010-11-15 09:13:47 +00002374 case ICK_Complex_Conversion: {
2375 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2376 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2377 CastKind CK;
2378 if (FromEl->isRealFloatingType()) {
2379 if (ToEl->isRealFloatingType())
2380 CK = CK_FloatingComplexCast;
2381 else
2382 CK = CK_FloatingComplexToIntegralComplex;
2383 } else if (ToEl->isRealFloatingType()) {
2384 CK = CK_IntegralComplexToFloatingComplex;
2385 } else {
2386 CK = CK_IntegralComplexCast;
2387 }
Richard Smithc8d7f582011-11-29 22:48:16 +00002388 From = ImpCastExprToType(From, ToType, CK,
2389 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002390 break;
John McCalldaa8e4e2010-11-15 09:13:47 +00002391 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00002392
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002393 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00002394 if (ToType->isRealFloatingType())
Richard Smithc8d7f582011-11-29 22:48:16 +00002395 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
2396 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002397 else
Richard Smithc8d7f582011-11-29 22:48:16 +00002398 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
2399 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002400 break;
2401
Douglas Gregorf9201e02009-02-11 23:02:49 +00002402 case ICK_Compatible_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002403 From = ImpCastExprToType(From, ToType, CK_NoOp,
2404 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002405 break;
2406
John McCallf85e1932011-06-15 23:02:42 +00002407 case ICK_Writeback_Conversion:
Anders Carlsson61faec12009-09-12 04:46:44 +00002408 case ICK_Pointer_Conversion: {
Douglas Gregora3998bd2010-12-02 21:47:04 +00002409 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor45920e82008-12-19 17:40:08 +00002410 // Diagnose incompatible Objective-C conversions
Douglas Gregor8cf0d222011-06-11 04:42:12 +00002411 if (Action == AA_Initializing || Action == AA_Assigning)
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002412 Diag(From->getSourceRange().getBegin(),
2413 diag::ext_typecheck_convert_incompatible_pointer)
2414 << ToType << From->getType() << Action
Anna Zaks67221552011-07-28 19:51:27 +00002415 << From->getSourceRange() << 0;
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002416 else
2417 Diag(From->getSourceRange().getBegin(),
2418 diag::ext_typecheck_convert_incompatible_pointer)
2419 << From->getType() << ToType << Action
Anna Zaks67221552011-07-28 19:51:27 +00002420 << From->getSourceRange() << 0;
John McCallf85e1932011-06-15 23:02:42 +00002421
Douglas Gregor926df6c2011-06-11 01:09:30 +00002422 if (From->getType()->isObjCObjectPointerType() &&
2423 ToType->isObjCObjectPointerType())
2424 EmitRelatedResultTypeNote(From);
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002425 }
2426 else if (getLangOptions().ObjCAutoRefCount &&
2427 !CheckObjCARCUnavailableWeakConversion(ToType,
2428 From->getType())) {
John McCall7f3a6d32011-09-09 06:12:06 +00002429 if (Action == AA_Initializing)
2430 Diag(From->getSourceRange().getBegin(),
2431 diag::err_arc_weak_unavailable_assign);
2432 else
2433 Diag(From->getSourceRange().getBegin(),
2434 diag::err_arc_convesion_of_weak_unavailable)
2435 << (Action == AA_Casting) << From->getType() << ToType
2436 << From->getSourceRange();
2437 }
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002438
John McCalldaa8e4e2010-11-15 09:13:47 +00002439 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002440 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002441 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002442 return ExprError();
John McCalldc05b112011-09-10 01:16:55 +00002443
2444 // Make sure we extend blocks if necessary.
2445 // FIXME: doing this here is really ugly.
2446 if (Kind == CK_BlockPointerToObjCPointerCast) {
2447 ExprResult E = From;
2448 (void) PrepareCastToObjCObjectPointer(E);
2449 From = E.take();
2450 }
2451
Richard Smithc8d7f582011-11-29 22:48:16 +00002452 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2453 .take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002454 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00002455 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002456
Anders Carlsson61faec12009-09-12 04:46:44 +00002457 case ICK_Pointer_Member: {
John McCalldaa8e4e2010-11-15 09:13:47 +00002458 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002459 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002460 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002461 return ExprError();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002462 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002463 return ExprError();
Richard Smithc8d7f582011-11-29 22:48:16 +00002464 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2465 .take();
Anders Carlsson61faec12009-09-12 04:46:44 +00002466 break;
2467 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002468
Abramo Bagnara737d5442011-04-07 09:26:19 +00002469 case ICK_Boolean_Conversion:
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00002470 // Perform half-to-boolean conversion via float.
2471 if (From->getType()->isHalfType()) {
2472 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).take();
2473 FromType = Context.FloatTy;
2474 }
2475
Richard Smithc8d7f582011-11-29 22:48:16 +00002476 From = ImpCastExprToType(From, Context.BoolTy,
2477 ScalarTypeToBooleanCastKind(FromType),
2478 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002479 break;
2480
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002481 case ICK_Derived_To_Base: {
John McCallf871d0c2010-08-07 06:22:56 +00002482 CXXCastPath BasePath;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002483 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002484 ToType.getNonReferenceType(),
2485 From->getLocStart(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002486 From->getSourceRange(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002487 &BasePath,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002488 CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002489 return ExprError();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002490
Richard Smithc8d7f582011-11-29 22:48:16 +00002491 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
2492 CK_DerivedToBase, From->getValueKind(),
2493 &BasePath, CCK).take();
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002494 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002495 }
2496
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002497 case ICK_Vector_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002498 From = ImpCastExprToType(From, ToType, CK_BitCast,
2499 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002500 break;
2501
2502 case ICK_Vector_Splat:
Richard Smithc8d7f582011-11-29 22:48:16 +00002503 From = ImpCastExprToType(From, ToType, CK_VectorSplat,
2504 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002505 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002506
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002507 case ICK_Complex_Real:
John McCalldaa8e4e2010-11-15 09:13:47 +00002508 // Case 1. x -> _Complex y
2509 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2510 QualType ElType = ToComplex->getElementType();
2511 bool isFloatingComplex = ElType->isRealFloatingType();
2512
2513 // x -> y
2514 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2515 // do nothing
2516 } else if (From->getType()->isRealFloatingType()) {
Richard Smithc8d7f582011-11-29 22:48:16 +00002517 From = ImpCastExprToType(From, ElType,
2518 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002519 } else {
2520 assert(From->getType()->isIntegerType());
Richard Smithc8d7f582011-11-29 22:48:16 +00002521 From = ImpCastExprToType(From, ElType,
2522 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002523 }
2524 // y -> _Complex y
Richard Smithc8d7f582011-11-29 22:48:16 +00002525 From = ImpCastExprToType(From, ToType,
2526 isFloatingComplex ? CK_FloatingRealToComplex
2527 : CK_IntegralRealToComplex).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002528
2529 // Case 2. _Complex x -> y
2530 } else {
2531 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2532 assert(FromComplex);
2533
2534 QualType ElType = FromComplex->getElementType();
2535 bool isFloatingComplex = ElType->isRealFloatingType();
2536
2537 // _Complex x -> x
Richard Smithc8d7f582011-11-29 22:48:16 +00002538 From = ImpCastExprToType(From, ElType,
2539 isFloatingComplex ? CK_FloatingComplexToReal
2540 : CK_IntegralComplexToReal,
2541 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002542
2543 // x -> y
2544 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2545 // do nothing
2546 } else if (ToType->isRealFloatingType()) {
Richard Smithc8d7f582011-11-29 22:48:16 +00002547 From = ImpCastExprToType(From, ToType,
2548 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
2549 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002550 } else {
2551 assert(ToType->isIntegerType());
Richard Smithc8d7f582011-11-29 22:48:16 +00002552 From = ImpCastExprToType(From, ToType,
2553 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
2554 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002555 }
2556 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002557 break;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002558
2559 case ICK_Block_Pointer_Conversion: {
Richard Smithc8d7f582011-11-29 22:48:16 +00002560 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
2561 VK_RValue, /*BasePath=*/0, CCK).take();
John McCallf85e1932011-06-15 23:02:42 +00002562 break;
2563 }
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002564
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002565 case ICK_TransparentUnionConversion: {
John Wiegley429bb272011-04-08 18:41:53 +00002566 ExprResult FromRes = Owned(From);
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002567 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00002568 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
2569 if (FromRes.isInvalid())
2570 return ExprError();
2571 From = FromRes.take();
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002572 assert ((ConvTy == Sema::Compatible) &&
2573 "Improper transparent union conversion");
2574 (void)ConvTy;
2575 break;
2576 }
2577
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002578 case ICK_Lvalue_To_Rvalue:
2579 case ICK_Array_To_Pointer:
2580 case ICK_Function_To_Pointer:
2581 case ICK_Qualification:
2582 case ICK_Num_Conversion_Kinds:
David Blaikieb219cfc2011-09-23 05:06:16 +00002583 llvm_unreachable("Improper second standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002584 }
2585
2586 switch (SCS.Third) {
2587 case ICK_Identity:
2588 // Nothing to do.
2589 break;
2590
Sebastian Redl906082e2010-07-20 04:20:21 +00002591 case ICK_Qualification: {
2592 // The qualification keeps the category of the inner expression, unless the
2593 // target type isn't a reference.
John McCall5baba9d2010-08-25 10:28:54 +00002594 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00002595 From->getValueKind() : VK_RValue;
Richard Smithc8d7f582011-11-29 22:48:16 +00002596 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
2597 CK_NoOp, VK, /*BasePath=*/0, CCK).take();
Douglas Gregora9bff302010-02-28 18:30:25 +00002598
Douglas Gregor069a6da2011-03-14 16:13:32 +00002599 if (SCS.DeprecatedStringLiteralToCharPtr &&
2600 !getLangOptions().WritableStrings)
Douglas Gregora9bff302010-02-28 18:30:25 +00002601 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2602 << ToType.getNonReferenceType();
2603
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002604 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002605 }
2606
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002607 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002608 llvm_unreachable("Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002609 }
2610
John Wiegley429bb272011-04-08 18:41:53 +00002611 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002612}
2613
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002614ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002615 SourceLocation KWLoc,
2616 ParsedType Ty,
2617 SourceLocation RParen) {
2618 TypeSourceInfo *TSInfo;
2619 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002620
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002621 if (!TSInfo)
2622 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002623 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002624}
2625
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002626/// \brief Check the completeness of a type in a unary type trait.
2627///
2628/// If the particular type trait requires a complete type, tries to complete
2629/// it. If completing the type fails, a diagnostic is emitted and false
2630/// returned. If completing the type succeeds or no completion was required,
2631/// returns true.
2632static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S,
2633 UnaryTypeTrait UTT,
2634 SourceLocation Loc,
2635 QualType ArgTy) {
2636 // C++0x [meta.unary.prop]p3:
2637 // For all of the class templates X declared in this Clause, instantiating
2638 // that template with a template argument that is a class template
2639 // specialization may result in the implicit instantiation of the template
2640 // argument if and only if the semantics of X require that the argument
2641 // must be a complete type.
2642 // We apply this rule to all the type trait expressions used to implement
2643 // these class templates. We also try to follow any GCC documented behavior
2644 // in these expressions to ensure portability of standard libraries.
2645 switch (UTT) {
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002646 // is_complete_type somewhat obviously cannot require a complete type.
2647 case UTT_IsCompleteType:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002648 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002649
2650 // These traits are modeled on the type predicates in C++0x
2651 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
2652 // requiring a complete type, as whether or not they return true cannot be
2653 // impacted by the completeness of the type.
2654 case UTT_IsVoid:
2655 case UTT_IsIntegral:
2656 case UTT_IsFloatingPoint:
2657 case UTT_IsArray:
2658 case UTT_IsPointer:
2659 case UTT_IsLvalueReference:
2660 case UTT_IsRvalueReference:
2661 case UTT_IsMemberFunctionPointer:
2662 case UTT_IsMemberObjectPointer:
2663 case UTT_IsEnum:
2664 case UTT_IsUnion:
2665 case UTT_IsClass:
2666 case UTT_IsFunction:
2667 case UTT_IsReference:
2668 case UTT_IsArithmetic:
2669 case UTT_IsFundamental:
2670 case UTT_IsObject:
2671 case UTT_IsScalar:
2672 case UTT_IsCompound:
2673 case UTT_IsMemberPointer:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002674 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002675
2676 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
2677 // which requires some of its traits to have the complete type. However,
2678 // the completeness of the type cannot impact these traits' semantics, and
2679 // so they don't require it. This matches the comments on these traits in
2680 // Table 49.
2681 case UTT_IsConst:
2682 case UTT_IsVolatile:
2683 case UTT_IsSigned:
2684 case UTT_IsUnsigned:
2685 return true;
2686
2687 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002688 // applied to a complete type.
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002689 case UTT_IsTrivial:
Sean Huntfeb375d2011-05-13 00:31:07 +00002690 case UTT_IsTriviallyCopyable:
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002691 case UTT_IsStandardLayout:
2692 case UTT_IsPOD:
2693 case UTT_IsLiteral:
2694 case UTT_IsEmpty:
2695 case UTT_IsPolymorphic:
2696 case UTT_IsAbstract:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002697 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002698
Douglas Gregor5e9392b2011-12-03 18:14:24 +00002699 // These traits require a complete type.
2700 case UTT_IsFinal:
2701
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002702 // These trait expressions are designed to help implement predicates in
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002703 // [meta.unary.prop] despite not being named the same. They are specified
2704 // by both GCC and the Embarcadero C++ compiler, and require the complete
2705 // type due to the overarching C++0x type predicates being implemented
2706 // requiring the complete type.
2707 case UTT_HasNothrowAssign:
2708 case UTT_HasNothrowConstructor:
2709 case UTT_HasNothrowCopy:
2710 case UTT_HasTrivialAssign:
Sean Hunt023df372011-05-09 18:22:59 +00002711 case UTT_HasTrivialDefaultConstructor:
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002712 case UTT_HasTrivialCopy:
2713 case UTT_HasTrivialDestructor:
2714 case UTT_HasVirtualDestructor:
2715 // Arrays of unknown bound are expressly allowed.
2716 QualType ElTy = ArgTy;
2717 if (ArgTy->isIncompleteArrayType())
2718 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
2719
2720 // The void type is expressly allowed.
2721 if (ElTy->isVoidType())
2722 return true;
2723
2724 return !S.RequireCompleteType(
2725 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleycf566412011-04-28 02:06:46 +00002726 }
Chandler Carruth73e0a912011-05-01 07:23:17 +00002727 llvm_unreachable("Type trait not handled by switch");
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002728}
2729
2730static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT,
2731 SourceLocation KeyLoc, QualType T) {
Chandler Carruthd064c702011-05-01 08:41:10 +00002732 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleycf566412011-04-28 02:06:46 +00002733
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002734 ASTContext &C = Self.Context;
2735 switch(UTT) {
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002736 // Type trait expressions corresponding to the primary type category
2737 // predicates in C++0x [meta.unary.cat].
2738 case UTT_IsVoid:
2739 return T->isVoidType();
2740 case UTT_IsIntegral:
2741 return T->isIntegralType(C);
2742 case UTT_IsFloatingPoint:
2743 return T->isFloatingType();
2744 case UTT_IsArray:
2745 return T->isArrayType();
2746 case UTT_IsPointer:
2747 return T->isPointerType();
2748 case UTT_IsLvalueReference:
2749 return T->isLValueReferenceType();
2750 case UTT_IsRvalueReference:
2751 return T->isRValueReferenceType();
2752 case UTT_IsMemberFunctionPointer:
2753 return T->isMemberFunctionPointerType();
2754 case UTT_IsMemberObjectPointer:
2755 return T->isMemberDataPointerType();
2756 case UTT_IsEnum:
2757 return T->isEnumeralType();
Chandler Carruth28eeb382011-05-01 06:11:03 +00002758 case UTT_IsUnion:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002759 return T->isUnionType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002760 case UTT_IsClass:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002761 return T->isClassType() || T->isStructureType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002762 case UTT_IsFunction:
2763 return T->isFunctionType();
2764
2765 // Type trait expressions which correspond to the convenient composition
2766 // predicates in C++0x [meta.unary.comp].
2767 case UTT_IsReference:
2768 return T->isReferenceType();
2769 case UTT_IsArithmetic:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002770 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002771 case UTT_IsFundamental:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002772 return T->isFundamentalType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002773 case UTT_IsObject:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002774 return T->isObjectType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002775 case UTT_IsScalar:
John McCallf85e1932011-06-15 23:02:42 +00002776 // Note: semantic analysis depends on Objective-C lifetime types to be
2777 // considered scalar types. However, such types do not actually behave
2778 // like scalar types at run time (since they may require retain/release
2779 // operations), so we report them as non-scalar.
2780 if (T->isObjCLifetimeType()) {
2781 switch (T.getObjCLifetime()) {
2782 case Qualifiers::OCL_None:
2783 case Qualifiers::OCL_ExplicitNone:
2784 return true;
2785
2786 case Qualifiers::OCL_Strong:
2787 case Qualifiers::OCL_Weak:
2788 case Qualifiers::OCL_Autoreleasing:
2789 return false;
2790 }
2791 }
2792
Chandler Carruthcec0ced2011-05-01 09:29:55 +00002793 return T->isScalarType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002794 case UTT_IsCompound:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002795 return T->isCompoundType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002796 case UTT_IsMemberPointer:
2797 return T->isMemberPointerType();
2798
2799 // Type trait expressions which correspond to the type property predicates
2800 // in C++0x [meta.unary.prop].
2801 case UTT_IsConst:
2802 return T.isConstQualified();
2803 case UTT_IsVolatile:
2804 return T.isVolatileQualified();
2805 case UTT_IsTrivial:
John McCallf85e1932011-06-15 23:02:42 +00002806 return T.isTrivialType(Self.Context);
Sean Huntfeb375d2011-05-13 00:31:07 +00002807 case UTT_IsTriviallyCopyable:
John McCallf85e1932011-06-15 23:02:42 +00002808 return T.isTriviallyCopyableType(Self.Context);
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002809 case UTT_IsStandardLayout:
2810 return T->isStandardLayoutType();
2811 case UTT_IsPOD:
John McCallf85e1932011-06-15 23:02:42 +00002812 return T.isPODType(Self.Context);
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002813 case UTT_IsLiteral:
2814 return T->isLiteralType();
2815 case UTT_IsEmpty:
2816 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2817 return !RD->isUnion() && RD->isEmpty();
2818 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002819 case UTT_IsPolymorphic:
Chandler Carruth28eeb382011-05-01 06:11:03 +00002820 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2821 return RD->isPolymorphic();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002822 return false;
2823 case UTT_IsAbstract:
Chandler Carruth28eeb382011-05-01 06:11:03 +00002824 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2825 return RD->isAbstract();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002826 return false;
Douglas Gregor5e9392b2011-12-03 18:14:24 +00002827 case UTT_IsFinal:
2828 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2829 return RD->hasAttr<FinalAttr>();
2830 return false;
John Wiegley20c0da72011-04-27 23:09:49 +00002831 case UTT_IsSigned:
2832 return T->isSignedIntegerType();
John Wiegley20c0da72011-04-27 23:09:49 +00002833 case UTT_IsUnsigned:
2834 return T->isUnsignedIntegerType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002835
2836 // Type trait expressions which query classes regarding their construction,
2837 // destruction, and copying. Rather than being based directly on the
2838 // related type predicates in the standard, they are specified by both
2839 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
2840 // specifications.
2841 //
2842 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
2843 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Sean Hunt023df372011-05-09 18:22:59 +00002844 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002845 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2846 // If __is_pod (type) is true then the trait is true, else if type is
2847 // a cv class or union type (or array thereof) with a trivial default
2848 // constructor ([class.ctor]) then the trait is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00002849 if (T.isPODType(Self.Context))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002850 return true;
2851 if (const RecordType *RT =
2852 C.getBaseElementType(T)->getAs<RecordType>())
Sean Hunt023df372011-05-09 18:22:59 +00002853 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDefaultConstructor();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002854 return false;
2855 case UTT_HasTrivialCopy:
2856 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2857 // If __is_pod (type) is true or type is a reference type then
2858 // the trait is true, else if type is a cv class or union type
2859 // with a trivial copy constructor ([class.copy]) then the trait
2860 // is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00002861 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002862 return true;
2863 if (const RecordType *RT = T->getAs<RecordType>())
2864 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2865 return false;
2866 case UTT_HasTrivialAssign:
2867 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2868 // If type is const qualified or is a reference type then the
2869 // trait is false. Otherwise if __is_pod (type) is true then the
2870 // trait is true, else if type is a cv class or union type with
2871 // a trivial copy assignment ([class.copy]) then the trait is
2872 // true, else it is false.
2873 // Note: the const and reference restrictions are interesting,
2874 // given that const and reference members don't prevent a class
2875 // from having a trivial copy assignment operator (but do cause
2876 // errors if the copy assignment operator is actually used, q.v.
2877 // [class.copy]p12).
2878
2879 if (C.getBaseElementType(T).isConstQualified())
2880 return false;
John McCallf85e1932011-06-15 23:02:42 +00002881 if (T.isPODType(Self.Context))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002882 return true;
2883 if (const RecordType *RT = T->getAs<RecordType>())
2884 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2885 return false;
2886 case UTT_HasTrivialDestructor:
2887 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2888 // If __is_pod (type) is true or type is a reference type
2889 // then the trait is true, else if type is a cv class or union
2890 // type (or array thereof) with a trivial destructor
2891 // ([class.dtor]) then the trait is true, else it is
2892 // false.
John McCallf85e1932011-06-15 23:02:42 +00002893 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002894 return true;
John McCallf85e1932011-06-15 23:02:42 +00002895
2896 // Objective-C++ ARC: autorelease types don't require destruction.
2897 if (T->isObjCLifetimeType() &&
2898 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
2899 return true;
2900
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002901 if (const RecordType *RT =
2902 C.getBaseElementType(T)->getAs<RecordType>())
2903 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2904 return false;
2905 // TODO: Propagate nothrowness for implicitly declared special members.
2906 case UTT_HasNothrowAssign:
2907 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2908 // If type is const qualified or is a reference type then the
2909 // trait is false. Otherwise if __has_trivial_assign (type)
2910 // is true then the trait is true, else if type is a cv class
2911 // or union type with copy assignment operators that are known
2912 // not to throw an exception then the trait is true, else it is
2913 // false.
2914 if (C.getBaseElementType(T).isConstQualified())
2915 return false;
2916 if (T->isReferenceType())
2917 return false;
John McCallf85e1932011-06-15 23:02:42 +00002918 if (T.isPODType(Self.Context) || T->isObjCLifetimeType())
2919 return true;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002920 if (const RecordType *RT = T->getAs<RecordType>()) {
2921 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2922 if (RD->hasTrivialCopyAssignment())
2923 return true;
2924
2925 bool FoundAssign = false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002926 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redlf8aca862010-09-14 23:40:14 +00002927 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2928 Sema::LookupOrdinaryName);
2929 if (Self.LookupQualifiedName(Res, RD)) {
Douglas Gregord41679d2011-10-12 15:40:49 +00002930 Res.suppressDiagnostics();
Sebastian Redlf8aca862010-09-14 23:40:14 +00002931 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2932 Op != OpEnd; ++Op) {
Douglas Gregord41679d2011-10-12 15:40:49 +00002933 if (isa<FunctionTemplateDecl>(*Op))
2934 continue;
2935
Sebastian Redlf8aca862010-09-14 23:40:14 +00002936 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2937 if (Operator->isCopyAssignmentOperator()) {
2938 FoundAssign = true;
2939 const FunctionProtoType *CPT
2940 = Operator->getType()->getAs<FunctionProtoType>();
Richard Smith7a614d82011-06-11 17:19:42 +00002941 if (CPT->getExceptionSpecType() == EST_Delayed)
2942 return false;
2943 if (!CPT->isNothrow(Self.Context))
2944 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002945 }
2946 }
2947 }
Douglas Gregord41679d2011-10-12 15:40:49 +00002948
Richard Smith7a614d82011-06-11 17:19:42 +00002949 return FoundAssign;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002950 }
2951 return false;
2952 case UTT_HasNothrowCopy:
2953 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2954 // If __has_trivial_copy (type) is true then the trait is true, else
2955 // if type is a cv class or union type with copy constructors that are
2956 // known not to throw an exception then the trait is true, else it is
2957 // false.
John McCallf85e1932011-06-15 23:02:42 +00002958 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002959 return true;
2960 if (const RecordType *RT = T->getAs<RecordType>()) {
2961 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2962 if (RD->hasTrivialCopyConstructor())
2963 return true;
2964
2965 bool FoundConstructor = false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002966 unsigned FoundTQs;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002967 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl5f4e8992010-09-13 21:10:20 +00002968 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002969 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002970 // A template constructor is never a copy constructor.
2971 // FIXME: However, it may actually be selected at the actual overload
2972 // resolution point.
2973 if (isa<FunctionTemplateDecl>(*Con))
2974 continue;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002975 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2976 if (Constructor->isCopyConstructor(FoundTQs)) {
2977 FoundConstructor = true;
2978 const FunctionProtoType *CPT
2979 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smith7a614d82011-06-11 17:19:42 +00002980 if (CPT->getExceptionSpecType() == EST_Delayed)
2981 return false;
Sebastian Redl60618fa2011-03-12 11:50:43 +00002982 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redl751025d2010-09-13 22:02:47 +00002983 // For now, we'll be conservative and assume that they can throw.
Richard Smith7a614d82011-06-11 17:19:42 +00002984 if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1)
2985 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002986 }
2987 }
2988
Richard Smith7a614d82011-06-11 17:19:42 +00002989 return FoundConstructor;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002990 }
2991 return false;
2992 case UTT_HasNothrowConstructor:
2993 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2994 // If __has_trivial_constructor (type) is true then the trait is
2995 // true, else if type is a cv class or union type (or array
2996 // thereof) with a default constructor that is known not to
2997 // throw an exception then the trait is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00002998 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002999 return true;
3000 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
3001 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Hunt023df372011-05-09 18:22:59 +00003002 if (RD->hasTrivialDefaultConstructor())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003003 return true;
3004
Sebastian Redl751025d2010-09-13 22:02:47 +00003005 DeclContext::lookup_const_iterator Con, ConEnd;
3006 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
3007 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00003008 // FIXME: In C++0x, a constructor template can be a default constructor.
3009 if (isa<FunctionTemplateDecl>(*Con))
3010 continue;
Sebastian Redl751025d2010-09-13 22:02:47 +00003011 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3012 if (Constructor->isDefaultConstructor()) {
3013 const FunctionProtoType *CPT
3014 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smith7a614d82011-06-11 17:19:42 +00003015 if (CPT->getExceptionSpecType() == EST_Delayed)
3016 return false;
Sebastian Redl751025d2010-09-13 22:02:47 +00003017 // TODO: check whether evaluating default arguments can throw.
3018 // For now, we'll be conservative and assume that they can throw.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00003019 return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
Sebastian Redl751025d2010-09-13 22:02:47 +00003020 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003021 }
3022 }
3023 return false;
3024 case UTT_HasVirtualDestructor:
3025 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3026 // If type is a class type with a virtual destructor ([class.dtor])
3027 // then the trait is true, else it is false.
3028 if (const RecordType *Record = T->getAs<RecordType>()) {
3029 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redlf8aca862010-09-14 23:40:14 +00003030 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003031 return Destructor->isVirtual();
3032 }
3033 return false;
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003034
3035 // These type trait expressions are modeled on the specifications for the
3036 // Embarcadero C++0x type trait functions:
3037 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
3038 case UTT_IsCompleteType:
3039 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
3040 // Returns True if and only if T is a complete type at the point of the
3041 // function call.
3042 return !T->isIncompleteType();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003043 }
Chandler Carruth83f563c2011-05-01 07:44:17 +00003044 llvm_unreachable("Type trait not covered by switch");
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003045}
3046
3047ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00003048 SourceLocation KWLoc,
3049 TypeSourceInfo *TSInfo,
3050 SourceLocation RParen) {
3051 QualType T = TSInfo->getType();
Chandler Carrutheb65a102011-04-30 10:07:32 +00003052 if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T))
3053 return ExprError();
Sebastian Redl64b45f72009-01-05 20:52:13 +00003054
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003055 bool Value = false;
3056 if (!T->isDependentType())
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00003057 Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003058
3059 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson3292d5c2009-07-07 19:06:02 +00003060 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00003061}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003062
Francois Pichet6ad6f282010-12-07 00:08:36 +00003063ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
3064 SourceLocation KWLoc,
3065 ParsedType LhsTy,
3066 ParsedType RhsTy,
3067 SourceLocation RParen) {
3068 TypeSourceInfo *LhsTSInfo;
3069 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
3070 if (!LhsTSInfo)
3071 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
3072
3073 TypeSourceInfo *RhsTSInfo;
3074 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
3075 if (!RhsTSInfo)
3076 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
3077
3078 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
3079}
3080
3081static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
3082 QualType LhsT, QualType RhsT,
3083 SourceLocation KeyLoc) {
Chandler Carruthd064c702011-05-01 08:41:10 +00003084 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
3085 "Cannot evaluate traits of dependent types");
Francois Pichet6ad6f282010-12-07 00:08:36 +00003086
3087 switch(BTT) {
John McCalld89d30f2011-01-28 22:02:36 +00003088 case BTT_IsBaseOf: {
Francois Pichet6ad6f282010-12-07 00:08:36 +00003089 // C++0x [meta.rel]p2
John McCalld89d30f2011-01-28 22:02:36 +00003090 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet6ad6f282010-12-07 00:08:36 +00003091 // Base and Derived are not unions and name the same class type without
3092 // regard to cv-qualifiers.
Francois Pichet6ad6f282010-12-07 00:08:36 +00003093
John McCalld89d30f2011-01-28 22:02:36 +00003094 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
3095 if (!lhsRecord) return false;
3096
3097 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
3098 if (!rhsRecord) return false;
3099
3100 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
3101 == (lhsRecord == rhsRecord));
3102
3103 if (lhsRecord == rhsRecord)
3104 return !lhsRecord->getDecl()->isUnion();
3105
3106 // C++0x [meta.rel]p2:
3107 // If Base and Derived are class types and are different types
3108 // (ignoring possible cv-qualifiers) then Derived shall be a
3109 // complete type.
3110 if (Self.RequireCompleteType(KeyLoc, RhsT,
3111 diag::err_incomplete_type_used_in_type_trait_expr))
3112 return false;
3113
3114 return cast<CXXRecordDecl>(rhsRecord->getDecl())
3115 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
3116 }
John Wiegley20c0da72011-04-27 23:09:49 +00003117 case BTT_IsSame:
3118 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichetf1872372010-12-08 22:35:30 +00003119 case BTT_TypeCompatible:
3120 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
3121 RhsT.getUnqualifiedType());
John Wiegley20c0da72011-04-27 23:09:49 +00003122 case BTT_IsConvertible:
Douglas Gregor9f361132011-01-27 20:28:01 +00003123 case BTT_IsConvertibleTo: {
3124 // C++0x [meta.rel]p4:
3125 // Given the following function prototype:
3126 //
3127 // template <class T>
3128 // typename add_rvalue_reference<T>::type create();
3129 //
3130 // the predicate condition for a template specialization
3131 // is_convertible<From, To> shall be satisfied if and only if
3132 // the return expression in the following code would be
3133 // well-formed, including any implicit conversions to the return
3134 // type of the function:
3135 //
3136 // To test() {
3137 // return create<From>();
3138 // }
3139 //
3140 // Access checking is performed as if in a context unrelated to To and
3141 // From. Only the validity of the immediate context of the expression
3142 // of the return-statement (including conversions to the return type)
3143 // is considered.
3144 //
3145 // We model the initialization as a copy-initialization of a temporary
3146 // of the appropriate type, which for this expression is identical to the
3147 // return statement (since NRVO doesn't apply).
3148 if (LhsT->isObjectType() || LhsT->isFunctionType())
3149 LhsT = Self.Context.getRValueReferenceType(LhsT);
3150
3151 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorb608b982011-01-28 02:26:04 +00003152 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor9f361132011-01-27 20:28:01 +00003153 Expr::getValueKindForType(LhsT));
3154 Expr *FromPtr = &From;
3155 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
3156 SourceLocation()));
3157
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00003158 // Perform the initialization within a SFINAE trap at translation unit
3159 // scope.
3160 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3161 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Douglas Gregor9f361132011-01-27 20:28:01 +00003162 InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003163 if (Init.Failed())
Douglas Gregor9f361132011-01-27 20:28:01 +00003164 return false;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00003165
Douglas Gregor9f361132011-01-27 20:28:01 +00003166 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
3167 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
3168 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00003169 }
3170 llvm_unreachable("Unknown type trait or not implemented");
3171}
3172
3173ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
3174 SourceLocation KWLoc,
3175 TypeSourceInfo *LhsTSInfo,
3176 TypeSourceInfo *RhsTSInfo,
3177 SourceLocation RParen) {
3178 QualType LhsT = LhsTSInfo->getType();
3179 QualType RhsT = RhsTSInfo->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003180
John McCalld89d30f2011-01-28 22:02:36 +00003181 if (BTT == BTT_TypeCompatible) {
Francois Pichetf1872372010-12-08 22:35:30 +00003182 if (getLangOptions().CPlusPlus) {
3183 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
3184 << SourceRange(KWLoc, RParen);
3185 return ExprError();
3186 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00003187 }
3188
3189 bool Value = false;
3190 if (!LhsT->isDependentType() && !RhsT->isDependentType())
3191 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
3192
Francois Pichetf1872372010-12-08 22:35:30 +00003193 // Select trait result type.
3194 QualType ResultType;
3195 switch (BTT) {
Francois Pichetf1872372010-12-08 22:35:30 +00003196 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
John Wiegley20c0da72011-04-27 23:09:49 +00003197 case BTT_IsConvertible: ResultType = Context.BoolTy; break;
3198 case BTT_IsSame: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00003199 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
Douglas Gregor9f361132011-01-27 20:28:01 +00003200 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00003201 }
3202
Francois Pichet6ad6f282010-12-07 00:08:36 +00003203 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
3204 RhsTSInfo, Value, RParen,
Francois Pichetf1872372010-12-08 22:35:30 +00003205 ResultType));
Francois Pichet6ad6f282010-12-07 00:08:36 +00003206}
3207
John Wiegley21ff2e52011-04-28 00:16:57 +00003208ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3209 SourceLocation KWLoc,
3210 ParsedType Ty,
3211 Expr* DimExpr,
3212 SourceLocation RParen) {
3213 TypeSourceInfo *TSInfo;
3214 QualType T = GetTypeFromParser(Ty, &TSInfo);
3215 if (!TSInfo)
3216 TSInfo = Context.getTrivialTypeSourceInfo(T);
3217
3218 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
3219}
3220
3221static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
3222 QualType T, Expr *DimExpr,
3223 SourceLocation KeyLoc) {
Chandler Carruthd064c702011-05-01 08:41:10 +00003224 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley21ff2e52011-04-28 00:16:57 +00003225
3226 switch(ATT) {
3227 case ATT_ArrayRank:
3228 if (T->isArrayType()) {
3229 unsigned Dim = 0;
3230 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3231 ++Dim;
3232 T = AT->getElementType();
3233 }
3234 return Dim;
John Wiegley21ff2e52011-04-28 00:16:57 +00003235 }
John Wiegleycf566412011-04-28 02:06:46 +00003236 return 0;
3237
John Wiegley21ff2e52011-04-28 00:16:57 +00003238 case ATT_ArrayExtent: {
3239 llvm::APSInt Value;
3240 uint64_t Dim;
John Wiegleycf566412011-04-28 02:06:46 +00003241 if (DimExpr->isIntegerConstantExpr(Value, Self.Context, 0, false)) {
3242 if (Value < llvm::APSInt(Value.getBitWidth(), Value.isUnsigned())) {
3243 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
3244 DimExpr->getSourceRange();
3245 return false;
3246 }
John Wiegley21ff2e52011-04-28 00:16:57 +00003247 Dim = Value.getLimitedValue();
John Wiegleycf566412011-04-28 02:06:46 +00003248 } else {
3249 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
3250 DimExpr->getSourceRange();
3251 return false;
3252 }
John Wiegley21ff2e52011-04-28 00:16:57 +00003253
3254 if (T->isArrayType()) {
3255 unsigned D = 0;
3256 bool Matched = false;
3257 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3258 if (Dim == D) {
3259 Matched = true;
3260 break;
3261 }
3262 ++D;
3263 T = AT->getElementType();
3264 }
3265
John Wiegleycf566412011-04-28 02:06:46 +00003266 if (Matched && T->isArrayType()) {
3267 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
3268 return CAT->getSize().getLimitedValue();
3269 }
John Wiegley21ff2e52011-04-28 00:16:57 +00003270 }
John Wiegleycf566412011-04-28 02:06:46 +00003271 return 0;
John Wiegley21ff2e52011-04-28 00:16:57 +00003272 }
3273 }
3274 llvm_unreachable("Unknown type trait or not implemented");
3275}
3276
3277ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
3278 SourceLocation KWLoc,
3279 TypeSourceInfo *TSInfo,
3280 Expr* DimExpr,
3281 SourceLocation RParen) {
3282 QualType T = TSInfo->getType();
John Wiegley21ff2e52011-04-28 00:16:57 +00003283
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003284 // FIXME: This should likely be tracked as an APInt to remove any host
3285 // assumptions about the width of size_t on the target.
Chandler Carruthd064c702011-05-01 08:41:10 +00003286 uint64_t Value = 0;
3287 if (!T->isDependentType())
3288 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
3289
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003290 // While the specification for these traits from the Embarcadero C++
3291 // compiler's documentation says the return type is 'unsigned int', Clang
3292 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
3293 // compiler, there is no difference. On several other platforms this is an
3294 // important distinction.
John Wiegley21ff2e52011-04-28 00:16:57 +00003295 return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value,
Chandler Carruth06207f62011-05-01 07:49:26 +00003296 DimExpr, RParen,
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003297 Context.getSizeType()));
John Wiegley21ff2e52011-04-28 00:16:57 +00003298}
3299
John Wiegley55262202011-04-25 06:54:41 +00003300ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003301 SourceLocation KWLoc,
3302 Expr *Queried,
3303 SourceLocation RParen) {
John Wiegley55262202011-04-25 06:54:41 +00003304 // If error parsing the expression, ignore.
3305 if (!Queried)
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003306 return ExprError();
John Wiegley55262202011-04-25 06:54:41 +00003307
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003308 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegley55262202011-04-25 06:54:41 +00003309
3310 return move(Result);
3311}
3312
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003313static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
3314 switch (ET) {
3315 case ET_IsLValueExpr: return E->isLValue();
3316 case ET_IsRValueExpr: return E->isRValue();
3317 }
3318 llvm_unreachable("Expression trait not covered by switch");
3319}
3320
John Wiegley55262202011-04-25 06:54:41 +00003321ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003322 SourceLocation KWLoc,
3323 Expr *Queried,
3324 SourceLocation RParen) {
John Wiegley55262202011-04-25 06:54:41 +00003325 if (Queried->isTypeDependent()) {
3326 // Delay type-checking for type-dependent expressions.
3327 } else if (Queried->getType()->isPlaceholderType()) {
3328 ExprResult PE = CheckPlaceholderExpr(Queried);
3329 if (PE.isInvalid()) return ExprError();
3330 return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen);
3331 }
3332
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003333 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf7ef0002011-05-01 08:48:19 +00003334
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003335 return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value,
3336 RParen, Context.BoolTy));
John Wiegley55262202011-04-25 06:54:41 +00003337}
3338
Richard Trieudd225092011-09-15 21:56:47 +00003339QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCallf89e55a2010-11-18 06:31:45 +00003340 ExprValueKind &VK,
3341 SourceLocation Loc,
3342 bool isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003343 assert(!LHS.get()->getType()->isPlaceholderType() &&
3344 !RHS.get()->getType()->isPlaceholderType() &&
John McCallea4aba02011-06-30 17:15:34 +00003345 "placeholders should have been weeded out by now");
3346
3347 // The LHS undergoes lvalue conversions if this is ->*.
3348 if (isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003349 LHS = DefaultLvalueConversion(LHS.take());
3350 if (LHS.isInvalid()) return QualType();
John McCallea4aba02011-06-30 17:15:34 +00003351 }
3352
3353 // The RHS always undergoes lvalue conversions.
Richard Trieudd225092011-09-15 21:56:47 +00003354 RHS = DefaultLvalueConversion(RHS.take());
3355 if (RHS.isInvalid()) return QualType();
John McCallea4aba02011-06-30 17:15:34 +00003356
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003357 const char *OpSpelling = isIndirect ? "->*" : ".*";
3358 // C++ 5.5p2
3359 // The binary operator .* [p3: ->*] binds its second operand, which shall
3360 // be of type "pointer to member of T" (where T is a completely-defined
3361 // class type) [...]
Richard Trieudd225092011-09-15 21:56:47 +00003362 QualType RHSType = RHS.get()->getType();
3363 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00003364 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003365 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieudd225092011-09-15 21:56:47 +00003366 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003367 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00003368 }
Douglas Gregore7450f52009-03-24 19:52:54 +00003369
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003370 QualType Class(MemPtr->getClass(), 0);
3371
Douglas Gregor7d520ba2010-10-13 20:41:14 +00003372 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
3373 // member pointer points must be completely-defined. However, there is no
3374 // reason for this semantic distinction, and the rule is not enforced by
3375 // other compilers. Therefore, we do not check this property, as it is
3376 // likely to be considered a defect.
Sebastian Redl59fc2692010-04-10 10:14:54 +00003377
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003378 // C++ 5.5p2
3379 // [...] to its first operand, which shall be of class T or of a class of
3380 // which T is an unambiguous and accessible base class. [p3: a pointer to
3381 // such a class]
Richard Trieudd225092011-09-15 21:56:47 +00003382 QualType LHSType = LHS.get()->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003383 if (isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003384 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
3385 LHSType = Ptr->getPointeeType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003386 else {
3387 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieudd225092011-09-15 21:56:47 +00003388 << OpSpelling << 1 << LHSType
Douglas Gregor849b2432010-03-31 17:46:05 +00003389 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003390 return QualType();
3391 }
3392 }
3393
Richard Trieudd225092011-09-15 21:56:47 +00003394 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00003395 // If we want to check the hierarchy, we need a complete type.
Richard Trieudd225092011-09-15 21:56:47 +00003396 if (RequireCompleteType(Loc, LHSType, PDiag(diag::err_bad_memptr_lhs)
Sebastian Redl17e1d352010-04-23 17:18:26 +00003397 << OpSpelling << (int)isIndirect)) {
3398 return QualType();
3399 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003400 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00003401 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00003402 // FIXME: Would it be useful to print full ambiguity paths, or is that
3403 // overkill?
Richard Trieudd225092011-09-15 21:56:47 +00003404 if (!IsDerivedFrom(LHSType, Class, Paths) ||
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003405 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
3406 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieudd225092011-09-15 21:56:47 +00003407 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003408 return QualType();
3409 }
Eli Friedman3005efe2010-01-16 00:00:48 +00003410 // Cast LHS to type of use.
3411 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00003412 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Sebastian Redl906082e2010-07-20 04:20:21 +00003413
John McCallf871d0c2010-08-07 06:22:56 +00003414 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003415 BuildBasePathArray(Paths, BasePath);
Richard Trieudd225092011-09-15 21:56:47 +00003416 LHS = ImpCastExprToType(LHS.take(), UseType, CK_DerivedToBase, VK,
3417 &BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003418 }
3419
Richard Trieudd225092011-09-15 21:56:47 +00003420 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00003421 // Diagnose use of pointer-to-member type which when used as
3422 // the functional cast in a pointer-to-member expression.
3423 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
3424 return QualType();
3425 }
John McCallf89e55a2010-11-18 06:31:45 +00003426
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003427 // C++ 5.5p2
3428 // The result is an object or a function of the type specified by the
3429 // second operand.
3430 // The cv qualifiers are the union of those in the pointer and the left side,
3431 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003432 QualType Result = MemPtr->getPointeeType();
Richard Trieudd225092011-09-15 21:56:47 +00003433 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCallf89e55a2010-11-18 06:31:45 +00003434
Douglas Gregor6b4df912011-01-26 16:40:18 +00003435 // C++0x [expr.mptr.oper]p6:
3436 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003437 // ill-formed if the second operand is a pointer to member function with
3438 // ref-qualifier &. In a ->* expression or in a .* expression whose object
3439 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor6b4df912011-01-26 16:40:18 +00003440 // is a pointer to member function with ref-qualifier &&.
3441 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
3442 switch (Proto->getRefQualifier()) {
3443 case RQ_None:
3444 // Do nothing
3445 break;
3446
3447 case RQ_LValue:
Richard Trieudd225092011-09-15 21:56:47 +00003448 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
Douglas Gregor6b4df912011-01-26 16:40:18 +00003449 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieudd225092011-09-15 21:56:47 +00003450 << RHSType << 1 << LHS.get()->getSourceRange();
Douglas Gregor6b4df912011-01-26 16:40:18 +00003451 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003452
Douglas Gregor6b4df912011-01-26 16:40:18 +00003453 case RQ_RValue:
Richard Trieudd225092011-09-15 21:56:47 +00003454 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor6b4df912011-01-26 16:40:18 +00003455 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieudd225092011-09-15 21:56:47 +00003456 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor6b4df912011-01-26 16:40:18 +00003457 break;
3458 }
3459 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003460
John McCallf89e55a2010-11-18 06:31:45 +00003461 // C++ [expr.mptr.oper]p6:
3462 // The result of a .* expression whose second operand is a pointer
3463 // to a data member is of the same value category as its
3464 // first operand. The result of a .* expression whose second
3465 // operand is a pointer to a member function is a prvalue. The
3466 // result of an ->* expression is an lvalue if its second operand
3467 // is a pointer to data member and a prvalue otherwise.
John McCall864c0412011-04-26 20:42:42 +00003468 if (Result->isFunctionType()) {
John McCallf89e55a2010-11-18 06:31:45 +00003469 VK = VK_RValue;
John McCall864c0412011-04-26 20:42:42 +00003470 return Context.BoundMemberTy;
3471 } else if (isIndirect) {
John McCallf89e55a2010-11-18 06:31:45 +00003472 VK = VK_LValue;
John McCall864c0412011-04-26 20:42:42 +00003473 } else {
Richard Trieudd225092011-09-15 21:56:47 +00003474 VK = LHS.get()->getValueKind();
John McCall864c0412011-04-26 20:42:42 +00003475 }
John McCallf89e55a2010-11-18 06:31:45 +00003476
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003477 return Result;
3478}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003479
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003480/// \brief Try to convert a type to another according to C++0x 5.16p3.
3481///
3482/// This is part of the parameter validation for the ? operator. If either
3483/// value operand is a class type, the two operands are attempted to be
3484/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003485/// It returns true if the program is ill-formed and has already been diagnosed
3486/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003487static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
3488 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00003489 bool &HaveConversion,
3490 QualType &ToType) {
3491 HaveConversion = false;
3492 ToType = To->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003493
3494 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00003495 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003496 // C++0x 5.16p3
3497 // The process for determining whether an operand expression E1 of type T1
3498 // can be converted to match an operand expression E2 of type T2 is defined
3499 // as follows:
3500 // -- If E2 is an lvalue:
John McCall7eb0a9e2010-11-24 05:12:34 +00003501 bool ToIsLvalue = To->isLValue();
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00003502 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003503 // E1 can be converted to match E2 if E1 can be implicitly converted to
3504 // type "lvalue reference to T2", subject to the constraint that in the
3505 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003506 QualType T = Self.Context.getLValueReferenceType(ToType);
3507 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003508
Douglas Gregorb70cf442010-03-26 20:14:36 +00003509 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3510 if (InitSeq.isDirectReferenceBinding()) {
3511 ToType = T;
3512 HaveConversion = true;
3513 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003514 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003515
Douglas Gregorb70cf442010-03-26 20:14:36 +00003516 if (InitSeq.isAmbiguous())
3517 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003518 }
John McCallb1bdc622010-02-25 01:37:24 +00003519
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003520 // -- If E2 is an rvalue, or if the conversion above cannot be done:
3521 // -- if E1 and E2 have class type, and the underlying class types are
3522 // the same or one is a base class of the other:
3523 QualType FTy = From->getType();
3524 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003525 const RecordType *FRec = FTy->getAs<RecordType>();
3526 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003527 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00003528 Self.IsDerivedFrom(FTy, TTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003529 if (FRec && TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00003530 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003531 // E1 can be converted to match E2 if the class of T2 is the
3532 // same type as, or a base class of, the class of T1, and
3533 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00003534 if (FRec == TRec || FDerivedFromT) {
3535 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003536 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3537 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003538 if (InitSeq) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003539 HaveConversion = true;
3540 return false;
3541 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003542
Douglas Gregorb70cf442010-03-26 20:14:36 +00003543 if (InitSeq.isAmbiguous())
3544 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003545 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003546 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003547
Douglas Gregorb70cf442010-03-26 20:14:36 +00003548 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003549 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003550
Douglas Gregorb70cf442010-03-26 20:14:36 +00003551 // -- Otherwise: E1 can be converted to match E2 if E1 can be
3552 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003553 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00003554 // an rvalue).
3555 //
3556 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
3557 // to the array-to-pointer or function-to-pointer conversions.
3558 if (!TTy->getAs<TagType>())
3559 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003560
Douglas Gregorb70cf442010-03-26 20:14:36 +00003561 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3562 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003563 HaveConversion = !InitSeq.Failed();
Douglas Gregorb70cf442010-03-26 20:14:36 +00003564 ToType = TTy;
3565 if (InitSeq.isAmbiguous())
3566 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3567
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003568 return false;
3569}
3570
3571/// \brief Try to find a common type for two according to C++0x 5.16p5.
3572///
3573/// This is part of the parameter validation for the ? operator. If either
3574/// value operand is a class type, overload resolution is used to find a
3575/// conversion to a common type.
John Wiegley429bb272011-04-08 18:41:53 +00003576static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth82214a82011-02-18 23:54:50 +00003577 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00003578 Expr *Args[2] = { LHS.get(), RHS.get() };
Chandler Carruth82214a82011-02-18 23:54:50 +00003579 OverloadCandidateSet CandidateSet(QuestionLoc);
3580 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
3581 CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003582
3583 OverloadCandidateSet::iterator Best;
Chandler Carruth82214a82011-02-18 23:54:50 +00003584 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley429bb272011-04-08 18:41:53 +00003585 case OR_Success: {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003586 // We found a match. Perform the conversions on the arguments and move on.
John Wiegley429bb272011-04-08 18:41:53 +00003587 ExprResult LHSRes =
3588 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
3589 Best->Conversions[0], Sema::AA_Converting);
3590 if (LHSRes.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003591 break;
John Wiegley429bb272011-04-08 18:41:53 +00003592 LHS = move(LHSRes);
3593
3594 ExprResult RHSRes =
3595 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
3596 Best->Conversions[1], Sema::AA_Converting);
3597 if (RHSRes.isInvalid())
3598 break;
3599 RHS = move(RHSRes);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003600 if (Best->Function)
3601 Self.MarkDeclarationReferenced(QuestionLoc, Best->Function);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003602 return false;
John Wiegley429bb272011-04-08 18:41:53 +00003603 }
3604
Douglas Gregor20093b42009-12-09 23:02:17 +00003605 case OR_No_Viable_Function:
Chandler Carruth82214a82011-02-18 23:54:50 +00003606
3607 // Emit a better diagnostic if one of the expressions is a null pointer
3608 // constant and the other is a pointer type. In this case, the user most
3609 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00003610 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00003611 return true;
3612
3613 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00003614 << LHS.get()->getType() << RHS.get()->getType()
3615 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003616 return true;
3617
Douglas Gregor20093b42009-12-09 23:02:17 +00003618 case OR_Ambiguous:
Chandler Carruth82214a82011-02-18 23:54:50 +00003619 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley429bb272011-04-08 18:41:53 +00003620 << LHS.get()->getType() << RHS.get()->getType()
3621 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00003622 // FIXME: Print the possible common types by printing the return types of
3623 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003624 break;
3625
Douglas Gregor20093b42009-12-09 23:02:17 +00003626 case OR_Deleted:
David Blaikieb219cfc2011-09-23 05:06:16 +00003627 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003628 }
3629 return true;
3630}
3631
Sebastian Redl76458502009-04-17 16:30:52 +00003632/// \brief Perform an "extended" implicit conversion as returned by
3633/// TryClassUnification.
John Wiegley429bb272011-04-08 18:41:53 +00003634static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003635 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley429bb272011-04-08 18:41:53 +00003636 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00003637 SourceLocation());
John Wiegley429bb272011-04-08 18:41:53 +00003638 Expr *Arg = E.take();
3639 InitializationSequence InitSeq(Self, Entity, Kind, &Arg, 1);
3640 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&Arg, 1));
Douglas Gregorb70cf442010-03-26 20:14:36 +00003641 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00003642 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003643
John Wiegley429bb272011-04-08 18:41:53 +00003644 E = Result;
Sebastian Redl76458502009-04-17 16:30:52 +00003645 return false;
3646}
3647
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003648/// \brief Check the operands of ?: under C++ semantics.
3649///
3650/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
3651/// extension. In this case, LHS == Cond. (But they're not aliases.)
John Wiegley429bb272011-04-08 18:41:53 +00003652QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCall56ca35d2011-02-17 10:25:35 +00003653 ExprValueKind &VK, ExprObjectKind &OK,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003654 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00003655 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
3656 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003657
3658 // C++0x 5.16p1
3659 // The first expression is contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00003660 if (!Cond.get()->isTypeDependent()) {
3661 ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
3662 if (CondRes.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003663 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003664 Cond = move(CondRes);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003665 }
3666
John McCallf89e55a2010-11-18 06:31:45 +00003667 // Assume r-value.
3668 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00003669 OK = OK_Ordinary;
John McCallf89e55a2010-11-18 06:31:45 +00003670
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003671 // Either of the arguments dependent?
John Wiegley429bb272011-04-08 18:41:53 +00003672 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003673 return Context.DependentTy;
3674
3675 // C++0x 5.16p2
3676 // If either the second or the third operand has type (cv) void, ...
John Wiegley429bb272011-04-08 18:41:53 +00003677 QualType LTy = LHS.get()->getType();
3678 QualType RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003679 bool LVoid = LTy->isVoidType();
3680 bool RVoid = RTy->isVoidType();
3681 if (LVoid || RVoid) {
3682 // ... then the [l2r] conversions are performed on the second and third
3683 // operands ...
John Wiegley429bb272011-04-08 18:41:53 +00003684 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3685 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3686 if (LHS.isInvalid() || RHS.isInvalid())
3687 return QualType();
3688 LTy = LHS.get()->getType();
3689 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003690
3691 // ... and one of the following shall hold:
3692 // -- The second or the third operand (but not both) is a throw-
3693 // expression; the result is of the type of the other and is an rvalue.
John Wiegley429bb272011-04-08 18:41:53 +00003694 bool LThrow = isa<CXXThrowExpr>(LHS.get());
3695 bool RThrow = isa<CXXThrowExpr>(RHS.get());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003696 if (LThrow && !RThrow)
3697 return RTy;
3698 if (RThrow && !LThrow)
3699 return LTy;
3700
3701 // -- Both the second and third operands have type void; the result is of
3702 // type void and is an rvalue.
3703 if (LVoid && RVoid)
3704 return Context.VoidTy;
3705
3706 // Neither holds, error.
3707 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
3708 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley429bb272011-04-08 18:41:53 +00003709 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003710 return QualType();
3711 }
3712
3713 // Neither is void.
3714
3715 // C++0x 5.16p3
3716 // Otherwise, if the second and third operand have different types, and
3717 // either has (cv) class type, and attempt is made to convert each of those
3718 // operands to the other.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003719 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003720 (LTy->isRecordType() || RTy->isRecordType())) {
3721 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
3722 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003723 QualType L2RType, R2LType;
3724 bool HaveL2R, HaveR2L;
John Wiegley429bb272011-04-08 18:41:53 +00003725 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003726 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003727 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003728 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003729
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003730 // If both can be converted, [...] the program is ill-formed.
3731 if (HaveL2R && HaveR2L) {
3732 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley429bb272011-04-08 18:41:53 +00003733 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003734 return QualType();
3735 }
3736
3737 // If exactly one conversion is possible, that conversion is applied to
3738 // the chosen operand and the converted operands are used in place of the
3739 // original operands for the remainder of this section.
3740 if (HaveL2R) {
John Wiegley429bb272011-04-08 18:41:53 +00003741 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003742 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003743 LTy = LHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003744 } else if (HaveR2L) {
John Wiegley429bb272011-04-08 18:41:53 +00003745 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003746 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003747 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003748 }
3749 }
3750
3751 // C++0x 5.16p4
John McCallf89e55a2010-11-18 06:31:45 +00003752 // If the second and third operands are glvalues of the same value
3753 // category and have the same type, the result is of that type and
3754 // value category and it is a bit-field if the second or the third
3755 // operand is a bit-field, or if both are bit-fields.
John McCall09431682010-11-18 19:01:18 +00003756 // We only extend this to bitfields, not to the crazy other kinds of
3757 // l-values.
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003758 bool Same = Context.hasSameType(LTy, RTy);
John McCallf89e55a2010-11-18 06:31:45 +00003759 if (Same &&
John Wiegley429bb272011-04-08 18:41:53 +00003760 LHS.get()->isGLValue() &&
3761 LHS.get()->getValueKind() == RHS.get()->getValueKind() &&
3762 LHS.get()->isOrdinaryOrBitFieldObject() &&
3763 RHS.get()->isOrdinaryOrBitFieldObject()) {
3764 VK = LHS.get()->getValueKind();
3765 if (LHS.get()->getObjectKind() == OK_BitField ||
3766 RHS.get()->getObjectKind() == OK_BitField)
John McCall09431682010-11-18 19:01:18 +00003767 OK = OK_BitField;
John McCallf89e55a2010-11-18 06:31:45 +00003768 return LTy;
Fariborz Jahanian3911a1a2010-09-25 01:08:05 +00003769 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003770
3771 // C++0x 5.16p5
3772 // Otherwise, the result is an rvalue. If the second and third operands
3773 // do not have the same type, and either has (cv) class type, ...
3774 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
3775 // ... overload resolution is used to determine the conversions (if any)
3776 // to be applied to the operands. If the overload resolution fails, the
3777 // program is ill-formed.
3778 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
3779 return QualType();
3780 }
3781
3782 // C++0x 5.16p6
3783 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
3784 // conversions are performed on the second and third operands.
John Wiegley429bb272011-04-08 18:41:53 +00003785 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3786 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3787 if (LHS.isInvalid() || RHS.isInvalid())
3788 return QualType();
3789 LTy = LHS.get()->getType();
3790 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003791
3792 // After those conversions, one of the following shall hold:
3793 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00003794 // is of that type. If the operands have class type, the result
3795 // is a prvalue temporary of the result type, which is
3796 // copy-initialized from either the second operand or the third
3797 // operand depending on the value of the first operand.
3798 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
3799 if (LTy->isRecordType()) {
3800 // The operands have class type. Make a temporary copy.
3801 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003802 ExprResult LHSCopy = PerformCopyInitialization(Entity,
3803 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00003804 LHS);
Douglas Gregorb65a4582010-05-19 23:40:50 +00003805 if (LHSCopy.isInvalid())
3806 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003807
3808 ExprResult RHSCopy = PerformCopyInitialization(Entity,
3809 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00003810 RHS);
Douglas Gregorb65a4582010-05-19 23:40:50 +00003811 if (RHSCopy.isInvalid())
3812 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003813
John Wiegley429bb272011-04-08 18:41:53 +00003814 LHS = LHSCopy;
3815 RHS = RHSCopy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00003816 }
3817
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003818 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00003819 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003820
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003821 // Extension: conditional operator involving vector types.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003822 if (LTy->isVectorType() || RTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00003823 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003824
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003825 // -- The second and third operands have arithmetic or enumeration type;
3826 // the usual arithmetic conversions are performed to bring them to a
3827 // common type, and the result is of that type.
3828 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
3829 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00003830 if (LHS.isInvalid() || RHS.isInvalid())
3831 return QualType();
3832 return LHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003833 }
3834
3835 // -- The second and third operands have pointer type, or one has pointer
3836 // type and the other is a null pointer constant; pointer conversions
3837 // and qualification conversions are performed to bring them to their
3838 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00003839 // -- The second and third operands have pointer to member type, or one has
3840 // pointer to member type and the other is a null pointer constant;
3841 // pointer to member conversions and qualification conversions are
3842 // performed to bring them to a common type, whose cv-qualification
3843 // shall match the cv-qualification of either the second or the third
3844 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003845 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003846 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003847 isSFINAEContext()? 0 : &NonStandardCompositeType);
3848 if (!Composite.isNull()) {
3849 if (NonStandardCompositeType)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003850 Diag(QuestionLoc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003851 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
3852 << LTy << RTy << Composite
John Wiegley429bb272011-04-08 18:41:53 +00003853 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003854
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003855 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003856 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003857
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003858 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00003859 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
3860 if (!Composite.isNull())
3861 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003862
Chandler Carruth7ef93242011-02-19 00:13:59 +00003863 // Check if we are using a null with a non-pointer type.
John Wiegley429bb272011-04-08 18:41:53 +00003864 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth7ef93242011-02-19 00:13:59 +00003865 return QualType();
3866
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003867 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00003868 << LHS.get()->getType() << RHS.get()->getType()
3869 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003870 return QualType();
3871}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003872
3873/// \brief Find a merged pointer type and convert the two expressions to it.
3874///
Douglas Gregor20b3e992009-08-24 17:42:35 +00003875/// This finds the composite pointer type (or member pointer type) for @p E1
3876/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
3877/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003878/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003879///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003880/// \param Loc The location of the operator requiring these two expressions to
3881/// be converted to the composite pointer type.
3882///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003883/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
3884/// a non-standard (but still sane) composite type to which both expressions
3885/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
3886/// will be set true.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003887QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003888 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003889 bool *NonStandardCompositeType) {
3890 if (NonStandardCompositeType)
3891 *NonStandardCompositeType = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003892
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003893 assert(getLangOptions().CPlusPlus && "This function assumes C++");
3894 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003895
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00003896 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
3897 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00003898 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003899
3900 // C++0x 5.9p2
3901 // Pointer conversions and qualification conversions are performed on
3902 // pointer operands to bring them to their composite pointer type. If
3903 // one operand is a null pointer constant, the composite pointer type is
3904 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00003905 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003906 if (T2->isMemberPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00003907 E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003908 else
John Wiegley429bb272011-04-08 18:41:53 +00003909 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003910 return T2;
3911 }
Douglas Gregorce940492009-09-25 04:25:58 +00003912 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003913 if (T1->isMemberPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00003914 E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003915 else
John Wiegley429bb272011-04-08 18:41:53 +00003916 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003917 return T1;
3918 }
Mike Stump1eb44332009-09-09 15:08:12 +00003919
Douglas Gregor20b3e992009-08-24 17:42:35 +00003920 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003921 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
3922 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003923 return QualType();
3924
3925 // Otherwise, of one of the operands has type "pointer to cv1 void," then
3926 // the other has type "pointer to cv2 T" and the composite pointer type is
3927 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
3928 // Otherwise, the composite pointer type is a pointer type similar to the
3929 // type of one of the operands, with a cv-qualification signature that is
3930 // the union of the cv-qualification signatures of the operand types.
3931 // In practice, the first part here is redundant; it's subsumed by the second.
3932 // What we do here is, we build the two possible composite types, and try the
3933 // conversions in both directions. If only one works, or if the two composite
3934 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00003935 // FIXME: extended qualifiers?
Chris Lattner5f9e2722011-07-23 10:55:15 +00003936 typedef SmallVector<unsigned, 4> QualifierVector;
Sebastian Redla439e6f2009-11-16 21:03:45 +00003937 QualifierVector QualifierUnion;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003938 typedef SmallVector<std::pair<const Type *, const Type *>, 4>
Sebastian Redla439e6f2009-11-16 21:03:45 +00003939 ContainingClassVector;
3940 ContainingClassVector MemberOfClass;
3941 QualType Composite1 = Context.getCanonicalType(T1),
3942 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003943 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00003944 do {
3945 const PointerType *Ptr1, *Ptr2;
3946 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3947 (Ptr2 = Composite2->getAs<PointerType>())) {
3948 Composite1 = Ptr1->getPointeeType();
3949 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003950
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003951 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003952 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003953 if (NonStandardCompositeType &&
3954 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3955 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003956
Douglas Gregor20b3e992009-08-24 17:42:35 +00003957 QualifierUnion.push_back(
3958 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3959 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3960 continue;
3961 }
Mike Stump1eb44332009-09-09 15:08:12 +00003962
Douglas Gregor20b3e992009-08-24 17:42:35 +00003963 const MemberPointerType *MemPtr1, *MemPtr2;
3964 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3965 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3966 Composite1 = MemPtr1->getPointeeType();
3967 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003968
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003969 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003970 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003971 if (NonStandardCompositeType &&
3972 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3973 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003974
Douglas Gregor20b3e992009-08-24 17:42:35 +00003975 QualifierUnion.push_back(
3976 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3977 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
3978 MemPtr2->getClass()));
3979 continue;
3980 }
Mike Stump1eb44332009-09-09 15:08:12 +00003981
Douglas Gregor20b3e992009-08-24 17:42:35 +00003982 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00003983
Douglas Gregor20b3e992009-08-24 17:42:35 +00003984 // Cannot unwrap any more types.
3985 break;
3986 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00003987
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003988 if (NeedConstBefore && NonStandardCompositeType) {
3989 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003990 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003991 // requirements of C++ [conv.qual]p4 bullet 3.
3992 for (unsigned I = 0; I != NeedConstBefore; ++I) {
3993 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
3994 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
3995 *NonStandardCompositeType = true;
3996 }
3997 }
3998 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003999
Douglas Gregor20b3e992009-08-24 17:42:35 +00004000 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00004001 ContainingClassVector::reverse_iterator MOC
4002 = MemberOfClass.rbegin();
4003 for (QualifierVector::reverse_iterator
4004 I = QualifierUnion.rbegin(),
4005 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00004006 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00004007 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00004008 if (MOC->first && MOC->second) {
4009 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00004010 Composite1 = Context.getMemberPointerType(
4011 Context.getQualifiedType(Composite1, Quals),
4012 MOC->first);
4013 Composite2 = Context.getMemberPointerType(
4014 Context.getQualifiedType(Composite2, Quals),
4015 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00004016 } else {
4017 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00004018 Composite1
4019 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
4020 Composite2
4021 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00004022 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004023 }
4024
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004025 // Try to convert to the first composite pointer type.
4026 InitializedEntity Entity1
4027 = InitializedEntity::InitializeTemporary(Composite1);
4028 InitializationKind Kind
4029 = InitializationKind::CreateCopy(Loc, SourceLocation());
4030 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
4031 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00004032
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004033 if (E1ToC1 && E2ToC1) {
4034 // Conversion to Composite1 is viable.
4035 if (!Context.hasSameType(Composite1, Composite2)) {
4036 // Composite2 is a different type from Composite1. Check whether
4037 // Composite2 is also viable.
4038 InitializedEntity Entity2
4039 = InitializedEntity::InitializeTemporary(Composite2);
4040 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4041 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4042 if (E1ToC2 && E2ToC2) {
4043 // Both Composite1 and Composite2 are viable and are different;
4044 // this is an ambiguity.
4045 return QualType();
4046 }
4047 }
4048
4049 // Convert E1 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00004050 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00004051 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004052 if (E1Result.isInvalid())
4053 return QualType();
4054 E1 = E1Result.takeAs<Expr>();
4055
4056 // Convert E2 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00004057 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00004058 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004059 if (E2Result.isInvalid())
4060 return QualType();
4061 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004062
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004063 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004064 }
4065
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004066 // Check whether Composite2 is viable.
4067 InitializedEntity Entity2
4068 = InitializedEntity::InitializeTemporary(Composite2);
4069 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4070 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4071 if (!E1ToC2 || !E2ToC2)
4072 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004073
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004074 // Convert E1 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00004075 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00004076 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004077 if (E1Result.isInvalid())
4078 return QualType();
4079 E1 = E1Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004080
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004081 // Convert E2 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00004082 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00004083 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004084 if (E2Result.isInvalid())
4085 return QualType();
4086 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004087
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004088 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004089}
Anders Carlsson165a0a02009-05-17 18:41:29 +00004090
John McCall60d7b3a2010-08-24 06:29:42 +00004091ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor19cc1c72010-11-01 21:10:29 +00004092 if (!E)
4093 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004094
John McCallf85e1932011-06-15 23:02:42 +00004095 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
4096
4097 // If the result is a glvalue, we shouldn't bind it.
4098 if (!E->isRValue())
Anders Carlsson089c2602009-08-15 23:41:35 +00004099 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004100
John McCallf85e1932011-06-15 23:02:42 +00004101 // In ARC, calls that return a retainable type can return retained,
4102 // in which case we have to insert a consuming cast.
4103 if (getLangOptions().ObjCAutoRefCount &&
4104 E->getType()->isObjCRetainableType()) {
4105
4106 bool ReturnsRetained;
4107
4108 // For actual calls, we compute this by examining the type of the
4109 // called value.
4110 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
4111 Expr *Callee = Call->getCallee()->IgnoreParens();
4112 QualType T = Callee->getType();
4113
4114 if (T == Context.BoundMemberTy) {
4115 // Handle pointer-to-members.
4116 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
4117 T = BinOp->getRHS()->getType();
4118 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
4119 T = Mem->getMemberDecl()->getType();
4120 }
4121
4122 if (const PointerType *Ptr = T->getAs<PointerType>())
4123 T = Ptr->getPointeeType();
4124 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
4125 T = Ptr->getPointeeType();
4126 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
4127 T = MemPtr->getPointeeType();
4128
4129 const FunctionType *FTy = T->getAs<FunctionType>();
4130 assert(FTy && "call to value not of function type?");
4131 ReturnsRetained = FTy->getExtInfo().getProducesResult();
4132
4133 // ActOnStmtExpr arranges things so that StmtExprs of retainable
4134 // type always produce a +1 object.
4135 } else if (isa<StmtExpr>(E)) {
4136 ReturnsRetained = true;
4137
4138 // For message sends and property references, we try to find an
4139 // actual method. FIXME: we should infer retention by selector in
4140 // cases where we don't have an actual method.
4141 } else {
John McCallfc4b1912011-08-03 07:02:44 +00004142 ObjCMethodDecl *D = 0;
John McCallf85e1932011-06-15 23:02:42 +00004143 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
4144 D = Send->getMethodDecl();
John McCallf85e1932011-06-15 23:02:42 +00004145 }
4146
4147 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCallfc4b1912011-08-03 07:02:44 +00004148
4149 // Don't do reclaims on performSelector calls; despite their
4150 // return type, the invoked method doesn't necessarily actually
4151 // return an object.
4152 if (!ReturnsRetained &&
4153 D && D->getMethodFamily() == OMF_performSelector)
4154 return Owned(E);
John McCallf85e1932011-06-15 23:02:42 +00004155 }
4156
John McCall567c5862011-11-14 19:53:16 +00004157 // Don't reclaim an object of Class type.
4158 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
4159 return Owned(E);
4160
John McCall7e5e5f42011-07-07 06:58:02 +00004161 ExprNeedsCleanups = true;
4162
John McCall33e56f32011-09-10 06:18:15 +00004163 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
4164 : CK_ARCReclaimReturnedObject);
John McCall7e5e5f42011-07-07 06:58:02 +00004165 return Owned(ImplicitCastExpr::Create(Context, E->getType(), ck, E, 0,
4166 VK_RValue));
John McCallf85e1932011-06-15 23:02:42 +00004167 }
4168
4169 if (!getLangOptions().CPlusPlus)
4170 return Owned(E);
Douglas Gregor51326552009-12-24 18:51:59 +00004171
Peter Collingbournebceb7552011-11-27 22:09:28 +00004172 QualType ET = Context.getBaseElementType(E->getType());
4173 const RecordType *RT = ET->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00004174 if (!RT)
4175 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004176
John McCall86ff3082010-02-04 22:26:26 +00004177 // That should be enough to guarantee that this type is complete.
4178 // If it has a trivial destructor, we can avoid the extra copy.
Jeffrey Yasskinb7ee2e52011-01-27 19:17:54 +00004179 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall507384f2010-08-12 02:40:37 +00004180 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall86ff3082010-02-04 22:26:26 +00004181 return Owned(E);
4182
John McCallf85e1932011-06-15 23:02:42 +00004183 CXXDestructorDecl *Destructor = LookupDestructor(RD);
4184
4185 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
4186 if (Destructor) {
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00004187 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00004188 CheckDestructorAccess(E->getExprLoc(), Destructor,
4189 PDiag(diag::err_access_dtor_temp)
4190 << E->getType());
John McCallf85e1932011-06-15 23:02:42 +00004191
John McCall80ee6e82011-11-10 05:35:25 +00004192 // We need a cleanup, but we don't need to remember the temporary.
John McCallf85e1932011-06-15 23:02:42 +00004193 ExprNeedsCleanups = true;
John McCallc91cc662010-04-07 00:41:46 +00004194 }
Anders Carlssondef11992009-05-30 20:36:53 +00004195 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
4196}
4197
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004198ExprResult
John McCall4765fa02010-12-06 08:20:24 +00004199Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregor90f93822009-12-22 22:17:25 +00004200 if (SubExpr.isInvalid())
4201 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004202
John McCall4765fa02010-12-06 08:20:24 +00004203 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregor90f93822009-12-22 22:17:25 +00004204}
4205
John McCall80ee6e82011-11-10 05:35:25 +00004206Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
4207 assert(SubExpr && "sub expression can't be null!");
4208
4209 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
4210 assert(ExprCleanupObjects.size() >= FirstCleanup);
4211 assert(ExprNeedsCleanups || ExprCleanupObjects.size() == FirstCleanup);
4212 if (!ExprNeedsCleanups)
4213 return SubExpr;
4214
4215 ArrayRef<ExprWithCleanups::CleanupObject> Cleanups
4216 = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
4217 ExprCleanupObjects.size() - FirstCleanup);
4218
4219 Expr *E = ExprWithCleanups::Create(Context, SubExpr, Cleanups);
4220 DiscardCleanupsInEvaluationContext();
4221
4222 return E;
4223}
4224
John McCall4765fa02010-12-06 08:20:24 +00004225Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004226 assert(SubStmt && "sub statement can't be null!");
4227
John McCallf85e1932011-06-15 23:02:42 +00004228 if (!ExprNeedsCleanups)
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004229 return SubStmt;
4230
4231 // FIXME: In order to attach the temporaries, wrap the statement into
4232 // a StmtExpr; currently this is only used for asm statements.
4233 // This is hacky, either create a new CXXStmtWithTemporaries statement or
4234 // a new AsmStmtWithTemporaries.
4235 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
4236 SourceLocation(),
4237 SourceLocation());
4238 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
4239 SourceLocation());
John McCall4765fa02010-12-06 08:20:24 +00004240 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004241}
4242
John McCall60d7b3a2010-08-24 06:29:42 +00004243ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004244Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallb3d87482010-08-24 05:47:05 +00004245 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00004246 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004247 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004248 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00004249 if (Result.isInvalid()) return ExprError();
4250 Base = Result.get();
Mike Stump1eb44332009-09-09 15:08:12 +00004251
John McCall3c3b7f92011-10-25 17:37:35 +00004252 Result = CheckPlaceholderExpr(Base);
4253 if (Result.isInvalid()) return ExprError();
4254 Base = Result.take();
4255
John McCall9ae2f072010-08-23 23:25:46 +00004256 QualType BaseType = Base->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00004257 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004258 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00004259 // If we have a pointer to a dependent type and are using the -> operator,
4260 // the object type is the type that the pointer points to. We might still
4261 // have enough information about that type to do something useful.
4262 if (OpKind == tok::arrow)
4263 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4264 BaseType = Ptr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004265
John McCallb3d87482010-08-24 05:47:05 +00004266 ObjectType = ParsedType::make(BaseType);
Douglas Gregord4dca082010-02-24 18:44:31 +00004267 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00004268 return Owned(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004269 }
Mike Stump1eb44332009-09-09 15:08:12 +00004270
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004271 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00004272 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004273 // returned, with the original second operand.
4274 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00004275 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00004276 llvm::SmallPtrSet<CanQualType,8> CTypes;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004277 SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00004278 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004279
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004280 while (BaseType->isRecordType()) {
John McCall9ae2f072010-08-23 23:25:46 +00004281 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
4282 if (Result.isInvalid())
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004283 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00004284 Base = Result.get();
4285 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonde699e52009-10-13 22:55:59 +00004286 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCall9ae2f072010-08-23 23:25:46 +00004287 BaseType = Base->getType();
John McCallc4e83212009-09-30 01:01:30 +00004288 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00004289 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00004290 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00004291 for (unsigned i = 0; i < Locations.size(); i++)
4292 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00004293 return ExprError();
4294 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004295 }
Mike Stump1eb44332009-09-09 15:08:12 +00004296
Douglas Gregor1d7049a2012-01-12 16:11:24 +00004297 if (BaseType->isPointerType() || BaseType->isObjCObjectPointerType())
Douglas Gregor31658df2009-11-20 19:58:21 +00004298 BaseType = BaseType->getPointeeType();
4299 }
Mike Stump1eb44332009-09-09 15:08:12 +00004300
Douglas Gregor1d7049a2012-01-12 16:11:24 +00004301 // Objective-C properties allow "." access on Objective-C pointer types,
4302 // so adjust the base type to the object type itself.
4303 if (BaseType->isObjCObjectPointerType())
4304 BaseType = BaseType->getPointeeType();
4305
4306 // C++ [basic.lookup.classref]p2:
4307 // [...] If the type of the object expression is of pointer to scalar
4308 // type, the unqualified-id is looked up in the context of the complete
4309 // postfix-expression.
4310 //
4311 // This also indicates that we could be parsing a pseudo-destructor-name.
4312 // Note that Objective-C class and object types can be pseudo-destructor
4313 // expressions or normal member (ivar or property) access expressions.
4314 if (BaseType->isObjCObjectOrInterfaceType()) {
4315 MayBePseudoDestructor = true;
4316 } else if (!BaseType->isRecordType()) {
John McCallb3d87482010-08-24 05:47:05 +00004317 ObjectType = ParsedType();
Douglas Gregord4dca082010-02-24 18:44:31 +00004318 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00004319 return Owned(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00004320 }
Mike Stump1eb44332009-09-09 15:08:12 +00004321
Douglas Gregor03c57052009-11-17 05:17:33 +00004322 // The object type must be complete (or dependent).
4323 if (!BaseType->isDependentType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004324 RequireCompleteType(OpLoc, BaseType,
Douglas Gregor03c57052009-11-17 05:17:33 +00004325 PDiag(diag::err_incomplete_member_access)))
4326 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004327
Douglas Gregorc68afe22009-09-03 21:38:09 +00004328 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004329 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00004330 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00004331 // type C (or of pointer to a class type C), the unqualified-id is looked
4332 // up in the scope of class C. [...]
John McCallb3d87482010-08-24 05:47:05 +00004333 ObjectType = ParsedType::make(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00004334 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004335}
4336
John McCall60d7b3a2010-08-24 06:29:42 +00004337ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCall9ae2f072010-08-23 23:25:46 +00004338 Expr *MemExpr) {
Douglas Gregor77549082010-02-24 21:29:12 +00004339 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCall9ae2f072010-08-23 23:25:46 +00004340 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
4341 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregor849b2432010-03-31 17:46:05 +00004342 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004343
Douglas Gregor77549082010-02-24 21:29:12 +00004344 return ActOnCallExpr(/*Scope*/ 0,
John McCall9ae2f072010-08-23 23:25:46 +00004345 MemExpr,
Douglas Gregor77549082010-02-24 21:29:12 +00004346 /*LPLoc*/ ExpectedLParenLoc,
John McCallf312b1e2010-08-26 23:41:50 +00004347 MultiExprArg(),
Douglas Gregor77549082010-02-24 21:29:12 +00004348 /*RPLoc*/ ExpectedLParenLoc);
4349}
Douglas Gregord4dca082010-02-24 18:44:31 +00004350
David Blaikie91ec7892011-12-16 16:03:09 +00004351static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *Base,
4352 tok::TokenKind& OpKind, SourceLocation OpLoc) {
4353 // C++ [expr.pseudo]p2:
4354 // The left-hand side of the dot operator shall be of scalar type. The
4355 // left-hand side of the arrow operator shall be of pointer to scalar type.
4356 // This scalar type is the object type.
4357 if (OpKind == tok::arrow) {
4358 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4359 ObjectType = Ptr->getPointeeType();
4360 } else if (!Base->isTypeDependent()) {
4361 // The user wrote "p->" when she probably meant "p."; fix it.
4362 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4363 << ObjectType << true
4364 << FixItHint::CreateReplacement(OpLoc, ".");
4365 if (S.isSFINAEContext())
4366 return true;
4367
4368 OpKind = tok::period;
4369 }
4370 }
4371
4372 return false;
4373}
4374
John McCall60d7b3a2010-08-24 06:29:42 +00004375ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00004376 SourceLocation OpLoc,
4377 tok::TokenKind OpKind,
4378 const CXXScopeSpec &SS,
4379 TypeSourceInfo *ScopeTypeInfo,
4380 SourceLocation CCLoc,
4381 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004382 PseudoDestructorTypeStorage Destructed,
John McCall2d9f5fa2011-02-25 05:21:17 +00004383 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004384 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004385
John McCall9ae2f072010-08-23 23:25:46 +00004386 QualType ObjectType = Base->getType();
David Blaikie91ec7892011-12-16 16:03:09 +00004387 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4388 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004389
Douglas Gregorb57fb492010-02-24 22:38:50 +00004390 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
4391 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
John McCall9ae2f072010-08-23 23:25:46 +00004392 << ObjectType << Base->getSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00004393 return ExprError();
4394 }
4395
4396 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004397 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb57fb492010-02-24 22:38:50 +00004398 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004399 if (DestructedTypeInfo) {
4400 QualType DestructedType = DestructedTypeInfo->getType();
4401 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004402 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCallf85e1932011-06-15 23:02:42 +00004403 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
4404 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
4405 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
4406 << ObjectType << DestructedType << Base->getSourceRange()
4407 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004408
John McCallf85e1932011-06-15 23:02:42 +00004409 // Recover by setting the destructed type to the object type.
4410 DestructedType = ObjectType;
4411 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004412 DestructedTypeStart);
John McCallf85e1932011-06-15 23:02:42 +00004413 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4414 } else if (DestructedType.getObjCLifetime() !=
4415 ObjectType.getObjCLifetime()) {
4416
4417 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
4418 // Okay: just pretend that the user provided the correctly-qualified
4419 // type.
4420 } else {
4421 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
4422 << ObjectType << DestructedType << Base->getSourceRange()
4423 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
4424 }
4425
4426 // Recover by setting the destructed type to the object type.
4427 DestructedType = ObjectType;
4428 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
4429 DestructedTypeStart);
4430 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4431 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004432 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00004433 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004434
Douglas Gregorb57fb492010-02-24 22:38:50 +00004435 // C++ [expr.pseudo]p2:
4436 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
4437 // form
4438 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004439 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb57fb492010-02-24 22:38:50 +00004440 //
4441 // shall designate the same scalar type.
4442 if (ScopeTypeInfo) {
4443 QualType ScopeType = ScopeTypeInfo->getType();
4444 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00004445 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004446
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004447 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00004448 diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00004449 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004450 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004451
Douglas Gregorb57fb492010-02-24 22:38:50 +00004452 ScopeType = QualType();
4453 ScopeTypeInfo = 0;
4454 }
4455 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004456
John McCall9ae2f072010-08-23 23:25:46 +00004457 Expr *Result
4458 = new (Context) CXXPseudoDestructorExpr(Context, Base,
4459 OpKind == tok::arrow, OpLoc,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00004460 SS.getWithLocInContext(Context),
John McCall9ae2f072010-08-23 23:25:46 +00004461 ScopeTypeInfo,
4462 CCLoc,
4463 TildeLoc,
4464 Destructed);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004465
Douglas Gregorb57fb492010-02-24 22:38:50 +00004466 if (HasTrailingLParen)
John McCall9ae2f072010-08-23 23:25:46 +00004467 return Owned(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004468
John McCall9ae2f072010-08-23 23:25:46 +00004469 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor77549082010-02-24 21:29:12 +00004470}
4471
John McCall60d7b3a2010-08-24 06:29:42 +00004472ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00004473 SourceLocation OpLoc,
4474 tok::TokenKind OpKind,
4475 CXXScopeSpec &SS,
4476 UnqualifiedId &FirstTypeName,
4477 SourceLocation CCLoc,
4478 SourceLocation TildeLoc,
4479 UnqualifiedId &SecondTypeName,
4480 bool HasTrailingLParen) {
Douglas Gregor77549082010-02-24 21:29:12 +00004481 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4482 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4483 "Invalid first type name in pseudo-destructor");
4484 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4485 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4486 "Invalid second type name in pseudo-destructor");
4487
John McCall9ae2f072010-08-23 23:25:46 +00004488 QualType ObjectType = Base->getType();
David Blaikie91ec7892011-12-16 16:03:09 +00004489 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4490 return ExprError();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004491
4492 // Compute the object type that we should use for name lookup purposes. Only
4493 // record types and dependent types matter.
John McCallb3d87482010-08-24 05:47:05 +00004494 ParsedType ObjectTypePtrForLookup;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004495 if (!SS.isSet()) {
John McCall2d9f5fa2011-02-25 05:21:17 +00004496 if (ObjectType->isRecordType())
4497 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallb3d87482010-08-24 05:47:05 +00004498 else if (ObjectType->isDependentType())
4499 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004500 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004501
4502 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb57fb492010-02-24 22:38:50 +00004503 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00004504 QualType DestructedType;
4505 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004506 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00004507 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004508 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00004509 SecondTypeName.StartLocation,
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +00004510 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004511 if (!T &&
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004512 ((SS.isSet() && !computeDeclContext(SS, false)) ||
4513 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004514 // The name of the type being destroyed is a dependent name, and we
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004515 // couldn't find anything useful in scope. Just store the identifier and
4516 // it's location, and we'll perform (qualified) name lookup again at
4517 // template instantiation time.
4518 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
4519 SecondTypeName.StartLocation);
4520 } else if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004521 Diag(SecondTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00004522 diag::err_pseudo_dtor_destructor_non_type)
4523 << SecondTypeName.Identifier << ObjectType;
4524 if (isSFINAEContext())
4525 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004526
Douglas Gregor77549082010-02-24 21:29:12 +00004527 // Recover by assuming we had the right type all along.
4528 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004529 } else
Douglas Gregor77549082010-02-24 21:29:12 +00004530 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004531 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00004532 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00004533 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004534 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4535 TemplateId->getTemplateArgs(),
4536 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00004537 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4538 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004539 TemplateId->TemplateNameLoc,
4540 TemplateId->LAngleLoc,
4541 TemplateArgsPtr,
4542 TemplateId->RAngleLoc);
4543 if (T.isInvalid() || !T.get()) {
4544 // Recover by assuming we had the right type all along.
4545 DestructedType = ObjectType;
4546 } else
4547 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004548 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004549
4550 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb57fb492010-02-24 22:38:50 +00004551 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004552 if (!DestructedType.isNull()) {
4553 if (!DestructedTypeInfo)
4554 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004555 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004556 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4557 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004558
Douglas Gregorb57fb492010-02-24 22:38:50 +00004559 // Convert the name of the scope type (the type prior to '::') into a type.
4560 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00004561 QualType ScopeType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004562 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor77549082010-02-24 21:29:12 +00004563 FirstTypeName.Identifier) {
4564 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004565 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00004566 FirstTypeName.StartLocation,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00004567 S, &SS, true, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00004568 if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004569 Diag(FirstTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00004570 diag::err_pseudo_dtor_destructor_non_type)
4571 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004572
Douglas Gregorb57fb492010-02-24 22:38:50 +00004573 if (isSFINAEContext())
4574 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004575
Douglas Gregorb57fb492010-02-24 22:38:50 +00004576 // Just drop this type. It's unnecessary anyway.
4577 ScopeType = QualType();
4578 } else
4579 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004580 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00004581 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00004582 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004583 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4584 TemplateId->getTemplateArgs(),
4585 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00004586 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4587 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004588 TemplateId->TemplateNameLoc,
4589 TemplateId->LAngleLoc,
4590 TemplateArgsPtr,
4591 TemplateId->RAngleLoc);
4592 if (T.isInvalid() || !T.get()) {
4593 // Recover by dropping this type.
4594 ScopeType = QualType();
4595 } else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004596 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004597 }
4598 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004599
Douglas Gregorb4a418f2010-02-24 23:02:30 +00004600 if (!ScopeType.isNull() && !ScopeTypeInfo)
4601 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
4602 FirstTypeName.StartLocation);
4603
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004604
John McCall9ae2f072010-08-23 23:25:46 +00004605 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00004606 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004607 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00004608}
4609
David Blaikie91ec7892011-12-16 16:03:09 +00004610ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4611 SourceLocation OpLoc,
4612 tok::TokenKind OpKind,
4613 SourceLocation TildeLoc,
4614 const DeclSpec& DS,
4615 bool HasTrailingLParen) {
4616
4617 QualType ObjectType = Base->getType();
4618 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4619 return ExprError();
4620
4621 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
4622
4623 TypeLocBuilder TLB;
4624 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
4625 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
4626 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
4627 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
4628
4629 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
4630 0, SourceLocation(), TildeLoc,
4631 Destructed, HasTrailingLParen);
4632}
4633
John Wiegley429bb272011-04-08 18:41:53 +00004634ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004635 CXXMethodDecl *Method,
4636 bool HadMultipleCandidates) {
John Wiegley429bb272011-04-08 18:41:53 +00004637 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
4638 FoundDecl, Method);
4639 if (Exp.isInvalid())
Douglas Gregorf2ae5262011-01-20 00:18:04 +00004640 return true;
Eli Friedman772fffa2009-12-09 04:53:56 +00004641
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004642 MemberExpr *ME =
John Wiegley429bb272011-04-08 18:41:53 +00004643 new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
Abramo Bagnara960809e2011-11-16 22:46:05 +00004644 SourceLocation(), Context.BoundMemberTy,
John McCallf89e55a2010-11-18 06:31:45 +00004645 VK_RValue, OK_Ordinary);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004646 if (HadMultipleCandidates)
4647 ME->setHadMultipleCandidates(true);
4648
John McCallf89e55a2010-11-18 06:31:45 +00004649 QualType ResultType = Method->getResultType();
4650 ExprValueKind VK = Expr::getValueKindForType(ResultType);
4651 ResultType = ResultType.getNonLValueExprType(Context);
4652
John Wiegley429bb272011-04-08 18:41:53 +00004653 MarkDeclarationReferenced(Exp.get()->getLocStart(), Method);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004654 CXXMemberCallExpr *CE =
John McCallf89e55a2010-11-18 06:31:45 +00004655 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
John Wiegley429bb272011-04-08 18:41:53 +00004656 Exp.get()->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00004657 return CE;
4658}
4659
Sebastian Redl2e156222010-09-10 20:55:43 +00004660ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4661 SourceLocation RParen) {
Sebastian Redl2e156222010-09-10 20:55:43 +00004662 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
4663 Operand->CanThrow(Context),
4664 KeyLoc, RParen));
4665}
4666
4667ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
4668 Expr *Operand, SourceLocation RParen) {
4669 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl02bc21a2010-09-10 20:55:37 +00004670}
4671
John McCallf6a16482010-12-04 03:47:34 +00004672/// Perform the conversions required for an expression used in a
4673/// context that ignores the result.
John Wiegley429bb272011-04-08 18:41:53 +00004674ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall3c3b7f92011-10-25 17:37:35 +00004675 if (E->hasPlaceholderType()) {
4676 ExprResult result = CheckPlaceholderExpr(E);
4677 if (result.isInvalid()) return Owned(E);
4678 E = result.take();
4679 }
4680
John McCalla878cda2010-12-02 02:07:15 +00004681 // C99 6.3.2.1:
4682 // [Except in specific positions,] an lvalue that does not have
4683 // array type is converted to the value stored in the
4684 // designated object (and is no longer an lvalue).
John McCalle6d134b2011-06-27 21:24:11 +00004685 if (E->isRValue()) {
4686 // In C, function designators (i.e. expressions of function type)
4687 // are r-values, but we still want to do function-to-pointer decay
4688 // on them. This is both technically correct and convenient for
4689 // some clients.
4690 if (!getLangOptions().CPlusPlus && E->getType()->isFunctionType())
4691 return DefaultFunctionArrayConversion(E);
4692
4693 return Owned(E);
4694 }
John McCalla878cda2010-12-02 02:07:15 +00004695
John McCallf6a16482010-12-04 03:47:34 +00004696 // Otherwise, this rule does not apply in C++, at least not for the moment.
John Wiegley429bb272011-04-08 18:41:53 +00004697 if (getLangOptions().CPlusPlus) return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004698
4699 // GCC seems to also exclude expressions of incomplete enum type.
4700 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
4701 if (!T->getDecl()->isComplete()) {
4702 // FIXME: stupid workaround for a codegen bug!
John Wiegley429bb272011-04-08 18:41:53 +00004703 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
4704 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004705 }
4706 }
4707
John Wiegley429bb272011-04-08 18:41:53 +00004708 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
4709 if (Res.isInvalid())
4710 return Owned(E);
4711 E = Res.take();
4712
John McCall85515d62010-12-04 12:29:11 +00004713 if (!E->getType()->isVoidType())
4714 RequireCompleteType(E->getExprLoc(), E->getType(),
4715 diag::err_incomplete_type);
John Wiegley429bb272011-04-08 18:41:53 +00004716 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004717}
4718
John Wiegley429bb272011-04-08 18:41:53 +00004719ExprResult Sema::ActOnFinishFullExpr(Expr *FE) {
4720 ExprResult FullExpr = Owned(FE);
4721
4722 if (!FullExpr.get())
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00004723 return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00004724
John Wiegley429bb272011-04-08 18:41:53 +00004725 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregord0937222010-12-13 22:49:22 +00004726 return ExprError();
4727
Douglas Gregor5e3a8be2011-12-15 00:53:32 +00004728 // Top-level message sends default to 'id' when we're in a debugger.
4729 if (getLangOptions().DebuggerSupport &&
4730 FullExpr.get()->getType() == Context.UnknownAnyTy &&
4731 isa<ObjCMessageExpr>(FullExpr.get())) {
4732 FullExpr = forceUnknownAnyToType(FullExpr.take(), Context.getObjCIdType());
4733 if (FullExpr.isInvalid())
4734 return ExprError();
4735 }
4736
John McCallfb8721c2011-04-10 19:13:55 +00004737 FullExpr = CheckPlaceholderExpr(FullExpr.take());
4738 if (FullExpr.isInvalid())
4739 return ExprError();
Douglas Gregor353ee242011-03-07 02:05:23 +00004740
John Wiegley429bb272011-04-08 18:41:53 +00004741 FullExpr = IgnoredValueConversions(FullExpr.take());
4742 if (FullExpr.isInvalid())
4743 return ExprError();
4744
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004745 CheckImplicitConversions(FullExpr.get(), FullExpr.get()->getExprLoc());
John McCall4765fa02010-12-06 08:20:24 +00004746 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson165a0a02009-05-17 18:41:29 +00004747}
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004748
4749StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
4750 if (!FullStmt) return StmtError();
4751
John McCall4765fa02010-12-06 08:20:24 +00004752 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004753}
Francois Pichet1e862692011-05-06 20:48:22 +00004754
Douglas Gregorba0513d2011-10-25 01:33:02 +00004755Sema::IfExistsResult
4756Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
4757 CXXScopeSpec &SS,
4758 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet1e862692011-05-06 20:48:22 +00004759 DeclarationName TargetName = TargetNameInfo.getName();
4760 if (!TargetName)
Douglas Gregor3896fc52011-10-24 22:31:10 +00004761 return IER_DoesNotExist;
Douglas Gregorba0513d2011-10-25 01:33:02 +00004762
Douglas Gregor3896fc52011-10-24 22:31:10 +00004763 // If the name itself is dependent, then the result is dependent.
4764 if (TargetName.isDependentName())
4765 return IER_Dependent;
Douglas Gregorba0513d2011-10-25 01:33:02 +00004766
Francois Pichet1e862692011-05-06 20:48:22 +00004767 // Do the redeclaration lookup in the current scope.
4768 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
4769 Sema::NotForRedeclaration);
Douglas Gregor3896fc52011-10-24 22:31:10 +00004770 LookupParsedName(R, S, &SS);
Francois Pichet1e862692011-05-06 20:48:22 +00004771 R.suppressDiagnostics();
Douglas Gregor3896fc52011-10-24 22:31:10 +00004772
4773 switch (R.getResultKind()) {
4774 case LookupResult::Found:
4775 case LookupResult::FoundOverloaded:
4776 case LookupResult::FoundUnresolvedValue:
4777 case LookupResult::Ambiguous:
4778 return IER_Exists;
4779
4780 case LookupResult::NotFound:
4781 return IER_DoesNotExist;
4782
4783 case LookupResult::NotFoundInCurrentInstantiation:
4784 return IER_Dependent;
4785 }
4786
Douglas Gregorba0513d2011-10-25 01:33:02 +00004787 return IER_DoesNotExist;
Francois Pichet1e862692011-05-06 20:48:22 +00004788}
Douglas Gregorba0513d2011-10-25 01:33:02 +00004789
Douglas Gregor65019ac2011-10-25 03:44:56 +00004790Sema::IfExistsResult
4791Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4792 bool IsIfExists, CXXScopeSpec &SS,
4793 UnqualifiedId &Name) {
Douglas Gregorba0513d2011-10-25 01:33:02 +00004794 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Douglas Gregor65019ac2011-10-25 03:44:56 +00004795
4796 // Check for unexpanded parameter packs.
4797 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
4798 collectUnexpandedParameterPacks(SS, Unexpanded);
4799 collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
4800 if (!Unexpanded.empty()) {
4801 DiagnoseUnexpandedParameterPacks(KeywordLoc,
4802 IsIfExists? UPPC_IfExists
4803 : UPPC_IfNotExists,
4804 Unexpanded);
4805 return IER_Error;
4806 }
4807
Douglas Gregorba0513d2011-10-25 01:33:02 +00004808 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
4809}
4810
Eli Friedmandc3b7232012-01-04 02:40:39 +00004811//===----------------------------------------------------------------------===//
4812// Lambdas.
4813//===----------------------------------------------------------------------===//
4814
Eli Friedmanec9ea722012-01-05 03:35:19 +00004815void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
4816 Declarator &ParamInfo,
4817 Scope *CurScope) {
4818 DeclContext *DC = CurContext;
Eli Friedman906a7e12012-01-06 03:05:34 +00004819 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
Eli Friedmanec9ea722012-01-05 03:35:19 +00004820 DC = DC->getParent();
Eli Friedmandc3b7232012-01-04 02:40:39 +00004821
Eli Friedmanec9ea722012-01-05 03:35:19 +00004822 // Start constructing the lambda class.
4823 CXXRecordDecl *Class = CXXRecordDecl::Create(Context, TTK_Class, DC,
4824 Intro.Range.getBegin(),
4825 /*IdLoc=*/SourceLocation(),
4826 /*Id=*/0);
4827 Class->startDefinition();
Eli Friedman72899c32012-01-07 04:59:52 +00004828 Class->setLambda(true);
Eli Friedmanec9ea722012-01-05 03:35:19 +00004829 CurContext->addDecl(Class);
Eli Friedmandc3b7232012-01-04 02:40:39 +00004830
Eli Friedmane81d7e92012-01-07 01:08:17 +00004831 QualType ThisCaptureType;
Eli Friedmanb69b42c2012-01-11 02:36:31 +00004832 llvm::DenseMap<VarDecl*, unsigned> CaptureMap;
4833 unsigned CXXThisCaptureIndex = 0;
Eli Friedman72899c32012-01-07 04:59:52 +00004834 llvm::SmallVector<LambdaScopeInfo::Capture, 4> Captures;
Eli Friedmane81d7e92012-01-07 01:08:17 +00004835 for (llvm::SmallVector<LambdaCapture, 4>::const_iterator
4836 C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E; ++C) {
4837 if (C->Kind == LCK_This) {
4838 if (!ThisCaptureType.isNull()) {
4839 Diag(C->Loc, diag::err_capture_more_than_once) << "'this'";
4840 continue;
4841 }
4842
4843 if (Intro.Default == LCD_ByCopy) {
4844 Diag(C->Loc, diag::err_this_capture_with_copy_default);
4845 continue;
4846 }
4847
4848 ThisCaptureType = getCurrentThisType();
Eli Friedmane81d7e92012-01-07 01:08:17 +00004849 if (ThisCaptureType.isNull()) {
4850 Diag(C->Loc, diag::err_invalid_this_use);
4851 continue;
4852 }
Eli Friedman72899c32012-01-07 04:59:52 +00004853 CheckCXXThisCapture(C->Loc);
4854
Eli Friedmanb69b42c2012-01-11 02:36:31 +00004855 // FIXME: Need getCurCapture().
4856 bool isNested = getCurBlock() || getCurLambda();
4857 CapturingScopeInfo::Capture Cap(CapturingScopeInfo::Capture::ThisCapture,
4858 isNested);
4859 Captures.push_back(Cap);
4860 CXXThisCaptureIndex = Captures.size();
Eli Friedmane81d7e92012-01-07 01:08:17 +00004861 continue;
4862 }
4863
4864 assert(C->Id && "missing identifier for capture");
4865
4866 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
4867 Diag(C->Loc, diag::err_reference_capture_with_reference_default);
4868 continue;
4869 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
4870 Diag(C->Loc, diag::err_copy_capture_with_copy_default);
4871 continue;
4872 }
4873
Eli Friedmane81d7e92012-01-07 01:08:17 +00004874 DeclarationNameInfo Name(C->Id, C->Loc);
4875 LookupResult R(*this, Name, LookupOrdinaryName);
4876 CXXScopeSpec ScopeSpec;
4877 LookupParsedName(R, CurScope, &ScopeSpec);
4878 if (R.isAmbiguous())
4879 continue;
4880 if (R.empty())
4881 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, CTC_Unknown))
4882 continue;
4883
4884 VarDecl *Var = R.getAsSingle<VarDecl>();
4885 if (!Var) {
4886 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
4887 continue;
4888 }
4889
Eli Friedmanb69b42c2012-01-11 02:36:31 +00004890 if (CaptureMap.count(Var)) {
4891 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
4892 continue;
4893 }
4894
Eli Friedmane81d7e92012-01-07 01:08:17 +00004895 if (!Var->hasLocalStorage()) {
4896 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
4897 continue;
4898 }
4899
Eli Friedmanb69b42c2012-01-11 02:36:31 +00004900 // FIXME: This is completely wrong for nested captures and variables
4901 // with a non-trivial constructor.
4902 // FIXME: We should refuse to capture __block variables.
4903 Captures.push_back(LambdaScopeInfo::Capture(Var, C->Kind == LCK_ByRef,
4904 /*isNested*/false, 0));
4905 CaptureMap[Var] = Captures.size();
Eli Friedmane81d7e92012-01-07 01:08:17 +00004906 }
4907
Eli Friedmanec9ea722012-01-05 03:35:19 +00004908 // Build the call operator; we don't really have all the relevant information
4909 // at this point, but we need something to attach child declarations to.
Eli Friedman906a7e12012-01-06 03:05:34 +00004910 QualType MethodTy;
Eli Friedmanf88c4002012-01-04 04:41:38 +00004911 TypeSourceInfo *MethodTyInfo;
Eli Friedman906a7e12012-01-06 03:05:34 +00004912 if (ParamInfo.getNumTypeObjects() == 0) {
4913 FunctionProtoType::ExtProtoInfo EPI;
4914 EPI.TypeQuals |= DeclSpec::TQ_const;
4915 MethodTy = Context.getFunctionType(Context.DependentTy,
4916 /*Args=*/0, /*NumArgs=*/0, EPI);
4917 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
4918 } else {
4919 assert(ParamInfo.isFunctionDeclarator() &&
4920 "lambda-declarator is a function");
4921 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
4922 if (!FTI.hasMutableQualifier())
4923 FTI.TypeQuals |= DeclSpec::TQ_const;
4924 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
4925 // FIXME: Can these asserts actually fail?
4926 assert(MethodTyInfo && "no type from lambda-declarator");
4927 MethodTy = MethodTyInfo->getType();
4928 assert(!MethodTy.isNull() && "no type from lambda declarator");
4929 }
Eli Friedmanf88c4002012-01-04 04:41:38 +00004930
Eli Friedmanec9ea722012-01-05 03:35:19 +00004931 DeclarationName MethodName
4932 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
4933 CXXMethodDecl *Method
4934 = CXXMethodDecl::Create(Context,
4935 Class,
4936 ParamInfo.getSourceRange().getEnd(),
4937 DeclarationNameInfo(MethodName,
4938 /*NameLoc=*/SourceLocation()),
Eli Friedman906a7e12012-01-06 03:05:34 +00004939 MethodTy,
Eli Friedmanec9ea722012-01-05 03:35:19 +00004940 MethodTyInfo,
4941 /*isStatic=*/false,
4942 SC_None,
4943 /*isInline=*/true,
4944 /*isConstExpr=*/false,
4945 ParamInfo.getSourceRange().getEnd());
4946 Method->setAccess(AS_public);
4947 Class->addDecl(Method);
4948 Method->setLexicalDeclContext(DC); // FIXME: Is this really correct?
4949
Eli Friedmanec9ea722012-01-05 03:35:19 +00004950 ProcessDeclAttributes(CurScope, Method, ParamInfo);
4951
Eli Friedmanec9ea722012-01-05 03:35:19 +00004952 // Enter a new evaluation context to insulate the block from any
4953 // cleanups from the enclosing full-expression.
4954 PushExpressionEvaluationContext(PotentiallyEvaluated);
4955
4956 PushDeclContext(CurScope, Method);
Eli Friedman906a7e12012-01-06 03:05:34 +00004957
Eli Friedman906a7e12012-01-06 03:05:34 +00004958 // Set the parameters on the decl, if specified.
4959 if (isa<FunctionProtoTypeLoc>(MethodTyInfo->getTypeLoc())) {
4960 FunctionProtoTypeLoc Proto =
4961 cast<FunctionProtoTypeLoc>(MethodTyInfo->getTypeLoc());
4962 Method->setParams(Proto.getParams());
4963 CheckParmsForFunctionDef(Method->param_begin(),
4964 Method->param_end(),
4965 /*CheckParameterNames=*/false);
4966
4967 // Introduce our parameters into the function scope
4968 for (unsigned p = 0, NumParams = Method->getNumParams(); p < NumParams; ++p) {
4969 ParmVarDecl *Param = Method->getParamDecl(p);
4970 Param->setOwningFunction(Method);
4971
4972 // If this has an identifier, add it to the scope stack.
4973 if (Param->getIdentifier()) {
4974 CheckShadow(CurScope, Param);
4975
4976 PushOnScopeChains(Param, CurScope);
4977 }
4978 }
4979 }
4980
Eli Friedman72899c32012-01-07 04:59:52 +00004981 // Introduce the lambda scope.
4982 PushLambdaScope(Class);
4983
4984 LambdaScopeInfo *LSI = getCurLambda();
Eli Friedmanb69b42c2012-01-11 02:36:31 +00004985 LSI->CXXThisCaptureIndex = CXXThisCaptureIndex;
4986 std::swap(LSI->CaptureMap, CaptureMap);
Eli Friedman72899c32012-01-07 04:59:52 +00004987 std::swap(LSI->Captures, Captures);
Eli Friedmanb69b42c2012-01-11 02:36:31 +00004988 LSI->NumExplicitCaptures = Captures.size();
4989 if (Intro.Default == LCD_ByCopy)
4990 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
4991 else if (Intro.Default == LCD_ByRef)
4992 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
Eli Friedman72899c32012-01-07 04:59:52 +00004993
Eli Friedman906a7e12012-01-06 03:05:34 +00004994 const FunctionType *Fn = MethodTy->getAs<FunctionType>();
4995 QualType RetTy = Fn->getResultType();
4996 if (RetTy != Context.DependentTy) {
4997 LSI->ReturnType = RetTy;
Eli Friedmanb69b42c2012-01-11 02:36:31 +00004998 } else {
Eli Friedman906a7e12012-01-06 03:05:34 +00004999 LSI->HasImplicitReturnType = true;
5000 }
5001
5002 // FIXME: Check return type is complete, !isObjCObjectType
5003
Eli Friedmandc3b7232012-01-04 02:40:39 +00005004}
5005
5006void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope) {
5007 // Leave the expression-evaluation context.
5008 DiscardCleanupsInEvaluationContext();
5009 PopExpressionEvaluationContext();
5010
5011 // Leave the context of the lambda.
Eli Friedmanec9ea722012-01-05 03:35:19 +00005012 PopDeclContext();
5013 PopFunctionScopeInfo();
Eli Friedmandc3b7232012-01-04 02:40:39 +00005014}
5015
5016ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc,
5017 Stmt *Body, Scope *CurScope) {
5018 // FIXME: Implement
5019 Diag(StartLoc, diag::err_lambda_unsupported);
5020 ActOnLambdaError(StartLoc, CurScope);
5021 return ExprError();
5022}