blob: d3c4da8816cac41627dc8abe43c161a3fd7e334b [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"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000031#include "llvm/ADT/STLExtras.h"
Chandler Carruth73e0a912011-05-01 07:23:17 +000032#include "llvm/Support/ErrorHandling.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000034using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000035
John McCallb3d87482010-08-24 05:47:05 +000036ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000037 IdentifierInfo &II,
John McCallb3d87482010-08-24 05:47:05 +000038 SourceLocation NameLoc,
39 Scope *S, CXXScopeSpec &SS,
40 ParsedType ObjectTypePtr,
41 bool EnteringContext) {
Douglas Gregor124b8782010-02-16 19:09:40 +000042 // Determine where to perform name lookup.
43
44 // FIXME: This area of the standard is very messy, and the current
45 // wording is rather unclear about which scopes we search for the
46 // destructor name; see core issues 399 and 555. Issue 399 in
47 // particular shows where the current description of destructor name
48 // lookup is completely out of line with existing practice, e.g.,
49 // this appears to be ill-formed:
50 //
51 // namespace N {
52 // template <typename T> struct S {
53 // ~S();
54 // };
55 // }
56 //
57 // void f(N::S<int>* s) {
58 // s->N::S<int>::~S();
59 // }
60 //
Douglas Gregor93649fd2010-02-23 00:15:22 +000061 // See also PR6358 and PR6359.
Sebastian Redlc0fee502010-07-07 23:17:38 +000062 // For this reason, we're currently only doing the C++03 version of this
63 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregor124b8782010-02-16 19:09:40 +000064 QualType SearchType;
65 DeclContext *LookupCtx = 0;
66 bool isDependent = false;
67 bool LookInScope = false;
68
69 // If we have an object type, it's because we are in a
70 // pseudo-destructor-expression or a member access expression, and
71 // we know what type we're looking for.
72 if (ObjectTypePtr)
73 SearchType = GetTypeFromParser(ObjectTypePtr);
74
75 if (SS.isSet()) {
Douglas Gregor93649fd2010-02-23 00:15:22 +000076 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000077
Douglas Gregor93649fd2010-02-23 00:15:22 +000078 bool AlreadySearched = false;
79 bool LookAtPrefix = true;
Sebastian Redlc0fee502010-07-07 23:17:38 +000080 // C++ [basic.lookup.qual]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000081 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redlc0fee502010-07-07 23:17:38 +000082 // the type-names are looked up as types in the scope designated by the
83 // nested-name-specifier. In a qualified-id of the form:
NAKAMURA Takumi00995302011-01-27 07:09:49 +000084 //
85 // ::[opt] nested-name-specifier ~ class-name
Sebastian Redlc0fee502010-07-07 23:17:38 +000086 //
87 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth5e895a82010-02-21 10:19:54 +000088 // a qualified-id of the form:
Douglas Gregor124b8782010-02-16 19:09:40 +000089 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +000090 // ::opt nested-name-specifier class-name :: ~ class-name
Douglas Gregor124b8782010-02-16 19:09:40 +000091 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000092 // the class-names are looked up as types in the scope designated by
Sebastian Redlc0fee502010-07-07 23:17:38 +000093 // the nested-name-specifier.
Douglas Gregor124b8782010-02-16 19:09:40 +000094 //
Sebastian Redlc0fee502010-07-07 23:17:38 +000095 // Here, we check the first case (completely) and determine whether the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000096 // code below is permitted to look at the prefix of the
Sebastian Redlc0fee502010-07-07 23:17:38 +000097 // nested-name-specifier.
98 DeclContext *DC = computeDeclContext(SS, EnteringContext);
99 if (DC && DC->isFileContext()) {
100 AlreadySearched = true;
101 LookupCtx = DC;
102 isDependent = false;
103 } else if (DC && isa<CXXRecordDecl>(DC))
104 LookAtPrefix = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000105
Sebastian Redlc0fee502010-07-07 23:17:38 +0000106 // The second case from the C++03 rules quoted further above.
Douglas Gregor93649fd2010-02-23 00:15:22 +0000107 NestedNameSpecifier *Prefix = 0;
108 if (AlreadySearched) {
109 // Nothing left to do.
110 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
111 CXXScopeSpec PrefixSS;
Douglas Gregor7e384942011-02-25 16:07:42 +0000112 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor93649fd2010-02-23 00:15:22 +0000113 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
114 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000115 } else if (ObjectTypePtr) {
Douglas Gregor124b8782010-02-16 19:09:40 +0000116 LookupCtx = computeDeclContext(SearchType);
117 isDependent = SearchType->isDependentType();
118 } else {
119 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000120 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregor124b8782010-02-16 19:09:40 +0000121 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000122
Douglas Gregoredc90502010-02-25 04:46:04 +0000123 LookInScope = false;
Douglas Gregor124b8782010-02-16 19:09:40 +0000124 } else if (ObjectTypePtr) {
125 // C++ [basic.lookup.classref]p3:
126 // If the unqualified-id is ~type-name, the type-name is looked up
127 // in the context of the entire postfix-expression. If the type T
128 // of the object expression is of a class type C, the type-name is
129 // also looked up in the scope of class C. At least one of the
130 // lookups shall find a name that refers to (possibly
131 // cv-qualified) T.
132 LookupCtx = computeDeclContext(SearchType);
133 isDependent = SearchType->isDependentType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000134 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregor124b8782010-02-16 19:09:40 +0000135 "Caller should have completed object type");
136
137 LookInScope = true;
138 } else {
139 // Perform lookup into the current scope (only).
140 LookInScope = true;
141 }
142
Douglas Gregor7ec18732011-03-04 22:32:08 +0000143 TypeDecl *NonMatchingTypeDecl = 0;
Douglas Gregor124b8782010-02-16 19:09:40 +0000144 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
145 for (unsigned Step = 0; Step != 2; ++Step) {
146 // Look for the name first in the computed lookup context (if we
Douglas Gregor7ec18732011-03-04 22:32:08 +0000147 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregor124b8782010-02-16 19:09:40 +0000148 // we're allowed to look there).
149 Found.clear();
150 if (Step == 0 && LookupCtx)
151 LookupQualifiedName(Found, LookupCtx);
Douglas Gregora2e7dd22010-02-25 01:56:36 +0000152 else if (Step == 1 && LookInScope && S)
Douglas Gregor124b8782010-02-16 19:09:40 +0000153 LookupName(Found, S);
154 else
155 continue;
156
157 // FIXME: Should we be suppressing ambiguities here?
158 if (Found.isAmbiguous())
John McCallb3d87482010-08-24 05:47:05 +0000159 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000160
161 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
162 QualType T = Context.getTypeDeclType(Type);
Douglas Gregor124b8782010-02-16 19:09:40 +0000163
164 if (SearchType.isNull() || SearchType->isDependentType() ||
165 Context.hasSameUnqualifiedType(T, SearchType)) {
166 // We found our type!
167
John McCallb3d87482010-08-24 05:47:05 +0000168 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000169 }
John Wiegley36784e72011-03-08 08:13:22 +0000170
Douglas Gregor7ec18732011-03-04 22:32:08 +0000171 if (!SearchType.isNull())
172 NonMatchingTypeDecl = Type;
Douglas Gregor124b8782010-02-16 19:09:40 +0000173 }
174
175 // If the name that we found is a class template name, and it is
176 // the same name as the template name in the last part of the
177 // nested-name-specifier (if present) or the object type, then
178 // this is the destructor for that class.
179 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000180 // issue 399, for which there isn't even an obvious direction.
Douglas Gregor124b8782010-02-16 19:09:40 +0000181 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
182 QualType MemberOfType;
183 if (SS.isSet()) {
184 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
185 // Figure out the type of the context, if it has one.
John McCall3cb0ebd2010-03-10 03:28:59 +0000186 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
187 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregor124b8782010-02-16 19:09:40 +0000188 }
189 }
190 if (MemberOfType.isNull())
191 MemberOfType = SearchType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000192
Douglas Gregor124b8782010-02-16 19:09:40 +0000193 if (MemberOfType.isNull())
194 continue;
195
196 // We're referring into a class template specialization. If the
197 // class template we found is the same as the template being
198 // specialized, we found what we are looking for.
199 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
200 if (ClassTemplateSpecializationDecl *Spec
201 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
202 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
203 Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000204 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000205 }
206
207 continue;
208 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000209
Douglas Gregor124b8782010-02-16 19:09:40 +0000210 // We're referring to an unresolved class template
211 // specialization. Determine whether we class template we found
212 // is the same as the template being specialized or, if we don't
213 // know which template is being specialized, that it at least
214 // has the same name.
215 if (const TemplateSpecializationType *SpecType
216 = MemberOfType->getAs<TemplateSpecializationType>()) {
217 TemplateName SpecName = SpecType->getTemplateName();
218
219 // The class template we found is the same template being
220 // specialized.
221 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
222 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000223 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000224
225 continue;
226 }
227
228 // The class template we found has the same name as the
229 // (dependent) template name being specialized.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000230 if (DependentTemplateName *DepTemplate
Douglas Gregor124b8782010-02-16 19:09:40 +0000231 = SpecName.getAsDependentTemplateName()) {
232 if (DepTemplate->isIdentifier() &&
233 DepTemplate->getIdentifier() == Template->getIdentifier())
John McCallb3d87482010-08-24 05:47:05 +0000234 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000235
236 continue;
237 }
238 }
239 }
240 }
241
242 if (isDependent) {
243 // We didn't find our type, but that's okay: it's dependent
244 // anyway.
Douglas Gregore29425b2011-02-28 22:42:13 +0000245
246 // FIXME: What if we have no nested-name-specifier?
247 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
248 SS.getWithLocInContext(Context),
249 II, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000250 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000251 }
252
Douglas Gregor7ec18732011-03-04 22:32:08 +0000253 if (NonMatchingTypeDecl) {
254 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
255 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
256 << T << SearchType;
257 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
258 << T;
259 } else if (ObjectTypePtr)
260 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000261 << &II;
Douglas Gregor124b8782010-02-16 19:09:40 +0000262 else
263 Diag(NameLoc, diag::err_destructor_class_name);
264
John McCallb3d87482010-08-24 05:47:05 +0000265 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000266}
267
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000268/// \brief Build a C++ typeid expression with a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000269ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000270 SourceLocation TypeidLoc,
271 TypeSourceInfo *Operand,
272 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000273 // C++ [expr.typeid]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000274 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000275 // that is the operand of typeid are always ignored.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000276 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000277 // type, the class shall be completely-defined.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000278 Qualifiers Quals;
279 QualType T
280 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
281 Quals);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000282 if (T->getAs<RecordType>() &&
283 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
284 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000285
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000286 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
287 Operand,
288 SourceRange(TypeidLoc, RParenLoc)));
289}
290
291/// \brief Build a C++ typeid expression with an expression operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000292ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000293 SourceLocation TypeidLoc,
294 Expr *E,
295 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000296 bool isUnevaluatedOperand = true;
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000297 if (E && !E->isTypeDependent()) {
John McCall6dbba4f2011-10-11 23:14:30 +0000298 if (E->getType()->isPlaceholderType()) {
299 ExprResult result = CheckPlaceholderExpr(E);
300 if (result.isInvalid()) return ExprError();
301 E = result.take();
302 }
303
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000304 QualType T = E->getType();
305 if (const RecordType *RecordT = T->getAs<RecordType>()) {
306 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
307 // C++ [expr.typeid]p3:
308 // [...] If the type of the expression is a class type, the class
309 // shall be completely-defined.
310 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
311 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000312
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000313 // C++ [expr.typeid]p3:
Sebastian Redl906082e2010-07-20 04:20:21 +0000314 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000315 // polymorphic class type [...] [the] expression is an unevaluated
316 // operand. [...]
Sebastian Redl906082e2010-07-20 04:20:21 +0000317 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000318 isUnevaluatedOperand = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000319
320 // We require a vtable to query the type at run time.
321 MarkVTableUsed(TypeidLoc, RecordD);
322 }
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000323 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000324
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000325 // C++ [expr.typeid]p4:
326 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000327 // cv-qualified type, the result of the typeid expression refers to a
328 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000329 // type.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000330 Qualifiers Quals;
331 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
332 if (!Context.hasSameType(T, UnqualT)) {
333 T = UnqualT;
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +0000334 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).take();
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000335 }
336 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000337
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000338 // If this is an unevaluated operand, clear out the set of
339 // declaration references we have been computing and eliminate any
340 // temporaries introduced in its computation.
341 if (isUnevaluatedOperand)
342 ExprEvalContexts.back().Context = Unevaluated;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000343
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000344 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCall9ae2f072010-08-23 23:25:46 +0000345 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000346 SourceRange(TypeidLoc, RParenLoc)));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000347}
348
349/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCall60d7b3a2010-08-24 06:29:42 +0000350ExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000351Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
352 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000353 // Find the std::type_info type.
Sebastian Redlce0682f2011-03-31 19:29:24 +0000354 if (!getStdNamespace())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000355 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000356
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000357 if (!CXXTypeInfoDecl) {
358 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
359 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
360 LookupQualifiedName(R, getStdNamespace());
361 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
362 if (!CXXTypeInfoDecl)
363 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
364 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000365
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000366 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000367
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000368 if (isType) {
369 // The operand is a type; handle it as such.
370 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +0000371 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
372 &TInfo);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000373 if (T.isNull())
374 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000375
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000376 if (!TInfo)
377 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000378
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000379 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000380 }
Mike Stump1eb44332009-09-09 15:08:12 +0000381
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000382 // The operand is an expression.
John McCall9ae2f072010-08-23 23:25:46 +0000383 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000384}
385
Francois Pichet6915c522010-12-27 01:32:00 +0000386/// Retrieve the UuidAttr associated with QT.
387static UuidAttr *GetUuidAttrOfType(QualType QT) {
388 // Optionally remove one level of pointer, reference or array indirection.
John McCallf4c73712011-01-19 06:33:43 +0000389 const Type *Ty = QT.getTypePtr();;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000390 if (QT->isPointerType() || QT->isReferenceType())
391 Ty = QT->getPointeeType().getTypePtr();
392 else if (QT->isArrayType())
393 Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
394
Francois Pichet8db75a22011-05-08 10:02:20 +0000395 // Loop all record redeclaration looking for an uuid attribute.
Francois Pichet6915c522010-12-27 01:32:00 +0000396 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Francois Pichet8db75a22011-05-08 10:02:20 +0000397 for (CXXRecordDecl::redecl_iterator I = RD->redecls_begin(),
398 E = RD->redecls_end(); I != E; ++I) {
399 if (UuidAttr *Uuid = I->getAttr<UuidAttr>())
Francois Pichet6915c522010-12-27 01:32:00 +0000400 return Uuid;
Francois Pichet6915c522010-12-27 01:32:00 +0000401 }
Francois Pichet8db75a22011-05-08 10:02:20 +0000402
Francois Pichet6915c522010-12-27 01:32:00 +0000403 return 0;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000404}
405
Francois Pichet01b7c302010-09-08 12:20:18 +0000406/// \brief Build a Microsoft __uuidof expression with a type operand.
407ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
408 SourceLocation TypeidLoc,
409 TypeSourceInfo *Operand,
410 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000411 if (!Operand->getType()->isDependentType()) {
412 if (!GetUuidAttrOfType(Operand->getType()))
413 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
414 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000415
Francois Pichet01b7c302010-09-08 12:20:18 +0000416 // FIXME: add __uuidof semantic analysis for type operand.
417 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
418 Operand,
419 SourceRange(TypeidLoc, RParenLoc)));
420}
421
422/// \brief Build a Microsoft __uuidof expression with an expression operand.
423ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
424 SourceLocation TypeidLoc,
425 Expr *E,
426 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000427 if (!E->getType()->isDependentType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000428 if (!GetUuidAttrOfType(E->getType()) &&
Francois Pichet6915c522010-12-27 01:32:00 +0000429 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
430 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
431 }
432 // FIXME: add __uuidof semantic analysis for type operand.
Francois Pichet01b7c302010-09-08 12:20:18 +0000433 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
434 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000435 SourceRange(TypeidLoc, RParenLoc)));
Francois Pichet01b7c302010-09-08 12:20:18 +0000436}
437
438/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
439ExprResult
440Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
441 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000442 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet01b7c302010-09-08 12:20:18 +0000443 if (!MSVCGuidDecl) {
444 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
445 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
446 LookupQualifiedName(R, Context.getTranslationUnitDecl());
447 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
448 if (!MSVCGuidDecl)
449 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000450 }
451
Francois Pichet01b7c302010-09-08 12:20:18 +0000452 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000453
Francois Pichet01b7c302010-09-08 12:20:18 +0000454 if (isType) {
455 // The operand is a type; handle it as such.
456 TypeSourceInfo *TInfo = 0;
457 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
458 &TInfo);
459 if (T.isNull())
460 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000461
Francois Pichet01b7c302010-09-08 12:20:18 +0000462 if (!TInfo)
463 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
464
465 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
466 }
467
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000468 // The operand is an expression.
Francois Pichet01b7c302010-09-08 12:20:18 +0000469 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
470}
471
Steve Naroff1b273c42007-09-16 14:56:35 +0000472/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCall60d7b3a2010-08-24 06:29:42 +0000473ExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000474Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000475 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000476 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000477 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
478 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000479}
Chris Lattner50dd2892008-02-26 00:51:44 +0000480
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000481/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCall60d7b3a2010-08-24 06:29:42 +0000482ExprResult
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000483Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
484 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
485}
486
Chris Lattner50dd2892008-02-26 00:51:44 +0000487/// ActOnCXXThrow - Parse throw expressions.
John McCall60d7b3a2010-08-24 06:29:42 +0000488ExprResult
Douglas Gregorbca01b42011-07-06 22:04:06 +0000489Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
490 bool IsThrownVarInScope = false;
491 if (Ex) {
492 // C++0x [class.copymove]p31:
493 // When certain criteria are met, an implementation is allowed to omit the
494 // copy/move construction of a class object [...]
495 //
496 // - in a throw-expression, when the operand is the name of a
497 // non-volatile automatic object (other than a function or catch-
498 // clause parameter) whose scope does not extend beyond the end of the
499 // innermost enclosing try-block (if there is one), the copy/move
500 // operation from the operand to the exception object (15.1) can be
501 // omitted by constructing the automatic object directly into the
502 // exception object
503 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
504 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
505 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
506 for( ; S; S = S->getParent()) {
507 if (S->isDeclScope(Var)) {
508 IsThrownVarInScope = true;
509 break;
510 }
511
512 if (S->getFlags() &
513 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
514 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
515 Scope::TryScope))
516 break;
517 }
518 }
519 }
520 }
521
522 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
523}
524
525ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
526 bool IsThrownVarInScope) {
Anders Carlsson729b8532011-02-23 03:46:46 +0000527 // Don't report an error if 'throw' is used in system headers.
Anders Carlsson15348ae2011-02-28 02:27:16 +0000528 if (!getLangOptions().CXXExceptions &&
Anders Carlsson729b8532011-02-23 03:46:46 +0000529 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb1fba312011-02-19 21:53:09 +0000530 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Douglas Gregorbca01b42011-07-06 22:04:06 +0000531
John Wiegley429bb272011-04-08 18:41:53 +0000532 if (Ex && !Ex->isTypeDependent()) {
Douglas Gregorbca01b42011-07-06 22:04:06 +0000533 ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex, IsThrownVarInScope);
John Wiegley429bb272011-04-08 18:41:53 +0000534 if (ExRes.isInvalid())
535 return ExprError();
536 Ex = ExRes.take();
537 }
Douglas Gregorbca01b42011-07-06 22:04:06 +0000538
539 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc,
540 IsThrownVarInScope));
Sebastian Redl972041f2009-04-27 20:27:31 +0000541}
542
543/// CheckCXXThrowOperand - Validate the operand of a throw.
Douglas Gregorbca01b42011-07-06 22:04:06 +0000544ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
545 bool IsThrownVarInScope) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000546 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000547 // A throw-expression initializes a temporary object, called the exception
548 // object, the type of which is determined by removing any top-level
549 // cv-qualifiers from the static type of the operand of throw and adjusting
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000550 // the type from "array of T" or "function returning T" to "pointer to T"
Douglas Gregor154fe982009-12-23 22:04:40 +0000551 // or "pointer to function returning T", [...]
552 if (E->getType().hasQualifiers())
John Wiegley429bb272011-04-08 18:41:53 +0000553 E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +0000554 E->getValueKind()).take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000555
John Wiegley429bb272011-04-08 18:41:53 +0000556 ExprResult Res = DefaultFunctionArrayConversion(E);
557 if (Res.isInvalid())
558 return ExprError();
559 E = Res.take();
Sebastian Redl972041f2009-04-27 20:27:31 +0000560
561 // If the type of the exception would be an incomplete type or a pointer
562 // to an incomplete type other than (cv) void the program is ill-formed.
563 QualType Ty = E->getType();
John McCallac418162010-04-22 01:10:34 +0000564 bool isPointer = false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000565 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000566 Ty = Ptr->getPointeeType();
John McCallac418162010-04-22 01:10:34 +0000567 isPointer = true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000568 }
569 if (!isPointer || !Ty->isVoidType()) {
570 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000571 PDiag(isPointer ? diag::err_throw_incomplete_ptr
572 : diag::err_throw_incomplete)
573 << E->getSourceRange()))
John Wiegley429bb272011-04-08 18:41:53 +0000574 return ExprError();
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000575
Douglas Gregorbf422f92010-04-15 18:05:39 +0000576 if (RequireNonAbstractType(ThrowLoc, E->getType(),
577 PDiag(diag::err_throw_abstract_type)
578 << E->getSourceRange()))
John Wiegley429bb272011-04-08 18:41:53 +0000579 return ExprError();
Sebastian Redl972041f2009-04-27 20:27:31 +0000580 }
581
John McCallac418162010-04-22 01:10:34 +0000582 // Initialize the exception result. This implicitly weeds out
583 // abstract types or types with inaccessible copy constructors.
Douglas Gregorbca01b42011-07-06 22:04:06 +0000584
585 // C++0x [class.copymove]p31:
586 // When certain criteria are met, an implementation is allowed to omit the
587 // copy/move construction of a class object [...]
588 //
589 // - in a throw-expression, when the operand is the name of a
590 // non-volatile automatic object (other than a function or catch-clause
591 // parameter) whose scope does not extend beyond the end of the
592 // innermost enclosing try-block (if there is one), the copy/move
593 // operation from the operand to the exception object (15.1) can be
594 // omitted by constructing the automatic object directly into the
595 // exception object
596 const VarDecl *NRVOVariable = 0;
597 if (IsThrownVarInScope)
598 NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
599
John McCallac418162010-04-22 01:10:34 +0000600 InitializedEntity Entity =
Douglas Gregor72dfa272011-01-21 22:46:35 +0000601 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
Douglas Gregorbca01b42011-07-06 22:04:06 +0000602 /*NRVO=*/NRVOVariable != 0);
John Wiegley429bb272011-04-08 18:41:53 +0000603 Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
Douglas Gregorbca01b42011-07-06 22:04:06 +0000604 QualType(), E,
605 IsThrownVarInScope);
John McCallac418162010-04-22 01:10:34 +0000606 if (Res.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000607 return ExprError();
608 E = Res.take();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000609
Eli Friedman5ed9b932010-06-03 20:39:03 +0000610 // If the exception has class type, we need additional handling.
611 const RecordType *RecordTy = Ty->getAs<RecordType>();
612 if (!RecordTy)
John Wiegley429bb272011-04-08 18:41:53 +0000613 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000614 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
615
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000616 // If we are throwing a polymorphic class type or pointer thereof,
617 // exception handling will make use of the vtable.
Eli Friedman5ed9b932010-06-03 20:39:03 +0000618 MarkVTableUsed(ThrowLoc, RD);
619
Eli Friedman98efb9f2010-10-12 20:32:36 +0000620 // If a pointer is thrown, the referenced object will not be destroyed.
621 if (isPointer)
John Wiegley429bb272011-04-08 18:41:53 +0000622 return Owned(E);
Eli Friedman98efb9f2010-10-12 20:32:36 +0000623
Eli Friedman5ed9b932010-06-03 20:39:03 +0000624 // If the class has a non-trivial destructor, we must be able to call it.
625 if (RD->hasTrivialDestructor())
John Wiegley429bb272011-04-08 18:41:53 +0000626 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000627
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000628 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +0000629 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman5ed9b932010-06-03 20:39:03 +0000630 if (!Destructor)
John Wiegley429bb272011-04-08 18:41:53 +0000631 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000632
633 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
634 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregored8abf12010-07-08 06:14:04 +0000635 PDiag(diag::err_access_dtor_exception) << Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000636 return Owned(E);
Chris Lattner50dd2892008-02-26 00:51:44 +0000637}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000638
Richard Smith7a614d82011-06-11 17:19:42 +0000639QualType Sema::getAndCaptureCurrentThisType() {
John McCall5808ce42011-02-03 08:15:49 +0000640 // Ignore block scopes: we can capture through them.
641 // Ignore nested enum scopes: we'll diagnose non-constant expressions
642 // where they're invalid, and other uses are legitimate.
643 // Don't ignore nested class scopes: you can't use 'this' in a local class.
John McCall469a1eb2011-02-02 13:00:07 +0000644 DeclContext *DC = CurContext;
Richard Smith7a614d82011-06-11 17:19:42 +0000645 unsigned NumBlocks = 0;
John McCall5808ce42011-02-03 08:15:49 +0000646 while (true) {
Richard Smith7a614d82011-06-11 17:19:42 +0000647 if (isa<BlockDecl>(DC)) {
648 DC = cast<BlockDecl>(DC)->getDeclContext();
649 ++NumBlocks;
650 } else if (isa<EnumDecl>(DC))
651 DC = cast<EnumDecl>(DC)->getDeclContext();
John McCall5808ce42011-02-03 08:15:49 +0000652 else break;
653 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000654
Richard Smith7a614d82011-06-11 17:19:42 +0000655 QualType ThisTy;
656 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
657 if (method && method->isInstance())
658 ThisTy = method->getThisType(Context);
659 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
660 // C++0x [expr.prim]p4:
661 // Otherwise, if a member-declarator declares a non-static data member
662 // of a class X, the expression this is a prvalue of type "pointer to X"
663 // within the optional brace-or-equal-initializer.
664 Scope *S = getScopeForContext(DC);
665 if (!S || S->getFlags() & Scope::ThisScope)
666 ThisTy = Context.getPointerType(Context.getRecordType(RD));
667 }
John McCall469a1eb2011-02-02 13:00:07 +0000668
Richard Smith7a614d82011-06-11 17:19:42 +0000669 // Mark that we're closing on 'this' in all the block scopes we ignored.
670 if (!ThisTy.isNull())
671 for (unsigned idx = FunctionScopes.size() - 1;
672 NumBlocks; --idx, --NumBlocks)
673 cast<BlockScopeInfo>(FunctionScopes[idx])->CapturesCXXThis = true;
John McCall469a1eb2011-02-02 13:00:07 +0000674
Richard Smith7a614d82011-06-11 17:19:42 +0000675 return ThisTy;
John McCall5808ce42011-02-03 08:15:49 +0000676}
677
Richard Smith7a614d82011-06-11 17:19:42 +0000678ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCall5808ce42011-02-03 08:15:49 +0000679 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
680 /// is a non-lvalue expression whose value is the address of the object for
681 /// which the function is called.
682
Richard Smith7a614d82011-06-11 17:19:42 +0000683 QualType ThisTy = getAndCaptureCurrentThisType();
684 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCall5808ce42011-02-03 08:15:49 +0000685
Richard Smith7a614d82011-06-11 17:19:42 +0000686 return Owned(new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000687}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000688
John McCall60d7b3a2010-08-24 06:29:42 +0000689ExprResult
Douglas Gregorab6677e2010-09-08 00:15:04 +0000690Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000691 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000692 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000693 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000694 if (!TypeRep)
695 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000696
John McCall9d125032010-01-15 18:39:57 +0000697 TypeSourceInfo *TInfo;
698 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
699 if (!TInfo)
700 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregorab6677e2010-09-08 00:15:04 +0000701
702 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
703}
704
705/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
706/// Can be interpreted either as function-style casting ("int(x)")
707/// or class type construction ("ClassType(x,y,z)")
708/// or creation of a value-initialized type ("int()").
709ExprResult
710Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
711 SourceLocation LParenLoc,
712 MultiExprArg exprs,
713 SourceLocation RParenLoc) {
714 QualType Ty = TInfo->getType();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000715 unsigned NumExprs = exprs.size();
716 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000717 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000718 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
719
Sebastian Redlf53597f2009-03-15 17:47:39 +0000720 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000721 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000722 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000723
Douglas Gregorab6677e2010-09-08 00:15:04 +0000724 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000725 LParenLoc,
726 Exprs, NumExprs,
727 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000728 }
729
Anders Carlssonbb60a502009-08-27 03:53:50 +0000730 if (Ty->isArrayType())
731 return ExprError(Diag(TyBeginLoc,
732 diag::err_value_init_for_array_type) << FullRange);
733 if (!Ty->isVoidType() &&
734 RequireCompleteType(TyBeginLoc, Ty,
735 PDiag(diag::err_invalid_incomplete_type_use)
736 << FullRange))
737 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000738
Anders Carlssonbb60a502009-08-27 03:53:50 +0000739 if (RequireNonAbstractType(TyBeginLoc, Ty,
740 diag::err_allocation_of_abstract_type))
741 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000742
743
Douglas Gregor506ae412009-01-16 18:33:17 +0000744 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000745 // If the expression list is a single expression, the type conversion
746 // expression is equivalent (in definedness, and if defined in meaning) to the
747 // corresponding cast expression.
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000748 if (NumExprs == 1) {
John McCallb45ae252011-10-05 07:41:44 +0000749 Expr *Arg = Exprs[0];
Anders Carlsson0aebc812009-09-09 21:33:21 +0000750 exprs.release();
John McCallb45ae252011-10-05 07:41:44 +0000751 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000752 }
753
Douglas Gregor19311e72010-09-08 21:40:08 +0000754 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
755 InitializationKind Kind
756 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
757 LParenLoc, RParenLoc)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000758 : InitializationKind::CreateValue(TyBeginLoc,
Douglas Gregor19311e72010-09-08 21:40:08 +0000759 LParenLoc, RParenLoc);
760 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
761 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redlf53597f2009-03-15 17:47:39 +0000762
Douglas Gregor19311e72010-09-08 21:40:08 +0000763 // FIXME: Improve AST representation?
764 return move(Result);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000765}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000766
John McCall6ec278d2011-01-27 09:37:56 +0000767/// doesUsualArrayDeleteWantSize - Answers whether the usual
768/// operator delete[] for the given type has a size_t parameter.
769static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
770 QualType allocType) {
771 const RecordType *record =
772 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
773 if (!record) return false;
774
775 // Try to find an operator delete[] in class scope.
776
777 DeclarationName deleteName =
778 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
779 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
780 S.LookupQualifiedName(ops, record->getDecl());
781
782 // We're just doing this for information.
783 ops.suppressDiagnostics();
784
785 // Very likely: there's no operator delete[].
786 if (ops.empty()) return false;
787
788 // If it's ambiguous, it should be illegal to call operator delete[]
789 // on this thing, so it doesn't matter if we allocate extra space or not.
790 if (ops.isAmbiguous()) return false;
791
792 LookupResult::Filter filter = ops.makeFilter();
793 while (filter.hasNext()) {
794 NamedDecl *del = filter.next()->getUnderlyingDecl();
795
796 // C++0x [basic.stc.dynamic.deallocation]p2:
797 // A template instance is never a usual deallocation function,
798 // regardless of its signature.
799 if (isa<FunctionTemplateDecl>(del)) {
800 filter.erase();
801 continue;
802 }
803
804 // C++0x [basic.stc.dynamic.deallocation]p2:
805 // If class T does not declare [an operator delete[] with one
806 // parameter] but does declare a member deallocation function
807 // named operator delete[] with exactly two parameters, the
808 // second of which has type std::size_t, then this function
809 // is a usual deallocation function.
810 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
811 filter.erase();
812 continue;
813 }
814 }
815 filter.done();
816
817 if (!ops.isSingleResult()) return false;
818
819 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
820 return (del->getNumParams() == 2);
821}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000822
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000823/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
824/// @code new (memory) int[size][4] @endcode
825/// or
826/// @code ::new Foo(23, "hello") @endcode
827/// For the interpretation of this heap of arguments, consult the base version.
John McCall60d7b3a2010-08-24 06:29:42 +0000828ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000829Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000830 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000831 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000832 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000833 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000834 SourceLocation ConstructorRParen) {
Richard Smith34b41d92011-02-20 03:19:35 +0000835 bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
836
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000837 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000838 // If the specified type is an array, unwrap it and save the expression.
839 if (D.getNumTypeObjects() > 0 &&
840 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
841 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smith34b41d92011-02-20 03:19:35 +0000842 if (TypeContainsAuto)
843 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
844 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000845 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000846 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
847 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000848 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000849 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
850 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000851
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000852 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000853 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000854 }
855
Douglas Gregor043cad22009-09-11 00:18:58 +0000856 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000857 if (ArraySize) {
858 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000859 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
860 break;
861
862 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
863 if (Expr *NumElts = (Expr *)Array.NumElts) {
864 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
865 !NumElts->isIntegerConstantExpr(Context)) {
866 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
867 << NumElts->getSourceRange();
868 return ExprError();
869 }
870 }
871 }
872 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000873
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +0000874 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
John McCallbf1a0282010-06-04 23:28:52 +0000875 QualType AllocType = TInfo->getType();
Chris Lattnereaaebc72009-04-25 08:06:05 +0000876 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000877 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000878
Mike Stump1eb44332009-09-09 15:08:12 +0000879 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000880 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000881 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000882 PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000883 TypeIdParens,
Mike Stump1eb44332009-09-09 15:08:12 +0000884 AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000885 TInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000886 ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000887 ConstructorLParen,
888 move(ConstructorArgs),
Richard Smith34b41d92011-02-20 03:19:35 +0000889 ConstructorRParen,
890 TypeContainsAuto);
Douglas Gregor3433cf72009-05-21 00:00:09 +0000891}
892
John McCall60d7b3a2010-08-24 06:29:42 +0000893ExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000894Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
895 SourceLocation PlacementLParen,
896 MultiExprArg PlacementArgs,
897 SourceLocation PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000898 SourceRange TypeIdParens,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000899 QualType AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000900 TypeSourceInfo *AllocTypeInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000901 Expr *ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000902 SourceLocation ConstructorLParen,
903 MultiExprArg ConstructorArgs,
Richard Smith34b41d92011-02-20 03:19:35 +0000904 SourceLocation ConstructorRParen,
905 bool TypeMayContainAuto) {
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000906 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000907
Richard Smith34b41d92011-02-20 03:19:35 +0000908 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
909 if (TypeMayContainAuto && AllocType->getContainedAutoType()) {
910 if (ConstructorArgs.size() == 0)
911 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
912 << AllocType << TypeRange);
913 if (ConstructorArgs.size() != 1) {
914 Expr *FirstBad = ConstructorArgs.get()[1];
915 return ExprError(Diag(FirstBad->getSourceRange().getBegin(),
916 diag::err_auto_new_ctor_multiple_expressions)
917 << AllocType << TypeRange);
918 }
Richard Smitha085da82011-03-17 16:11:59 +0000919 TypeSourceInfo *DeducedType = 0;
920 if (!DeduceAutoType(AllocTypeInfo, ConstructorArgs.get()[0], DeducedType))
Richard Smith34b41d92011-02-20 03:19:35 +0000921 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
922 << AllocType
923 << ConstructorArgs.get()[0]->getType()
924 << TypeRange
925 << ConstructorArgs.get()[0]->getSourceRange());
Richard Smitha085da82011-03-17 16:11:59 +0000926 if (!DeducedType)
927 return ExprError();
Richard Smith34b41d92011-02-20 03:19:35 +0000928
Richard Smitha085da82011-03-17 16:11:59 +0000929 AllocTypeInfo = DeducedType;
930 AllocType = AllocTypeInfo->getType();
Richard Smith34b41d92011-02-20 03:19:35 +0000931 }
932
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000933 // Per C++0x [expr.new]p5, the type being constructed may be a
934 // typedef of an array type.
John McCall9ae2f072010-08-23 23:25:46 +0000935 if (!ArraySize) {
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000936 if (const ConstantArrayType *Array
937 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000938 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
939 Context.getSizeType(),
940 TypeRange.getEnd());
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000941 AllocType = Array->getElementType();
942 }
943 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000944
Douglas Gregora0750762010-10-06 16:00:31 +0000945 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
946 return ExprError();
947
John McCallf85e1932011-06-15 23:02:42 +0000948 // In ARC, infer 'retaining' for the allocated
949 if (getLangOptions().ObjCAutoRefCount &&
950 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
951 AllocType->isObjCLifetimeType()) {
952 AllocType = Context.getLifetimeQualifiedType(AllocType,
953 AllocType->getObjCARCImplicitLifetime());
954 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000955
John McCallf85e1932011-06-15 23:02:42 +0000956 QualType ResultType = Context.getPointerType(AllocType);
957
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000958 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
959 // or enumeration type with a non-negative value."
Sebastian Redl28507842009-02-26 14:39:58 +0000960 if (ArraySize && !ArraySize->isTypeDependent()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000961
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000962 QualType SizeType = ArraySize->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000963
John McCall60d7b3a2010-08-24 06:29:42 +0000964 ExprResult ConvertedSize
John McCall9ae2f072010-08-23 23:25:46 +0000965 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000966 PDiag(diag::err_array_size_not_integral),
967 PDiag(diag::err_array_size_incomplete_type)
968 << ArraySize->getSourceRange(),
969 PDiag(diag::err_array_size_explicit_conversion),
970 PDiag(diag::note_array_size_conversion),
971 PDiag(diag::err_array_size_ambiguous_conversion),
972 PDiag(diag::note_array_size_conversion),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000973 PDiag(getLangOptions().CPlusPlus0x? 0
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000974 : diag::ext_array_size_conversion));
975 if (ConvertedSize.isInvalid())
976 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000977
John McCall9ae2f072010-08-23 23:25:46 +0000978 ArraySize = ConvertedSize.take();
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000979 SizeType = ArraySize->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000980 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000981 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000982
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000983 // Let's see if this is a constant < 0. If so, we reject it out of hand.
984 // We don't care about special rules, so we tell the machinery it's not
985 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000986 if (!ArraySize->isValueDependent()) {
987 llvm::APSInt Value;
988 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
989 if (Value < llvm::APSInt(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000990 llvm::APInt::getNullValue(Value.getBitWidth()),
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000991 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000992 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +0000993 diag::err_typecheck_negative_array_size)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000994 << ArraySize->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000995
Douglas Gregor2767ce22010-08-18 00:39:00 +0000996 if (!AllocType->isDependentType()) {
997 unsigned ActiveSizeBits
998 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
999 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001000 Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +00001001 diag::err_array_too_large)
1002 << Value.toString(10)
1003 << ArraySize->getSourceRange();
1004 return ExprError();
1005 }
1006 }
Douglas Gregor4bd40312010-07-13 15:54:32 +00001007 } else if (TypeIdParens.isValid()) {
1008 // Can't have dynamic array size when the type-id is in parentheses.
1009 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1010 << ArraySize->getSourceRange()
1011 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1012 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001013
Douglas Gregor4bd40312010-07-13 15:54:32 +00001014 TypeIdParens = SourceRange();
Sebastian Redl28507842009-02-26 14:39:58 +00001015 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001016 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001017
John McCallf85e1932011-06-15 23:02:42 +00001018 // ARC: warn about ABI issues.
1019 if (getLangOptions().ObjCAutoRefCount) {
1020 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1021 if (BaseAllocType.hasStrongOrWeakObjCLifetime())
1022 Diag(StartLoc, diag::warn_err_new_delete_object_array)
1023 << 0 << BaseAllocType;
1024 }
1025
John McCall7d166272011-05-15 07:14:44 +00001026 // Note that we do *not* convert the argument in any way. It can
1027 // be signed, larger than size_t, whatever.
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001028 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001029
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001030 FunctionDecl *OperatorNew = 0;
1031 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +00001032 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
1033 unsigned NumPlaceArgs = PlacementArgs.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001034
Sebastian Redl28507842009-02-26 14:39:58 +00001035 if (!AllocType->isDependentType() &&
1036 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
1037 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +00001038 SourceRange(PlacementLParen, PlacementRParen),
1039 UseGlobal, AllocType, ArraySize, PlaceArgs,
1040 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +00001041 return ExprError();
John McCall6ec278d2011-01-27 09:37:56 +00001042
1043 // If this is an array allocation, compute whether the usual array
1044 // deallocation function for the type has a size_t parameter.
1045 bool UsualArrayDeleteWantsSize = false;
1046 if (ArraySize && !AllocType->isDependentType())
1047 UsualArrayDeleteWantsSize
1048 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1049
Chris Lattner5f9e2722011-07-23 10:55:15 +00001050 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001051 if (OperatorNew) {
1052 // Add default arguments, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001053 const FunctionProtoType *Proto =
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001054 OperatorNew->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001055 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00001056 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001057
Anders Carlsson28e94832010-05-03 02:07:56 +00001058 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001059 Proto, 1, PlaceArgs, NumPlaceArgs,
Anders Carlsson28e94832010-05-03 02:07:56 +00001060 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001061 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001062
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001063 NumPlaceArgs = AllPlaceArgs.size();
1064 if (NumPlaceArgs > 0)
1065 PlaceArgs = &AllPlaceArgs[0];
1066 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001067
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001068 bool Init = ConstructorLParen.isValid();
1069 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001070 CXXConstructorDecl *Constructor = 0;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001071 bool HadMultipleCandidates = false;
Sebastian Redlf53597f2009-03-15 17:47:39 +00001072 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
1073 unsigned NumConsArgs = ConstructorArgs.size();
John McCallca0408f2010-08-23 06:44:23 +00001074 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmana8ce9ec2009-11-08 22:15:39 +00001075
Anders Carlsson48c95012010-05-03 15:45:23 +00001076 // Array 'new' can't have any initializers.
Anders Carlsson55cbd6e2010-05-16 16:24:20 +00001077 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlsson48c95012010-05-03 15:45:23 +00001078 SourceRange InitRange(ConsArgs[0]->getLocStart(),
1079 ConsArgs[NumConsArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001080
Anders Carlsson48c95012010-05-03 15:45:23 +00001081 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1082 return ExprError();
1083 }
1084
Douglas Gregor99a2e602009-12-16 01:38:02 +00001085 if (!AllocType->isDependentType() &&
1086 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
1087 // C++0x [expr.new]p15:
1088 // A new-expression that creates an object of type T initializes that
1089 // object as follows:
1090 InitializationKind Kind
1091 // - If the new-initializer is omitted, the object is default-
1092 // initialized (8.5); if no initialization is performed,
1093 // the object has indeterminate value
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001094 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001095 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor99a2e602009-12-16 01:38:02 +00001096 // initialization rules of 8.5 for direct-initialization.
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001097 : InitializationKind::CreateDirect(TypeRange.getBegin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001098 ConstructorLParen,
Douglas Gregor99a2e602009-12-16 01:38:02 +00001099 ConstructorRParen);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001100
Douglas Gregor99a2e602009-12-16 01:38:02 +00001101 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00001102 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001103 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001104 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor99a2e602009-12-16 01:38:02 +00001105 move(ConstructorArgs));
1106 if (FullInit.isInvalid())
1107 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001108
1109 // FullInit is our initializer; walk through it to determine if it's a
Douglas Gregor99a2e602009-12-16 01:38:02 +00001110 // constructor call, which CXXNewExpr handles directly.
1111 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
1112 if (CXXBindTemporaryExpr *Binder
1113 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
1114 FullInitExpr = Binder->getSubExpr();
1115 if (CXXConstructExpr *Construct
1116 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
1117 Constructor = Construct->getConstructor();
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001118 HadMultipleCandidates = Construct->hadMultipleCandidates();
Douglas Gregor99a2e602009-12-16 01:38:02 +00001119 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
1120 AEnd = Construct->arg_end();
1121 A != AEnd; ++A)
John McCall3fa5cae2010-10-26 07:05:15 +00001122 ConvertedConstructorArgs.push_back(*A);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001123 } else {
1124 // Take the converted initializer.
1125 ConvertedConstructorArgs.push_back(FullInit.release());
1126 }
1127 } else {
1128 // No initialization required.
1129 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001130
Douglas Gregor99a2e602009-12-16 01:38:02 +00001131 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +00001132 NumConsArgs = ConvertedConstructorArgs.size();
1133 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001134 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001135
Douglas Gregor6d908702010-02-26 05:06:18 +00001136 // Mark the new and delete operators as referenced.
1137 if (OperatorNew)
1138 MarkDeclarationReferenced(StartLoc, OperatorNew);
1139 if (OperatorDelete)
1140 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1141
John McCall84ff0fc2011-07-13 20:12:57 +00001142 // C++0x [expr.new]p17:
1143 // If the new expression creates an array of objects of class type,
1144 // access and ambiguity control are done for the destructor.
1145 if (ArraySize && Constructor) {
1146 if (CXXDestructorDecl *dtor = LookupDestructor(Constructor->getParent())) {
1147 MarkDeclarationReferenced(StartLoc, dtor);
1148 CheckDestructorAccess(StartLoc, dtor,
1149 PDiag(diag::err_access_dtor)
1150 << Context.getBaseElementType(AllocType));
1151 }
1152 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001153
Sebastian Redlf53597f2009-03-15 17:47:39 +00001154 PlacementArgs.release();
1155 ConstructorArgs.release();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001156
Ted Kremenekad7fe862010-02-11 22:51:03 +00001157 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregor4bd40312010-07-13 15:54:32 +00001158 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001159 ArraySize, Constructor, Init,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001160 ConsArgs, NumConsArgs,
1161 HadMultipleCandidates,
1162 OperatorDelete,
John McCall6ec278d2011-01-27 09:37:56 +00001163 UsualArrayDeleteWantsSize,
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001164 ResultType, AllocTypeInfo,
1165 StartLoc,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001166 Init ? ConstructorRParen :
Chandler Carruth428edaf2010-10-25 08:47:36 +00001167 TypeRange.getEnd(),
1168 ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001169}
1170
1171/// CheckAllocatedType - Checks that a type is suitable as the allocated type
1172/// in a new-expression.
1173/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +00001174bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00001175 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001176 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1177 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +00001178 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001179 return Diag(Loc, diag::err_bad_new_type)
1180 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001181 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001182 return Diag(Loc, diag::err_bad_new_type)
1183 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001184 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +00001185 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001186 PDiag(diag::err_new_incomplete_type)
1187 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001188 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +00001189 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +00001190 diag::err_allocation_of_abstract_type))
1191 return true;
Douglas Gregora0750762010-10-06 16:00:31 +00001192 else if (AllocType->isVariablyModifiedType())
1193 return Diag(Loc, diag::err_variably_modified_new_type)
1194 << AllocType;
Douglas Gregor5666d362011-04-15 19:46:20 +00001195 else if (unsigned AddressSpace = AllocType.getAddressSpace())
1196 return Diag(Loc, diag::err_address_space_qualified_new)
1197 << AllocType.getUnqualifiedType() << AddressSpace;
John McCallf85e1932011-06-15 23:02:42 +00001198 else if (getLangOptions().ObjCAutoRefCount) {
1199 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
1200 QualType BaseAllocType = Context.getBaseElementType(AT);
1201 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1202 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001203 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001204 << BaseAllocType;
1205 }
1206 }
Douglas Gregor5666d362011-04-15 19:46:20 +00001207
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001208 return false;
1209}
1210
Douglas Gregor6d908702010-02-26 05:06:18 +00001211/// \brief Determine whether the given function is a non-placement
1212/// deallocation function.
1213static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1214 if (FD->isInvalidDecl())
1215 return false;
1216
1217 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1218 return Method->isUsualDeallocationFunction();
1219
1220 return ((FD->getOverloadedOperator() == OO_Delete ||
1221 FD->getOverloadedOperator() == OO_Array_Delete) &&
1222 FD->getNumParams() == 1);
1223}
1224
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001225/// FindAllocationFunctions - Finds the overloads of operator new and delete
1226/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001227bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1228 bool UseGlobal, QualType AllocType,
1229 bool IsArray, Expr **PlaceArgs,
1230 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001231 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +00001232 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001233 // --- Choosing an allocation function ---
1234 // C++ 5.3.4p8 - 14 & 18
1235 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1236 // in the scope of the allocated class.
1237 // 2) If an array size is given, look for operator new[], else look for
1238 // operator new.
1239 // 3) The first argument is always size_t. Append the arguments from the
1240 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001241
Chris Lattner5f9e2722011-07-23 10:55:15 +00001242 SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001243 // We don't care about the actual value of this argument.
1244 // FIXME: Should the Sema create the expression and embed it in the syntax
1245 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00001246 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001247 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssond67c4c32009-08-16 20:29:29 +00001248 Context.getSizeType(),
1249 SourceLocation());
1250 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001251 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1252
Douglas Gregor6d908702010-02-26 05:06:18 +00001253 // C++ [expr.new]p8:
1254 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001255 // function's name is operator new and the deallocation function's
Douglas Gregor6d908702010-02-26 05:06:18 +00001256 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001257 // type, the allocation function's name is operator new[] and the
1258 // deallocation function's name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001259 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1260 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +00001261 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1262 IsArray ? OO_Array_Delete : OO_Delete);
1263
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001264 QualType AllocElemType = Context.getBaseElementType(AllocType);
1265
1266 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +00001267 CXXRecordDecl *Record
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001268 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +00001269 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001270 AllocArgs.size(), Record, /*AllowMissing=*/true,
1271 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001272 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001273 }
1274 if (!OperatorNew) {
1275 // Didn't find a member overload. Look for a global one.
1276 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +00001277 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +00001278 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001279 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1280 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001281 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001282 }
1283
John McCall9c82afc2010-04-20 02:18:25 +00001284 // We don't need an operator delete if we're running under
1285 // -fno-exceptions.
1286 if (!getLangOptions().Exceptions) {
1287 OperatorDelete = 0;
1288 return false;
1289 }
1290
Anders Carlssond9583892009-05-31 20:26:12 +00001291 // FindAllocationOverload can change the passed in arguments, so we need to
1292 // copy them back.
1293 if (NumPlaceArgs > 0)
1294 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001295
Douglas Gregor6d908702010-02-26 05:06:18 +00001296 // C++ [expr.new]p19:
1297 //
1298 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001299 // deallocation function's name is looked up in the global
Douglas Gregor6d908702010-02-26 05:06:18 +00001300 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001301 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6d908702010-02-26 05:06:18 +00001302 // the scope of T. If this lookup fails to find the name, or if
1303 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001304 // deallocation function's name is looked up in the global scope.
Douglas Gregor6d908702010-02-26 05:06:18 +00001305 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001306 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001307 CXXRecordDecl *RD
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001308 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6d908702010-02-26 05:06:18 +00001309 LookupQualifiedName(FoundDelete, RD);
1310 }
John McCall90c8c572010-03-18 08:19:33 +00001311 if (FoundDelete.isAmbiguous())
1312 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +00001313
1314 if (FoundDelete.empty()) {
1315 DeclareGlobalNewDelete();
1316 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1317 }
1318
1319 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +00001320
Chris Lattner5f9e2722011-07-23 10:55:15 +00001321 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCall9aa472c2010-03-19 07:35:19 +00001322
John McCalledeb6c92010-09-14 21:34:24 +00001323 // Whether we're looking for a placement operator delete is dictated
1324 // by whether we selected a placement operator new, not by whether
1325 // we had explicit placement arguments. This matters for things like
1326 // struct A { void *operator new(size_t, int = 0); ... };
1327 // A *a = new A()
1328 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1329
1330 if (isPlacementNew) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001331 // C++ [expr.new]p20:
1332 // A declaration of a placement deallocation function matches the
1333 // declaration of a placement allocation function if it has the
1334 // same number of parameters and, after parameter transformations
1335 // (8.3.5), all parameter types except the first are
1336 // identical. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001337 //
Douglas Gregor6d908702010-02-26 05:06:18 +00001338 // To perform this comparison, we compute the function type that
1339 // the deallocation function should have, and use that type both
1340 // for template argument deduction and for comparison purposes.
John McCalle23cf432010-12-14 08:05:40 +00001341 //
1342 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6d908702010-02-26 05:06:18 +00001343 QualType ExpectedFunctionType;
1344 {
1345 const FunctionProtoType *Proto
1346 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00001347
Chris Lattner5f9e2722011-07-23 10:55:15 +00001348 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001349 ArgTypes.push_back(Context.VoidPtrTy);
Douglas Gregor6d908702010-02-26 05:06:18 +00001350 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1351 ArgTypes.push_back(Proto->getArgType(I));
1352
John McCalle23cf432010-12-14 08:05:40 +00001353 FunctionProtoType::ExtProtoInfo EPI;
1354 EPI.Variadic = Proto->isVariadic();
1355
Douglas Gregor6d908702010-02-26 05:06:18 +00001356 ExpectedFunctionType
1357 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
John McCalle23cf432010-12-14 08:05:40 +00001358 ArgTypes.size(), EPI);
Douglas Gregor6d908702010-02-26 05:06:18 +00001359 }
1360
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001361 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001362 DEnd = FoundDelete.end();
1363 D != DEnd; ++D) {
1364 FunctionDecl *Fn = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001365 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6d908702010-02-26 05:06:18 +00001366 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1367 // Perform template argument deduction to try to match the
1368 // expected function type.
1369 TemplateDeductionInfo Info(Context, StartLoc);
1370 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1371 continue;
1372 } else
1373 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1374
1375 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001376 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001377 }
1378 } else {
1379 // C++ [expr.new]p20:
1380 // [...] Any non-placement deallocation function matches a
1381 // non-placement allocation function. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001382 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001383 DEnd = FoundDelete.end();
1384 D != DEnd; ++D) {
1385 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1386 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001387 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001388 }
1389 }
1390
1391 // C++ [expr.new]p20:
1392 // [...] If the lookup finds a single matching deallocation
1393 // function, that function will be called; otherwise, no
1394 // deallocation function will be called.
1395 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001396 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001397
1398 // C++0x [expr.new]p20:
1399 // If the lookup finds the two-parameter form of a usual
1400 // deallocation function (3.7.4.2) and that function, considered
1401 // as a placement deallocation function, would have been
1402 // selected as a match for the allocation function, the program
1403 // is ill-formed.
1404 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1405 isNonPlacementDeallocationFunction(OperatorDelete)) {
1406 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001407 << SourceRange(PlaceArgs[0]->getLocStart(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001408 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1409 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1410 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001411 } else {
1412 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001413 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001414 }
1415 }
1416
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001417 return false;
1418}
1419
Sebastian Redl7f662392008-12-04 22:20:51 +00001420/// FindAllocationOverload - Find an fitting overload for the allocation
1421/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001422bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1423 DeclarationName Name, Expr** Args,
1424 unsigned NumArgs, DeclContext *Ctx,
Sean Hunt2be7e902011-05-12 22:46:29 +00001425 bool AllowMissing, FunctionDecl *&Operator,
1426 bool Diagnose) {
John McCalla24dc2e2009-11-17 02:14:36 +00001427 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1428 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001429 if (R.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001430 if (AllowMissing || !Diagnose)
Sebastian Redl7f662392008-12-04 22:20:51 +00001431 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001432 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001433 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001434 }
1435
John McCall90c8c572010-03-18 08:19:33 +00001436 if (R.isAmbiguous())
1437 return true;
1438
1439 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001440
John McCall5769d612010-02-08 23:07:23 +00001441 OverloadCandidateSet Candidates(StartLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001442 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001443 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001444 // Even member operator new/delete are implicitly treated as
1445 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001446 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001447
John McCall9aa472c2010-03-19 07:35:19 +00001448 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1449 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001450 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1451 Candidates,
1452 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001453 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001454 }
1455
John McCall9aa472c2010-03-19 07:35:19 +00001456 FunctionDecl *Fn = cast<FunctionDecl>(D);
1457 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001458 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001459 }
1460
1461 // Do the resolution.
1462 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00001463 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001464 case OR_Success: {
1465 // Got one!
1466 FunctionDecl *FnDecl = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00001467 MarkDeclarationReferenced(StartLoc, FnDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001468 // The first argument is size_t, and the first parameter must be size_t,
1469 // too. This is checked on declaration and can be assumed. (It can't be
1470 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001471 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001472 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1473 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001474 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1475 FnDecl->getParamDecl(i));
1476
1477 if (!Diagnose && !CanPerformCopyInitialization(Entity, Owned(Args[i])))
1478 return true;
1479
John McCall60d7b3a2010-08-24 06:29:42 +00001480 ExprResult Result
Sean Hunt2be7e902011-05-12 22:46:29 +00001481 = PerformCopyInitialization(Entity, SourceLocation(), Owned(Args[i]));
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001482 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001483 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001484
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001485 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001486 }
1487 Operator = FnDecl;
Sean Hunt2be7e902011-05-12 22:46:29 +00001488 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl,
1489 Diagnose);
Sebastian Redl7f662392008-12-04 22:20:51 +00001490 return false;
1491 }
1492
1493 case OR_No_Viable_Function:
Chandler Carruth361d3802011-06-08 10:26:03 +00001494 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001495 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1496 << Name << Range;
Chandler Carruth361d3802011-06-08 10:26:03 +00001497 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1498 }
Sebastian Redl7f662392008-12-04 22:20:51 +00001499 return true;
1500
1501 case OR_Ambiguous:
Chandler Carruth361d3802011-06-08 10:26:03 +00001502 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001503 Diag(StartLoc, diag::err_ovl_ambiguous_call)
1504 << Name << Range;
Chandler Carruth361d3802011-06-08 10:26:03 +00001505 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
1506 }
Sebastian Redl7f662392008-12-04 22:20:51 +00001507 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001508
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001509 case OR_Deleted: {
Chandler Carruth361d3802011-06-08 10:26:03 +00001510 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001511 Diag(StartLoc, diag::err_ovl_deleted_call)
1512 << Best->Function->isDeleted()
1513 << Name
1514 << getDeletedOrUnavailableSuffix(Best->Function)
1515 << Range;
Chandler Carruth361d3802011-06-08 10:26:03 +00001516 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1517 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001518 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001519 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001520 }
David Blaikieb219cfc2011-09-23 05:06:16 +00001521 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Sebastian Redl7f662392008-12-04 22:20:51 +00001522}
1523
1524
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001525/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1526/// delete. These are:
1527/// @code
Sebastian Redl8999fe12011-03-14 18:08:30 +00001528/// // C++03:
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001529/// void* operator new(std::size_t) throw(std::bad_alloc);
1530/// void* operator new[](std::size_t) throw(std::bad_alloc);
1531/// void operator delete(void *) throw();
1532/// void operator delete[](void *) throw();
Sebastian Redl8999fe12011-03-14 18:08:30 +00001533/// // C++0x:
1534/// void* operator new(std::size_t);
1535/// void* operator new[](std::size_t);
1536/// void operator delete(void *);
1537/// void operator delete[](void *);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001538/// @endcode
Sebastian Redl8999fe12011-03-14 18:08:30 +00001539/// C++0x operator delete is implicitly noexcept.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001540/// Note that the placement and nothrow forms of new are *not* implicitly
1541/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001542void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001543 if (GlobalNewDeleteDeclared)
1544 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001545
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001546 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001547 // [...] The following allocation and deallocation functions (18.4) are
1548 // implicitly declared in global scope in each translation unit of a
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001549 // program
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001550 //
Sebastian Redl8999fe12011-03-14 18:08:30 +00001551 // C++03:
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001552 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001553 // void* operator new[](std::size_t) throw(std::bad_alloc);
1554 // void operator delete(void*) throw();
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001555 // void operator delete[](void*) throw();
Sebastian Redl8999fe12011-03-14 18:08:30 +00001556 // C++0x:
1557 // void* operator new(std::size_t);
1558 // void* operator new[](std::size_t);
1559 // void operator delete(void*);
1560 // void operator delete[](void*);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001561 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001562 // These implicit declarations introduce only the function names operator
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001563 // new, operator new[], operator delete, operator delete[].
1564 //
1565 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1566 // "std" or "bad_alloc" as necessary to form the exception specification.
1567 // However, we do not make these implicit declarations visible to name
1568 // lookup.
Sebastian Redl8999fe12011-03-14 18:08:30 +00001569 // Note that the C++0x versions of operator delete are deallocation functions,
1570 // and thus are implicitly noexcept.
1571 if (!StdBadAlloc && !getLangOptions().CPlusPlus0x) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001572 // The "std::bad_alloc" class has not yet been declared, so build it
1573 // implicitly.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001574 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1575 getOrCreateStdNamespace(),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001576 SourceLocation(), SourceLocation(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001577 &PP.getIdentifierTable().get("bad_alloc"),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001578 0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001579 getStdBadAlloc()->setImplicit(true);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001580 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001581
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001582 GlobalNewDeleteDeclared = true;
1583
1584 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1585 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001586 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001587
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001588 DeclareGlobalAllocationFunction(
1589 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001590 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001591 DeclareGlobalAllocationFunction(
1592 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001593 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001594 DeclareGlobalAllocationFunction(
1595 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1596 Context.VoidTy, VoidPtr);
1597 DeclareGlobalAllocationFunction(
1598 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1599 Context.VoidTy, VoidPtr);
1600}
1601
1602/// DeclareGlobalAllocationFunction - Declares a single implicit global
1603/// allocation function if it doesn't already exist.
1604void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001605 QualType Return, QualType Argument,
1606 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001607 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1608
1609 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001610 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001611 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001612 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001613 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001614 // Only look at non-template functions, as it is the predefined,
1615 // non-templated allocation function we are trying to declare here.
1616 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1617 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001618 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001619 Func->getParamDecl(0)->getType().getUnqualifiedType());
1620 // FIXME: Do we need to check for default arguments here?
Douglas Gregor7b868622010-08-18 15:06:25 +00001621 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1622 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00001623 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001624 return;
Douglas Gregor7b868622010-08-18 15:06:25 +00001625 }
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001626 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001627 }
1628 }
1629
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001630 QualType BadAllocType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001631 bool HasBadAllocExceptionSpec
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001632 = (Name.getCXXOverloadedOperator() == OO_New ||
1633 Name.getCXXOverloadedOperator() == OO_Array_New);
Sebastian Redl8999fe12011-03-14 18:08:30 +00001634 if (HasBadAllocExceptionSpec && !getLangOptions().CPlusPlus0x) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001635 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001636 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001637 }
John McCalle23cf432010-12-14 08:05:40 +00001638
1639 FunctionProtoType::ExtProtoInfo EPI;
John McCalle23cf432010-12-14 08:05:40 +00001640 if (HasBadAllocExceptionSpec) {
Sebastian Redl8999fe12011-03-14 18:08:30 +00001641 if (!getLangOptions().CPlusPlus0x) {
1642 EPI.ExceptionSpecType = EST_Dynamic;
1643 EPI.NumExceptions = 1;
1644 EPI.Exceptions = &BadAllocType;
1645 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00001646 } else {
Sebastian Redl8999fe12011-03-14 18:08:30 +00001647 EPI.ExceptionSpecType = getLangOptions().CPlusPlus0x ?
1648 EST_BasicNoexcept : EST_DynamicNone;
John McCalle23cf432010-12-14 08:05:40 +00001649 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001650
John McCalle23cf432010-12-14 08:05:40 +00001651 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001652 FunctionDecl *Alloc =
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001653 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
1654 SourceLocation(), Name,
John McCalld931b082010-08-26 03:08:43 +00001655 FnType, /*TInfo=*/0, SC_None,
1656 SC_None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001657 Alloc->setImplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001658
Nuno Lopesfc284482009-12-16 16:59:22 +00001659 if (AddMallocAttr)
Sean Huntcf807c42010-08-18 23:23:40 +00001660 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001661
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001662 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001663 SourceLocation(), 0,
1664 Argument, /*TInfo=*/0,
1665 SC_None, SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00001666 Alloc->setParams(Param);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001667
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001668 // FIXME: Also add this declaration to the IdentifierResolver, but
1669 // make sure it is at the end of the chain to coincide with the
1670 // global scope.
John McCall5f1e0942010-08-24 08:50:51 +00001671 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001672}
1673
Anders Carlsson78f74552009-11-15 18:45:20 +00001674bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1675 DeclarationName Name,
Sean Hunt2be7e902011-05-12 22:46:29 +00001676 FunctionDecl* &Operator, bool Diagnose) {
John McCalla24dc2e2009-11-17 02:14:36 +00001677 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001678 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001679 LookupQualifiedName(Found, RD);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001680
John McCalla24dc2e2009-11-17 02:14:36 +00001681 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001682 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001683
Chandler Carruth23893242010-06-28 00:30:51 +00001684 Found.suppressDiagnostics();
1685
Chris Lattner5f9e2722011-07-23 10:55:15 +00001686 SmallVector<DeclAccessPair,4> Matches;
Anders Carlsson78f74552009-11-15 18:45:20 +00001687 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1688 F != FEnd; ++F) {
Chandler Carruth09556fd2010-08-08 07:04:00 +00001689 NamedDecl *ND = (*F)->getUnderlyingDecl();
1690
1691 // Ignore template operator delete members from the check for a usual
1692 // deallocation function.
1693 if (isa<FunctionTemplateDecl>(ND))
1694 continue;
1695
1696 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall046a7462010-08-04 00:31:26 +00001697 Matches.push_back(F.getPair());
1698 }
1699
1700 // There's exactly one suitable operator; pick it.
1701 if (Matches.size() == 1) {
1702 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
Sean Hunt2be7e902011-05-12 22:46:29 +00001703
1704 if (Operator->isDeleted()) {
1705 if (Diagnose) {
1706 Diag(StartLoc, diag::err_deleted_function_use);
1707 Diag(Operator->getLocation(), diag::note_unavailable_here) << true;
1708 }
1709 return true;
1710 }
1711
John McCall046a7462010-08-04 00:31:26 +00001712 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Sean Hunt2be7e902011-05-12 22:46:29 +00001713 Matches[0], Diagnose);
John McCall046a7462010-08-04 00:31:26 +00001714 return false;
1715
1716 // We found multiple suitable operators; complain about the ambiguity.
1717 } else if (!Matches.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001718 if (Diagnose) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00001719 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1720 << Name << RD;
John McCall046a7462010-08-04 00:31:26 +00001721
Chris Lattner5f9e2722011-07-23 10:55:15 +00001722 for (SmallVectorImpl<DeclAccessPair>::iterator
Sean Huntcb45a0f2011-05-12 22:46:25 +00001723 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1724 Diag((*F)->getUnderlyingDecl()->getLocation(),
1725 diag::note_member_declared_here) << Name;
1726 }
John McCall046a7462010-08-04 00:31:26 +00001727 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001728 }
1729
1730 // We did find operator delete/operator delete[] declarations, but
1731 // none of them were suitable.
1732 if (!Found.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001733 if (Diagnose) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00001734 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1735 << Name << RD;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001736
Sean Huntcb45a0f2011-05-12 22:46:25 +00001737 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1738 F != FEnd; ++F)
1739 Diag((*F)->getUnderlyingDecl()->getLocation(),
1740 diag::note_member_declared_here) << Name;
1741 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001742 return true;
1743 }
1744
1745 // Look for a global declaration.
1746 DeclareGlobalNewDelete();
1747 DeclContext *TUDecl = Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001748
Anders Carlsson78f74552009-11-15 18:45:20 +00001749 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1750 Expr* DeallocArgs[1];
1751 DeallocArgs[0] = &Null;
1752 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
Sean Hunt2be7e902011-05-12 22:46:29 +00001753 DeallocArgs, 1, TUDecl, !Diagnose,
1754 Operator, Diagnose))
Anders Carlsson78f74552009-11-15 18:45:20 +00001755 return true;
1756
1757 assert(Operator && "Did not find a deallocation function!");
1758 return false;
1759}
1760
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001761/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1762/// @code ::delete ptr; @endcode
1763/// or
1764/// @code delete [] ptr; @endcode
John McCall60d7b3a2010-08-24 06:29:42 +00001765ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001766Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley429bb272011-04-08 18:41:53 +00001767 bool ArrayForm, Expr *ExE) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001768 // C++ [expr.delete]p1:
1769 // The operand shall have a pointer type, or a class type having a single
1770 // conversion function to a pointer type. The result has type void.
1771 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001772 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1773
John Wiegley429bb272011-04-08 18:41:53 +00001774 ExprResult Ex = Owned(ExE);
Anders Carlssond67c4c32009-08-16 20:29:29 +00001775 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001776 bool ArrayFormAsWritten = ArrayForm;
John McCall6ec278d2011-01-27 09:37:56 +00001777 bool UsualArrayDeleteWantsSize = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001778
John Wiegley429bb272011-04-08 18:41:53 +00001779 if (!Ex.get()->isTypeDependent()) {
1780 QualType Type = Ex.get()->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001781
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001782 if (const RecordType *Record = Type->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001783 if (RequireCompleteType(StartLoc, Type,
Douglas Gregor254a9422010-07-29 14:44:35 +00001784 PDiag(diag::err_delete_incomplete_class_type)))
1785 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001786
Chris Lattner5f9e2722011-07-23 10:55:15 +00001787 SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
John McCall32daa422010-03-31 01:36:47 +00001788
Fariborz Jahanian53462782009-09-11 21:44:33 +00001789 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001790 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001791 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001792 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001793 NamedDecl *D = I.getDecl();
1794 if (isa<UsingShadowDecl>(D))
1795 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1796
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001797 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001798 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001799 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001800
John McCall32daa422010-03-31 01:36:47 +00001801 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001802
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001803 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1804 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedman13578692010-08-05 02:49:48 +00001805 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001806 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001807 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001808 if (ObjectPtrConversions.size() == 1) {
1809 // We have a single conversion to a pointer-to-object type. Perform
1810 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001811 // TODO: don't redo the conversion calculation.
John Wiegley429bb272011-04-08 18:41:53 +00001812 ExprResult Res =
1813 PerformImplicitConversion(Ex.get(),
John McCall32daa422010-03-31 01:36:47 +00001814 ObjectPtrConversions.front()->getConversionType(),
John Wiegley429bb272011-04-08 18:41:53 +00001815 AA_Converting);
1816 if (Res.isUsable()) {
1817 Ex = move(Res);
1818 Type = Ex.get()->getType();
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001819 }
1820 }
1821 else if (ObjectPtrConversions.size() > 1) {
1822 Diag(StartLoc, diag::err_ambiguous_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001823 << Type << Ex.get()->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001824 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1825 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001826 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001827 }
Sebastian Redl28507842009-02-26 14:39:58 +00001828 }
1829
Sebastian Redlf53597f2009-03-15 17:47:39 +00001830 if (!Type->isPointerType())
1831 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001832 << Type << Ex.get()->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001833
Ted Kremenek6217b802009-07-29 21:53:49 +00001834 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmane52c9142011-07-26 22:25:31 +00001835 QualType PointeeElem = Context.getBaseElementType(Pointee);
1836
1837 if (unsigned AddressSpace = Pointee.getAddressSpace())
1838 return Diag(Ex.get()->getLocStart(),
1839 diag::err_address_space_qualified_delete)
1840 << Pointee.getUnqualifiedType() << AddressSpace;
1841
1842 CXXRecordDecl *PointeeRD = 0;
Douglas Gregor94a61572010-05-24 17:01:56 +00001843 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001844 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregor94a61572010-05-24 17:01:56 +00001845 // effectively bans deletion of "void*". However, most compilers support
1846 // this, so we treat it as a warning unless we're in a SFINAE context.
1847 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001848 << Type << Ex.get()->getSourceRange();
Eli Friedmane52c9142011-07-26 22:25:31 +00001849 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00001850 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001851 << Type << Ex.get()->getSourceRange());
Eli Friedmane52c9142011-07-26 22:25:31 +00001852 } else if (!Pointee->isDependentType()) {
1853 if (!RequireCompleteType(StartLoc, Pointee,
1854 PDiag(diag::warn_delete_incomplete)
1855 << Ex.get()->getSourceRange())) {
1856 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
1857 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
1858 }
1859 }
1860
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001861 // C++ [expr.delete]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001862 // [Note: a pointer to a const type can be the operand of a
1863 // delete-expression; it is not necessary to cast away the constness
1864 // (5.2.11) of the pointer expression before it is used as the operand
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001865 // of the delete-expression. ]
John McCallf85e1932011-06-15 23:02:42 +00001866 if (!Context.hasSameType(Ex.get()->getType(), Context.VoidPtrTy))
1867 Ex = Owned(ImplicitCastExpr::Create(Context, Context.VoidPtrTy, CK_NoOp,
1868 Ex.take(), 0, VK_RValue));
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001869
1870 if (Pointee->isArrayType() && !ArrayForm) {
1871 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley429bb272011-04-08 18:41:53 +00001872 << Type << Ex.get()->getSourceRange()
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001873 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1874 ArrayForm = true;
1875 }
1876
Anders Carlssond67c4c32009-08-16 20:29:29 +00001877 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1878 ArrayForm ? OO_Array_Delete : OO_Delete);
1879
Eli Friedmane52c9142011-07-26 22:25:31 +00001880 if (PointeeRD) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001881 if (!UseGlobal &&
Eli Friedmane52c9142011-07-26 22:25:31 +00001882 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
1883 OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001884 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001885
John McCall6ec278d2011-01-27 09:37:56 +00001886 // If we're allocating an array of records, check whether the
1887 // usual operator delete[] has a size_t parameter.
1888 if (ArrayForm) {
1889 // If the user specifically asked to use the global allocator,
1890 // we'll need to do the lookup into the class.
1891 if (UseGlobal)
1892 UsualArrayDeleteWantsSize =
1893 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
1894
1895 // Otherwise, the usual operator delete[] should be the
1896 // function we just found.
1897 else if (isa<CXXMethodDecl>(OperatorDelete))
1898 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
1899 }
1900
Eli Friedmane52c9142011-07-26 22:25:31 +00001901 if (!PointeeRD->hasTrivialDestructor())
1902 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001903 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001904 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor9b623632010-10-12 23:32:35 +00001905 DiagnoseUseOfDecl(Dtor, StartLoc);
1906 }
Argyrios Kyrtzidis6f0074a2011-05-24 19:53:26 +00001907
1908 // C++ [expr.delete]p3:
1909 // In the first alternative (delete object), if the static type of the
1910 // object to be deleted is different from its dynamic type, the static
1911 // type shall be a base class of the dynamic type of the object to be
1912 // deleted and the static type shall have a virtual destructor or the
1913 // behavior is undefined.
1914 //
1915 // Note: a final class cannot be derived from, no issue there
Eli Friedmanef8c79c2011-07-26 23:27:24 +00001916 if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) {
Eli Friedmane52c9142011-07-26 22:25:31 +00001917 CXXDestructorDecl *dtor = PointeeRD->getDestructor();
Eli Friedmanef8c79c2011-07-26 23:27:24 +00001918 if (dtor && !dtor->isVirtual()) {
1919 if (PointeeRD->isAbstract()) {
1920 // If the class is abstract, we warn by default, because we're
1921 // sure the code has undefined behavior.
1922 Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor)
1923 << PointeeElem;
1924 } else if (!ArrayForm) {
1925 // Otherwise, if this is not an array delete, it's a bit suspect,
1926 // but not necessarily wrong.
1927 Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
1928 }
1929 }
Argyrios Kyrtzidis6f0074a2011-05-24 19:53:26 +00001930 }
John McCallf85e1932011-06-15 23:02:42 +00001931
1932 } else if (getLangOptions().ObjCAutoRefCount &&
1933 PointeeElem->isObjCLifetimeType() &&
1934 (PointeeElem.getObjCLifetime() == Qualifiers::OCL_Strong ||
1935 PointeeElem.getObjCLifetime() == Qualifiers::OCL_Weak) &&
1936 ArrayForm) {
1937 Diag(StartLoc, diag::warn_err_new_delete_object_array)
1938 << 1 << PointeeElem;
Anders Carlssond67c4c32009-08-16 20:29:29 +00001939 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001940
Anders Carlssond67c4c32009-08-16 20:29:29 +00001941 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001942 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001943 DeclareGlobalNewDelete();
1944 DeclContext *TUDecl = Context.getTranslationUnitDecl();
John Wiegley429bb272011-04-08 18:41:53 +00001945 Expr *Arg = Ex.get();
Mike Stump1eb44332009-09-09 15:08:12 +00001946 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
John Wiegley429bb272011-04-08 18:41:53 +00001947 &Arg, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001948 OperatorDelete))
1949 return ExprError();
1950 }
Mike Stump1eb44332009-09-09 15:08:12 +00001951
John McCall9c82afc2010-04-20 02:18:25 +00001952 MarkDeclarationReferenced(StartLoc, OperatorDelete);
John McCall6ec278d2011-01-27 09:37:56 +00001953
Douglas Gregord880f522011-02-01 15:50:11 +00001954 // Check access and ambiguity of operator delete and destructor.
Eli Friedmane52c9142011-07-26 22:25:31 +00001955 if (PointeeRD) {
1956 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
John Wiegley429bb272011-04-08 18:41:53 +00001957 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregord880f522011-02-01 15:50:11 +00001958 PDiag(diag::err_access_dtor) << PointeeElem);
1959 }
1960 }
1961
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001962 }
1963
Sebastian Redlf53597f2009-03-15 17:47:39 +00001964 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
John McCall6ec278d2011-01-27 09:37:56 +00001965 ArrayFormAsWritten,
1966 UsualArrayDeleteWantsSize,
John Wiegley429bb272011-04-08 18:41:53 +00001967 OperatorDelete, Ex.take(), StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001968}
1969
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001970/// \brief Check the use of the given variable as a C++ condition in an if,
1971/// while, do-while, or switch statement.
John McCall60d7b3a2010-08-24 06:29:42 +00001972ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCallf89e55a2010-11-18 06:31:45 +00001973 SourceLocation StmtLoc,
1974 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001975 QualType T = ConditionVar->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001976
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001977 // C++ [stmt.select]p2:
1978 // The declarator shall not specify a function or an array.
1979 if (T->isFunctionType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001980 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001981 diag::err_invalid_use_of_function_type)
1982 << ConditionVar->getSourceRange());
1983 else if (T->isArrayType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001984 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001985 diag::err_invalid_use_of_array_type)
1986 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001987
John Wiegley429bb272011-04-08 18:41:53 +00001988 ExprResult Condition =
1989 Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
Douglas Gregor40d96a62011-02-28 21:54:11 +00001990 ConditionVar,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001991 ConditionVar->getLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00001992 ConditionVar->getType().getNonReferenceType(),
John Wiegley429bb272011-04-08 18:41:53 +00001993 VK_LValue));
1994 if (ConvertToBoolean) {
1995 Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
1996 if (Condition.isInvalid())
1997 return ExprError();
1998 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001999
John Wiegley429bb272011-04-08 18:41:53 +00002000 return move(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002001}
2002
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002003/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
John Wiegley429bb272011-04-08 18:41:53 +00002004ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002005 // C++ 6.4p4:
2006 // The value of a condition that is an initialized declaration in a statement
2007 // other than a switch statement is the value of the declared variable
2008 // implicitly converted to type bool. If that conversion is ill-formed, the
2009 // program is ill-formed.
2010 // The value of a condition that is an expression is the value of the
2011 // expression, implicitly converted to bool.
2012 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002013 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002014}
Douglas Gregor77a52232008-09-12 00:47:35 +00002015
2016/// Helper function to determine whether this is the (deprecated) C++
2017/// conversion from a string literal to a pointer to non-const char or
2018/// non-const wchar_t (for narrow and wide string literals,
2019/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00002020bool
Douglas Gregor77a52232008-09-12 00:47:35 +00002021Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
2022 // Look inside the implicit cast, if it exists.
2023 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
2024 From = Cast->getSubExpr();
2025
2026 // A string literal (2.13.4) that is not a wide string literal can
2027 // be converted to an rvalue of type "pointer to char"; a wide
2028 // string literal can be converted to an rvalue of type "pointer
2029 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00002030 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00002031 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00002032 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00002033 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00002034 // This conversion is considered only when there is an
2035 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregor5cee1192011-07-27 05:40:30 +00002036 if (!ToPtrType->getPointeeType().hasQualifiers()) {
2037 switch (StrLit->getKind()) {
2038 case StringLiteral::UTF8:
2039 case StringLiteral::UTF16:
2040 case StringLiteral::UTF32:
2041 // We don't allow UTF literals to be implicitly converted
2042 break;
2043 case StringLiteral::Ascii:
2044 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
2045 ToPointeeType->getKind() == BuiltinType::Char_S);
2046 case StringLiteral::Wide:
2047 return ToPointeeType->isWideCharType();
2048 }
2049 }
Douglas Gregor77a52232008-09-12 00:47:35 +00002050 }
2051
2052 return false;
2053}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002054
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002055static ExprResult BuildCXXCastArgument(Sema &S,
John McCall2de56d12010-08-25 11:45:40 +00002056 SourceLocation CastLoc,
2057 QualType Ty,
2058 CastKind Kind,
2059 CXXMethodDecl *Method,
John McCallca82a822011-09-21 08:36:56 +00002060 DeclAccessPair FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002061 bool HadMultipleCandidates,
John McCall2de56d12010-08-25 11:45:40 +00002062 Expr *From) {
Douglas Gregorba70ab62010-04-16 22:17:36 +00002063 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002064 default: llvm_unreachable("Unhandled cast kind!");
John McCall2de56d12010-08-25 11:45:40 +00002065 case CK_ConstructorConversion: {
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002066 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
John McCallca0408f2010-08-23 06:44:23 +00002067 ASTOwningVector<Expr*> ConstructorArgs(S);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002068
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002069 if (S.CompleteConstructorCall(Constructor,
John McCallf312b1e2010-08-26 23:41:50 +00002070 MultiExprArg(&From, 1),
Douglas Gregorba70ab62010-04-16 22:17:36 +00002071 CastLoc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00002072 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002073
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002074 S.CheckConstructorAccess(CastLoc, Constructor, Constructor->getAccess(),
2075 S.PDiag(diag::err_access_ctor));
2076
2077 ExprResult Result
2078 = S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2079 move_arg(ConstructorArgs),
2080 HadMultipleCandidates, /*ZeroInit*/ false,
2081 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregorba70ab62010-04-16 22:17:36 +00002082 if (Result.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00002083 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002084
Douglas Gregorba70ab62010-04-16 22:17:36 +00002085 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
2086 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002087
John McCall2de56d12010-08-25 11:45:40 +00002088 case CK_UserDefinedConversion: {
Douglas Gregorba70ab62010-04-16 22:17:36 +00002089 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002090
Douglas Gregorba70ab62010-04-16 22:17:36 +00002091 // Create an implicit call expr that calls it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002092 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method,
2093 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00002094 if (Result.isInvalid())
2095 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002096
John McCallca82a822011-09-21 08:36:56 +00002097 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ 0, FoundDecl);
2098
Douglas Gregorf2ae5262011-01-20 00:18:04 +00002099 return S.MaybeBindToTemporary(Result.get());
Douglas Gregorba70ab62010-04-16 22:17:36 +00002100 }
2101 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002102}
Douglas Gregorba70ab62010-04-16 22:17:36 +00002103
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002104/// PerformImplicitConversion - Perform an implicit conversion of the
2105/// expression From to the type ToType using the pre-computed implicit
John Wiegley429bb272011-04-08 18:41:53 +00002106/// conversion sequence ICS. Returns the converted
Douglas Gregor68647482009-12-16 03:45:30 +00002107/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002108/// used in the error message.
John Wiegley429bb272011-04-08 18:41:53 +00002109ExprResult
2110Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002111 const ImplicitConversionSequence &ICS,
John McCallf85e1932011-06-15 23:02:42 +00002112 AssignmentAction Action,
2113 CheckedConversionKind CCK) {
John McCall1d318332010-01-12 00:44:57 +00002114 switch (ICS.getKind()) {
John Wiegley429bb272011-04-08 18:41:53 +00002115 case ImplicitConversionSequence::StandardConversion: {
2116 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
John McCallf85e1932011-06-15 23:02:42 +00002117 Action, CCK);
John Wiegley429bb272011-04-08 18:41:53 +00002118 if (Res.isInvalid())
2119 return ExprError();
2120 From = Res.take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002121 break;
John Wiegley429bb272011-04-08 18:41:53 +00002122 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002123
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002124 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002125
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00002126 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCalldaa8e4e2010-11-15 09:13:47 +00002127 CastKind CastKind;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002128 QualType BeforeToType;
2129 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCall2de56d12010-08-25 11:45:40 +00002130 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002131
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002132 // If the user-defined conversion is specified by a conversion function,
2133 // the initial standard conversion sequence converts the source type to
2134 // the implicit object parameter of the conversion function.
2135 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCall9ec94452010-12-04 09:57:16 +00002136 } else {
2137 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCall2de56d12010-08-25 11:45:40 +00002138 CastKind = CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002139 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00002140 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002141 // If the user-defined conversion is specified by a constructor, the
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002142 // initial standard conversion sequence converts the source type to the
2143 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00002144 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
2145 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002146 }
Douglas Gregora3998bd2010-12-02 21:47:04 +00002147 // Watch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00002148 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley429bb272011-04-08 18:41:53 +00002149 ExprResult Res =
2150 PerformImplicitConversion(From, BeforeToType,
2151 ICS.UserDefined.Before, AA_Converting,
John McCallf85e1932011-06-15 23:02:42 +00002152 CCK);
John Wiegley429bb272011-04-08 18:41:53 +00002153 if (Res.isInvalid())
2154 return ExprError();
2155 From = Res.take();
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002156 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002157
2158 ExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00002159 = BuildCXXCastArgument(*this,
2160 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00002161 ToType.getNonReferenceType(),
Douglas Gregor83eecbe2011-01-20 01:32:05 +00002162 CastKind, cast<CXXMethodDecl>(FD),
2163 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002164 ICS.UserDefined.HadMultipleCandidates,
John McCall9ae2f072010-08-23 23:25:46 +00002165 From);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002166
2167 if (CastArg.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00002168 return ExprError();
Eli Friedmand8889622009-11-27 04:41:50 +00002169
John Wiegley429bb272011-04-08 18:41:53 +00002170 From = CastArg.take();
Eli Friedmand8889622009-11-27 04:41:50 +00002171
Eli Friedmand8889622009-11-27 04:41:50 +00002172 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
John McCallf85e1932011-06-15 23:02:42 +00002173 AA_Converting, CCK);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00002174 }
John McCall1d318332010-01-12 00:44:57 +00002175
2176 case ImplicitConversionSequence::AmbiguousConversion:
John McCall120d63c2010-08-24 20:38:10 +00002177 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall1d318332010-01-12 00:44:57 +00002178 PDiag(diag::err_typecheck_ambiguous_condition)
2179 << From->getSourceRange());
John Wiegley429bb272011-04-08 18:41:53 +00002180 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002181
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002182 case ImplicitConversionSequence::EllipsisConversion:
David Blaikieb219cfc2011-09-23 05:06:16 +00002183 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002184
2185 case ImplicitConversionSequence::BadConversion:
John Wiegley429bb272011-04-08 18:41:53 +00002186 return ExprError();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002187 }
2188
2189 // Everything went well.
John Wiegley429bb272011-04-08 18:41:53 +00002190 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002191}
2192
2193/// PerformImplicitConversion - Perform an implicit conversion of the
2194/// expression From to the type ToType by following the standard
John Wiegley429bb272011-04-08 18:41:53 +00002195/// conversion sequence SCS. Returns the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00002196/// expression. Flavor is the context in which we're performing this
2197/// conversion, for use in error messages.
John Wiegley429bb272011-04-08 18:41:53 +00002198ExprResult
2199Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00002200 const StandardConversionSequence& SCS,
John McCallf85e1932011-06-15 23:02:42 +00002201 AssignmentAction Action,
2202 CheckedConversionKind CCK) {
2203 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
2204
Mike Stump390b4cc2009-05-16 07:39:55 +00002205 // Overall FIXME: we are recomputing too many types here and doing far too
2206 // much extra work. What this means is that we need to keep track of more
2207 // information that is computed when we try the implicit conversion initially,
2208 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002209 QualType FromType = From->getType();
John McCallf85e1932011-06-15 23:02:42 +00002210
Douglas Gregor225c41e2008-11-03 19:09:14 +00002211 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00002212 // FIXME: When can ToType be a reference type?
2213 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002214 if (SCS.Second == ICK_Derived_To_Base) {
John McCallca0408f2010-08-23 06:44:23 +00002215 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002216 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCallca0408f2010-08-23 06:44:23 +00002217 MultiExprArg(*this, &From, 1),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002218 /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002219 ConstructorArgs))
John Wiegley429bb272011-04-08 18:41:53 +00002220 return ExprError();
2221 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2222 ToType, SCS.CopyConstructor,
2223 move_arg(ConstructorArgs),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002224 /*HadMultipleCandidates*/ false,
John Wiegley429bb272011-04-08 18:41:53 +00002225 /*ZeroInit*/ false,
2226 CXXConstructExpr::CK_Complete,
2227 SourceRange());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002228 }
John Wiegley429bb272011-04-08 18:41:53 +00002229 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2230 ToType, SCS.CopyConstructor,
2231 MultiExprArg(*this, &From, 1),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002232 /*HadMultipleCandidates*/ false,
John Wiegley429bb272011-04-08 18:41:53 +00002233 /*ZeroInit*/ false,
2234 CXXConstructExpr::CK_Complete,
2235 SourceRange());
Douglas Gregor225c41e2008-11-03 19:09:14 +00002236 }
2237
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002238 // Resolve overloaded function references.
2239 if (Context.hasSameType(FromType, Context.OverloadTy)) {
2240 DeclAccessPair Found;
2241 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2242 true, Found);
2243 if (!Fn)
John Wiegley429bb272011-04-08 18:41:53 +00002244 return ExprError();
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002245
2246 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
John Wiegley429bb272011-04-08 18:41:53 +00002247 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002248
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002249 From = FixOverloadedFunctionReference(From, Found, Fn);
2250 FromType = From->getType();
2251 }
2252
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002253 // Perform the first implicit conversion.
2254 switch (SCS.First) {
2255 case ICK_Identity:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002256 // Nothing to do.
2257 break;
2258
John McCallf6a16482010-12-04 03:47:34 +00002259 case ICK_Lvalue_To_Rvalue:
2260 // Should this get its own ICK?
2261 if (From->getObjectKind() == OK_ObjCProperty) {
John Wiegley429bb272011-04-08 18:41:53 +00002262 ExprResult FromRes = ConvertPropertyForRValue(From);
2263 if (FromRes.isInvalid())
2264 return ExprError();
2265 From = FromRes.take();
John McCall241d5582010-12-07 22:54:16 +00002266 if (!From->isGLValue()) break;
John McCallf6a16482010-12-04 03:47:34 +00002267 }
2268
2269 FromType = FromType.getUnqualifiedType();
2270 From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
2271 From, 0, VK_RValue);
2272 break;
2273
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002274 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002275 FromType = Context.getArrayDecayedType(FromType);
John McCallf85e1932011-06-15 23:02:42 +00002276 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
2277 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002278 break;
2279
2280 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002281 FromType = Context.getPointerType(FromType);
John McCallf85e1932011-06-15 23:02:42 +00002282 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
2283 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002284 break;
2285
2286 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002287 llvm_unreachable("Improper first standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002288 }
2289
2290 // Perform the second implicit conversion
2291 switch (SCS.Second) {
2292 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002293 // If both sides are functions (or pointers/references to them), there could
2294 // be incompatible exception declarations.
2295 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002296 return ExprError();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002297 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002298 break;
2299
Douglas Gregor43c79c22009-12-09 00:47:37 +00002300 case ICK_NoReturn_Adjustment:
2301 // If both sides are functions (or pointers/references to them), there could
2302 // be incompatible exception declarations.
2303 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002304 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002305
John McCallf85e1932011-06-15 23:02:42 +00002306 From = ImpCastExprToType(From, ToType, CK_NoOp,
2307 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor43c79c22009-12-09 00:47:37 +00002308 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002309
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002310 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002311 case ICK_Integral_Conversion:
John McCallf85e1932011-06-15 23:02:42 +00002312 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
2313 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002314 break;
2315
2316 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002317 case ICK_Floating_Conversion:
John McCallf85e1932011-06-15 23:02:42 +00002318 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
2319 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002320 break;
2321
2322 case ICK_Complex_Promotion:
John McCalldaa8e4e2010-11-15 09:13:47 +00002323 case ICK_Complex_Conversion: {
2324 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2325 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2326 CastKind CK;
2327 if (FromEl->isRealFloatingType()) {
2328 if (ToEl->isRealFloatingType())
2329 CK = CK_FloatingComplexCast;
2330 else
2331 CK = CK_FloatingComplexToIntegralComplex;
2332 } else if (ToEl->isRealFloatingType()) {
2333 CK = CK_IntegralComplexToFloatingComplex;
2334 } else {
2335 CK = CK_IntegralComplexCast;
2336 }
John McCallf85e1932011-06-15 23:02:42 +00002337 From = ImpCastExprToType(From, ToType, CK,
2338 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002339 break;
John McCalldaa8e4e2010-11-15 09:13:47 +00002340 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00002341
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002342 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00002343 if (ToType->isRealFloatingType())
John McCallf85e1932011-06-15 23:02:42 +00002344 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
2345 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002346 else
John McCallf85e1932011-06-15 23:02:42 +00002347 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
2348 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002349 break;
2350
Douglas Gregorf9201e02009-02-11 23:02:49 +00002351 case ICK_Compatible_Conversion:
John McCallf85e1932011-06-15 23:02:42 +00002352 From = ImpCastExprToType(From, ToType, CK_NoOp,
2353 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002354 break;
2355
John McCallf85e1932011-06-15 23:02:42 +00002356 case ICK_Writeback_Conversion:
Anders Carlsson61faec12009-09-12 04:46:44 +00002357 case ICK_Pointer_Conversion: {
Douglas Gregora3998bd2010-12-02 21:47:04 +00002358 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor45920e82008-12-19 17:40:08 +00002359 // Diagnose incompatible Objective-C conversions
Douglas Gregor8cf0d222011-06-11 04:42:12 +00002360 if (Action == AA_Initializing || Action == AA_Assigning)
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002361 Diag(From->getSourceRange().getBegin(),
2362 diag::ext_typecheck_convert_incompatible_pointer)
2363 << ToType << From->getType() << Action
Anna Zaks67221552011-07-28 19:51:27 +00002364 << From->getSourceRange() << 0;
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002365 else
2366 Diag(From->getSourceRange().getBegin(),
2367 diag::ext_typecheck_convert_incompatible_pointer)
2368 << From->getType() << ToType << Action
Anna Zaks67221552011-07-28 19:51:27 +00002369 << From->getSourceRange() << 0;
John McCallf85e1932011-06-15 23:02:42 +00002370
Douglas Gregor926df6c2011-06-11 01:09:30 +00002371 if (From->getType()->isObjCObjectPointerType() &&
2372 ToType->isObjCObjectPointerType())
2373 EmitRelatedResultTypeNote(From);
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002374 }
2375 else if (getLangOptions().ObjCAutoRefCount &&
2376 !CheckObjCARCUnavailableWeakConversion(ToType,
2377 From->getType())) {
John McCall7f3a6d32011-09-09 06:12:06 +00002378 if (Action == AA_Initializing)
2379 Diag(From->getSourceRange().getBegin(),
2380 diag::err_arc_weak_unavailable_assign);
2381 else
2382 Diag(From->getSourceRange().getBegin(),
2383 diag::err_arc_convesion_of_weak_unavailable)
2384 << (Action == AA_Casting) << From->getType() << ToType
2385 << From->getSourceRange();
2386 }
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002387
John McCalldaa8e4e2010-11-15 09:13:47 +00002388 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002389 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002390 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002391 return ExprError();
John McCalldc05b112011-09-10 01:16:55 +00002392
2393 // Make sure we extend blocks if necessary.
2394 // FIXME: doing this here is really ugly.
2395 if (Kind == CK_BlockPointerToObjCPointerCast) {
2396 ExprResult E = From;
2397 (void) PrepareCastToObjCObjectPointer(E);
2398 From = E.take();
2399 }
2400
John McCallf85e1932011-06-15 23:02:42 +00002401 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2402 .take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002403 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00002404 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002405
Anders Carlsson61faec12009-09-12 04:46:44 +00002406 case ICK_Pointer_Member: {
John McCalldaa8e4e2010-11-15 09:13:47 +00002407 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002408 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002409 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002410 return ExprError();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002411 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002412 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +00002413 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2414 .take();
Anders Carlsson61faec12009-09-12 04:46:44 +00002415 break;
2416 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002417
Abramo Bagnara737d5442011-04-07 09:26:19 +00002418 case ICK_Boolean_Conversion:
John Wiegley429bb272011-04-08 18:41:53 +00002419 From = ImpCastExprToType(From, Context.BoolTy,
John McCallf85e1932011-06-15 23:02:42 +00002420 ScalarTypeToBooleanCastKind(FromType),
2421 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002422 break;
2423
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002424 case ICK_Derived_To_Base: {
John McCallf871d0c2010-08-07 06:22:56 +00002425 CXXCastPath BasePath;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002426 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002427 ToType.getNonReferenceType(),
2428 From->getLocStart(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002429 From->getSourceRange(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002430 &BasePath,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002431 CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002432 return ExprError();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002433
John Wiegley429bb272011-04-08 18:41:53 +00002434 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00002435 CK_DerivedToBase, From->getValueKind(),
John McCallf85e1932011-06-15 23:02:42 +00002436 &BasePath, CCK).take();
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002437 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002438 }
2439
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002440 case ICK_Vector_Conversion:
John McCallf85e1932011-06-15 23:02:42 +00002441 From = ImpCastExprToType(From, ToType, CK_BitCast,
2442 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002443 break;
2444
2445 case ICK_Vector_Splat:
John McCallf85e1932011-06-15 23:02:42 +00002446 From = ImpCastExprToType(From, ToType, CK_VectorSplat,
2447 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002448 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002449
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002450 case ICK_Complex_Real:
John McCalldaa8e4e2010-11-15 09:13:47 +00002451 // Case 1. x -> _Complex y
2452 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2453 QualType ElType = ToComplex->getElementType();
2454 bool isFloatingComplex = ElType->isRealFloatingType();
2455
2456 // x -> y
2457 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2458 // do nothing
2459 } else if (From->getType()->isRealFloatingType()) {
John Wiegley429bb272011-04-08 18:41:53 +00002460 From = ImpCastExprToType(From, ElType,
2461 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002462 } else {
2463 assert(From->getType()->isIntegerType());
John Wiegley429bb272011-04-08 18:41:53 +00002464 From = ImpCastExprToType(From, ElType,
2465 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002466 }
2467 // y -> _Complex y
John Wiegley429bb272011-04-08 18:41:53 +00002468 From = ImpCastExprToType(From, ToType,
John McCalldaa8e4e2010-11-15 09:13:47 +00002469 isFloatingComplex ? CK_FloatingRealToComplex
John Wiegley429bb272011-04-08 18:41:53 +00002470 : CK_IntegralRealToComplex).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002471
2472 // Case 2. _Complex x -> y
2473 } else {
2474 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2475 assert(FromComplex);
2476
2477 QualType ElType = FromComplex->getElementType();
2478 bool isFloatingComplex = ElType->isRealFloatingType();
2479
2480 // _Complex x -> x
John Wiegley429bb272011-04-08 18:41:53 +00002481 From = ImpCastExprToType(From, ElType,
John McCalldaa8e4e2010-11-15 09:13:47 +00002482 isFloatingComplex ? CK_FloatingComplexToReal
John McCallf85e1932011-06-15 23:02:42 +00002483 : CK_IntegralComplexToReal,
2484 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002485
2486 // x -> y
2487 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2488 // do nothing
2489 } else if (ToType->isRealFloatingType()) {
John Wiegley429bb272011-04-08 18:41:53 +00002490 From = ImpCastExprToType(From, ToType,
John McCallf85e1932011-06-15 23:02:42 +00002491 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
2492 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002493 } else {
2494 assert(ToType->isIntegerType());
John Wiegley429bb272011-04-08 18:41:53 +00002495 From = ImpCastExprToType(From, ToType,
John McCallf85e1932011-06-15 23:02:42 +00002496 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
2497 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002498 }
2499 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002500 break;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002501
2502 case ICK_Block_Pointer_Conversion: {
John McCallf85e1932011-06-15 23:02:42 +00002503 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
2504 VK_RValue, /*BasePath=*/0, CCK).take();
2505 break;
2506 }
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002507
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002508 case ICK_TransparentUnionConversion: {
John Wiegley429bb272011-04-08 18:41:53 +00002509 ExprResult FromRes = Owned(From);
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002510 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00002511 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
2512 if (FromRes.isInvalid())
2513 return ExprError();
2514 From = FromRes.take();
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002515 assert ((ConvTy == Sema::Compatible) &&
2516 "Improper transparent union conversion");
2517 (void)ConvTy;
2518 break;
2519 }
2520
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002521 case ICK_Lvalue_To_Rvalue:
2522 case ICK_Array_To_Pointer:
2523 case ICK_Function_To_Pointer:
2524 case ICK_Qualification:
2525 case ICK_Num_Conversion_Kinds:
David Blaikieb219cfc2011-09-23 05:06:16 +00002526 llvm_unreachable("Improper second standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002527 }
2528
2529 switch (SCS.Third) {
2530 case ICK_Identity:
2531 // Nothing to do.
2532 break;
2533
Sebastian Redl906082e2010-07-20 04:20:21 +00002534 case ICK_Qualification: {
2535 // The qualification keeps the category of the inner expression, unless the
2536 // target type isn't a reference.
John McCall5baba9d2010-08-25 10:28:54 +00002537 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00002538 From->getValueKind() : VK_RValue;
John Wiegley429bb272011-04-08 18:41:53 +00002539 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
John McCallf85e1932011-06-15 23:02:42 +00002540 CK_NoOp, VK, /*BasePath=*/0, CCK).take();
Douglas Gregora9bff302010-02-28 18:30:25 +00002541
Douglas Gregor069a6da2011-03-14 16:13:32 +00002542 if (SCS.DeprecatedStringLiteralToCharPtr &&
2543 !getLangOptions().WritableStrings)
Douglas Gregora9bff302010-02-28 18:30:25 +00002544 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2545 << ToType.getNonReferenceType();
2546
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002547 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002548 }
2549
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002550 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002551 llvm_unreachable("Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002552 }
2553
John Wiegley429bb272011-04-08 18:41:53 +00002554 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002555}
2556
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002557ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002558 SourceLocation KWLoc,
2559 ParsedType Ty,
2560 SourceLocation RParen) {
2561 TypeSourceInfo *TSInfo;
2562 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002563
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002564 if (!TSInfo)
2565 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002566 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002567}
2568
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002569/// \brief Check the completeness of a type in a unary type trait.
2570///
2571/// If the particular type trait requires a complete type, tries to complete
2572/// it. If completing the type fails, a diagnostic is emitted and false
2573/// returned. If completing the type succeeds or no completion was required,
2574/// returns true.
2575static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S,
2576 UnaryTypeTrait UTT,
2577 SourceLocation Loc,
2578 QualType ArgTy) {
2579 // C++0x [meta.unary.prop]p3:
2580 // For all of the class templates X declared in this Clause, instantiating
2581 // that template with a template argument that is a class template
2582 // specialization may result in the implicit instantiation of the template
2583 // argument if and only if the semantics of X require that the argument
2584 // must be a complete type.
2585 // We apply this rule to all the type trait expressions used to implement
2586 // these class templates. We also try to follow any GCC documented behavior
2587 // in these expressions to ensure portability of standard libraries.
2588 switch (UTT) {
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002589 // is_complete_type somewhat obviously cannot require a complete type.
2590 case UTT_IsCompleteType:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002591 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002592
2593 // These traits are modeled on the type predicates in C++0x
2594 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
2595 // requiring a complete type, as whether or not they return true cannot be
2596 // impacted by the completeness of the type.
2597 case UTT_IsVoid:
2598 case UTT_IsIntegral:
2599 case UTT_IsFloatingPoint:
2600 case UTT_IsArray:
2601 case UTT_IsPointer:
2602 case UTT_IsLvalueReference:
2603 case UTT_IsRvalueReference:
2604 case UTT_IsMemberFunctionPointer:
2605 case UTT_IsMemberObjectPointer:
2606 case UTT_IsEnum:
2607 case UTT_IsUnion:
2608 case UTT_IsClass:
2609 case UTT_IsFunction:
2610 case UTT_IsReference:
2611 case UTT_IsArithmetic:
2612 case UTT_IsFundamental:
2613 case UTT_IsObject:
2614 case UTT_IsScalar:
2615 case UTT_IsCompound:
2616 case UTT_IsMemberPointer:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002617 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002618
2619 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
2620 // which requires some of its traits to have the complete type. However,
2621 // the completeness of the type cannot impact these traits' semantics, and
2622 // so they don't require it. This matches the comments on these traits in
2623 // Table 49.
2624 case UTT_IsConst:
2625 case UTT_IsVolatile:
2626 case UTT_IsSigned:
2627 case UTT_IsUnsigned:
2628 return true;
2629
2630 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002631 // applied to a complete type.
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002632 case UTT_IsTrivial:
Sean Huntfeb375d2011-05-13 00:31:07 +00002633 case UTT_IsTriviallyCopyable:
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002634 case UTT_IsStandardLayout:
2635 case UTT_IsPOD:
2636 case UTT_IsLiteral:
2637 case UTT_IsEmpty:
2638 case UTT_IsPolymorphic:
2639 case UTT_IsAbstract:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002640 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002641
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002642 // These trait expressions are designed to help implement predicates in
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002643 // [meta.unary.prop] despite not being named the same. They are specified
2644 // by both GCC and the Embarcadero C++ compiler, and require the complete
2645 // type due to the overarching C++0x type predicates being implemented
2646 // requiring the complete type.
2647 case UTT_HasNothrowAssign:
2648 case UTT_HasNothrowConstructor:
2649 case UTT_HasNothrowCopy:
2650 case UTT_HasTrivialAssign:
Sean Hunt023df372011-05-09 18:22:59 +00002651 case UTT_HasTrivialDefaultConstructor:
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002652 case UTT_HasTrivialCopy:
2653 case UTT_HasTrivialDestructor:
2654 case UTT_HasVirtualDestructor:
2655 // Arrays of unknown bound are expressly allowed.
2656 QualType ElTy = ArgTy;
2657 if (ArgTy->isIncompleteArrayType())
2658 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
2659
2660 // The void type is expressly allowed.
2661 if (ElTy->isVoidType())
2662 return true;
2663
2664 return !S.RequireCompleteType(
2665 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleycf566412011-04-28 02:06:46 +00002666 }
Chandler Carruth73e0a912011-05-01 07:23:17 +00002667 llvm_unreachable("Type trait not handled by switch");
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002668}
2669
2670static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT,
2671 SourceLocation KeyLoc, QualType T) {
Chandler Carruthd064c702011-05-01 08:41:10 +00002672 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleycf566412011-04-28 02:06:46 +00002673
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002674 ASTContext &C = Self.Context;
2675 switch(UTT) {
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002676 // Type trait expressions corresponding to the primary type category
2677 // predicates in C++0x [meta.unary.cat].
2678 case UTT_IsVoid:
2679 return T->isVoidType();
2680 case UTT_IsIntegral:
2681 return T->isIntegralType(C);
2682 case UTT_IsFloatingPoint:
2683 return T->isFloatingType();
2684 case UTT_IsArray:
2685 return T->isArrayType();
2686 case UTT_IsPointer:
2687 return T->isPointerType();
2688 case UTT_IsLvalueReference:
2689 return T->isLValueReferenceType();
2690 case UTT_IsRvalueReference:
2691 return T->isRValueReferenceType();
2692 case UTT_IsMemberFunctionPointer:
2693 return T->isMemberFunctionPointerType();
2694 case UTT_IsMemberObjectPointer:
2695 return T->isMemberDataPointerType();
2696 case UTT_IsEnum:
2697 return T->isEnumeralType();
Chandler Carruth28eeb382011-05-01 06:11:03 +00002698 case UTT_IsUnion:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002699 return T->isUnionType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002700 case UTT_IsClass:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002701 return T->isClassType() || T->isStructureType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002702 case UTT_IsFunction:
2703 return T->isFunctionType();
2704
2705 // Type trait expressions which correspond to the convenient composition
2706 // predicates in C++0x [meta.unary.comp].
2707 case UTT_IsReference:
2708 return T->isReferenceType();
2709 case UTT_IsArithmetic:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002710 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002711 case UTT_IsFundamental:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002712 return T->isFundamentalType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002713 case UTT_IsObject:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002714 return T->isObjectType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002715 case UTT_IsScalar:
John McCallf85e1932011-06-15 23:02:42 +00002716 // Note: semantic analysis depends on Objective-C lifetime types to be
2717 // considered scalar types. However, such types do not actually behave
2718 // like scalar types at run time (since they may require retain/release
2719 // operations), so we report them as non-scalar.
2720 if (T->isObjCLifetimeType()) {
2721 switch (T.getObjCLifetime()) {
2722 case Qualifiers::OCL_None:
2723 case Qualifiers::OCL_ExplicitNone:
2724 return true;
2725
2726 case Qualifiers::OCL_Strong:
2727 case Qualifiers::OCL_Weak:
2728 case Qualifiers::OCL_Autoreleasing:
2729 return false;
2730 }
2731 }
2732
Chandler Carruthcec0ced2011-05-01 09:29:55 +00002733 return T->isScalarType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002734 case UTT_IsCompound:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002735 return T->isCompoundType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002736 case UTT_IsMemberPointer:
2737 return T->isMemberPointerType();
2738
2739 // Type trait expressions which correspond to the type property predicates
2740 // in C++0x [meta.unary.prop].
2741 case UTT_IsConst:
2742 return T.isConstQualified();
2743 case UTT_IsVolatile:
2744 return T.isVolatileQualified();
2745 case UTT_IsTrivial:
John McCallf85e1932011-06-15 23:02:42 +00002746 return T.isTrivialType(Self.Context);
Sean Huntfeb375d2011-05-13 00:31:07 +00002747 case UTT_IsTriviallyCopyable:
John McCallf85e1932011-06-15 23:02:42 +00002748 return T.isTriviallyCopyableType(Self.Context);
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002749 case UTT_IsStandardLayout:
2750 return T->isStandardLayoutType();
2751 case UTT_IsPOD:
John McCallf85e1932011-06-15 23:02:42 +00002752 return T.isPODType(Self.Context);
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002753 case UTT_IsLiteral:
2754 return T->isLiteralType();
2755 case UTT_IsEmpty:
2756 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2757 return !RD->isUnion() && RD->isEmpty();
2758 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002759 case UTT_IsPolymorphic:
Chandler Carruth28eeb382011-05-01 06:11:03 +00002760 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2761 return RD->isPolymorphic();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002762 return false;
2763 case UTT_IsAbstract:
Chandler Carruth28eeb382011-05-01 06:11:03 +00002764 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2765 return RD->isAbstract();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002766 return false;
John Wiegley20c0da72011-04-27 23:09:49 +00002767 case UTT_IsSigned:
2768 return T->isSignedIntegerType();
John Wiegley20c0da72011-04-27 23:09:49 +00002769 case UTT_IsUnsigned:
2770 return T->isUnsignedIntegerType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002771
2772 // Type trait expressions which query classes regarding their construction,
2773 // destruction, and copying. Rather than being based directly on the
2774 // related type predicates in the standard, they are specified by both
2775 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
2776 // specifications.
2777 //
2778 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
2779 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Sean Hunt023df372011-05-09 18:22:59 +00002780 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002781 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2782 // If __is_pod (type) is true then the trait is true, else if type is
2783 // a cv class or union type (or array thereof) with a trivial default
2784 // constructor ([class.ctor]) then the trait is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00002785 if (T.isPODType(Self.Context))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002786 return true;
2787 if (const RecordType *RT =
2788 C.getBaseElementType(T)->getAs<RecordType>())
Sean Hunt023df372011-05-09 18:22:59 +00002789 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDefaultConstructor();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002790 return false;
2791 case UTT_HasTrivialCopy:
2792 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2793 // If __is_pod (type) is true or type is a reference type then
2794 // the trait is true, else if type is a cv class or union type
2795 // with a trivial copy constructor ([class.copy]) then the trait
2796 // is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00002797 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002798 return true;
2799 if (const RecordType *RT = T->getAs<RecordType>())
2800 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2801 return false;
2802 case UTT_HasTrivialAssign:
2803 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2804 // If type is const qualified or is a reference type then the
2805 // trait is false. Otherwise if __is_pod (type) is true then the
2806 // trait is true, else if type is a cv class or union type with
2807 // a trivial copy assignment ([class.copy]) then the trait is
2808 // true, else it is false.
2809 // Note: the const and reference restrictions are interesting,
2810 // given that const and reference members don't prevent a class
2811 // from having a trivial copy assignment operator (but do cause
2812 // errors if the copy assignment operator is actually used, q.v.
2813 // [class.copy]p12).
2814
2815 if (C.getBaseElementType(T).isConstQualified())
2816 return false;
John McCallf85e1932011-06-15 23:02:42 +00002817 if (T.isPODType(Self.Context))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002818 return true;
2819 if (const RecordType *RT = T->getAs<RecordType>())
2820 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2821 return false;
2822 case UTT_HasTrivialDestructor:
2823 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2824 // If __is_pod (type) is true or type is a reference type
2825 // then the trait is true, else if type is a cv class or union
2826 // type (or array thereof) with a trivial destructor
2827 // ([class.dtor]) then the trait is true, else it is
2828 // false.
John McCallf85e1932011-06-15 23:02:42 +00002829 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002830 return true;
John McCallf85e1932011-06-15 23:02:42 +00002831
2832 // Objective-C++ ARC: autorelease types don't require destruction.
2833 if (T->isObjCLifetimeType() &&
2834 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
2835 return true;
2836
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002837 if (const RecordType *RT =
2838 C.getBaseElementType(T)->getAs<RecordType>())
2839 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2840 return false;
2841 // TODO: Propagate nothrowness for implicitly declared special members.
2842 case UTT_HasNothrowAssign:
2843 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2844 // If type is const qualified or is a reference type then the
2845 // trait is false. Otherwise if __has_trivial_assign (type)
2846 // is true then the trait is true, else if type is a cv class
2847 // or union type with copy assignment operators that are known
2848 // not to throw an exception then the trait is true, else it is
2849 // false.
2850 if (C.getBaseElementType(T).isConstQualified())
2851 return false;
2852 if (T->isReferenceType())
2853 return false;
John McCallf85e1932011-06-15 23:02:42 +00002854 if (T.isPODType(Self.Context) || T->isObjCLifetimeType())
2855 return true;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002856 if (const RecordType *RT = T->getAs<RecordType>()) {
2857 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2858 if (RD->hasTrivialCopyAssignment())
2859 return true;
2860
2861 bool FoundAssign = false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002862 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redlf8aca862010-09-14 23:40:14 +00002863 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2864 Sema::LookupOrdinaryName);
2865 if (Self.LookupQualifiedName(Res, RD)) {
Douglas Gregord41679d2011-10-12 15:40:49 +00002866 Res.suppressDiagnostics();
Sebastian Redlf8aca862010-09-14 23:40:14 +00002867 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2868 Op != OpEnd; ++Op) {
Douglas Gregord41679d2011-10-12 15:40:49 +00002869 if (isa<FunctionTemplateDecl>(*Op))
2870 continue;
2871
Sebastian Redlf8aca862010-09-14 23:40:14 +00002872 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2873 if (Operator->isCopyAssignmentOperator()) {
2874 FoundAssign = true;
2875 const FunctionProtoType *CPT
2876 = Operator->getType()->getAs<FunctionProtoType>();
Richard Smith7a614d82011-06-11 17:19:42 +00002877 if (CPT->getExceptionSpecType() == EST_Delayed)
2878 return false;
2879 if (!CPT->isNothrow(Self.Context))
2880 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002881 }
2882 }
2883 }
Douglas Gregord41679d2011-10-12 15:40:49 +00002884
Richard Smith7a614d82011-06-11 17:19:42 +00002885 return FoundAssign;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002886 }
2887 return false;
2888 case UTT_HasNothrowCopy:
2889 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2890 // If __has_trivial_copy (type) is true then the trait is true, else
2891 // if type is a cv class or union type with copy constructors that are
2892 // known not to throw an exception then the trait is true, else it is
2893 // false.
John McCallf85e1932011-06-15 23:02:42 +00002894 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002895 return true;
2896 if (const RecordType *RT = T->getAs<RecordType>()) {
2897 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2898 if (RD->hasTrivialCopyConstructor())
2899 return true;
2900
2901 bool FoundConstructor = false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002902 unsigned FoundTQs;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002903 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl5f4e8992010-09-13 21:10:20 +00002904 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002905 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002906 // A template constructor is never a copy constructor.
2907 // FIXME: However, it may actually be selected at the actual overload
2908 // resolution point.
2909 if (isa<FunctionTemplateDecl>(*Con))
2910 continue;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002911 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2912 if (Constructor->isCopyConstructor(FoundTQs)) {
2913 FoundConstructor = true;
2914 const FunctionProtoType *CPT
2915 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smith7a614d82011-06-11 17:19:42 +00002916 if (CPT->getExceptionSpecType() == EST_Delayed)
2917 return false;
Sebastian Redl60618fa2011-03-12 11:50:43 +00002918 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redl751025d2010-09-13 22:02:47 +00002919 // For now, we'll be conservative and assume that they can throw.
Richard Smith7a614d82011-06-11 17:19:42 +00002920 if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1)
2921 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002922 }
2923 }
2924
Richard Smith7a614d82011-06-11 17:19:42 +00002925 return FoundConstructor;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002926 }
2927 return false;
2928 case UTT_HasNothrowConstructor:
2929 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2930 // If __has_trivial_constructor (type) is true then the trait is
2931 // true, else if type is a cv class or union type (or array
2932 // thereof) with a default constructor that is known not to
2933 // throw an exception then the trait is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00002934 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002935 return true;
2936 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
2937 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Hunt023df372011-05-09 18:22:59 +00002938 if (RD->hasTrivialDefaultConstructor())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002939 return true;
2940
Sebastian Redl751025d2010-09-13 22:02:47 +00002941 DeclContext::lookup_const_iterator Con, ConEnd;
2942 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2943 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002944 // FIXME: In C++0x, a constructor template can be a default constructor.
2945 if (isa<FunctionTemplateDecl>(*Con))
2946 continue;
Sebastian Redl751025d2010-09-13 22:02:47 +00002947 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2948 if (Constructor->isDefaultConstructor()) {
2949 const FunctionProtoType *CPT
2950 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smith7a614d82011-06-11 17:19:42 +00002951 if (CPT->getExceptionSpecType() == EST_Delayed)
2952 return false;
Sebastian Redl751025d2010-09-13 22:02:47 +00002953 // TODO: check whether evaluating default arguments can throw.
2954 // For now, we'll be conservative and assume that they can throw.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002955 return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
Sebastian Redl751025d2010-09-13 22:02:47 +00002956 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002957 }
2958 }
2959 return false;
2960 case UTT_HasVirtualDestructor:
2961 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2962 // If type is a class type with a virtual destructor ([class.dtor])
2963 // then the trait is true, else it is false.
2964 if (const RecordType *Record = T->getAs<RecordType>()) {
2965 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redlf8aca862010-09-14 23:40:14 +00002966 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002967 return Destructor->isVirtual();
2968 }
2969 return false;
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002970
2971 // These type trait expressions are modeled on the specifications for the
2972 // Embarcadero C++0x type trait functions:
2973 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
2974 case UTT_IsCompleteType:
2975 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
2976 // Returns True if and only if T is a complete type at the point of the
2977 // function call.
2978 return !T->isIncompleteType();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002979 }
Chandler Carruth83f563c2011-05-01 07:44:17 +00002980 llvm_unreachable("Type trait not covered by switch");
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002981}
2982
2983ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002984 SourceLocation KWLoc,
2985 TypeSourceInfo *TSInfo,
2986 SourceLocation RParen) {
2987 QualType T = TSInfo->getType();
Chandler Carrutheb65a102011-04-30 10:07:32 +00002988 if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T))
2989 return ExprError();
Sebastian Redl64b45f72009-01-05 20:52:13 +00002990
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002991 bool Value = false;
2992 if (!T->isDependentType())
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002993 Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002994
2995 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002996 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00002997}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002998
Francois Pichet6ad6f282010-12-07 00:08:36 +00002999ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
3000 SourceLocation KWLoc,
3001 ParsedType LhsTy,
3002 ParsedType RhsTy,
3003 SourceLocation RParen) {
3004 TypeSourceInfo *LhsTSInfo;
3005 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
3006 if (!LhsTSInfo)
3007 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
3008
3009 TypeSourceInfo *RhsTSInfo;
3010 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
3011 if (!RhsTSInfo)
3012 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
3013
3014 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
3015}
3016
3017static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
3018 QualType LhsT, QualType RhsT,
3019 SourceLocation KeyLoc) {
Chandler Carruthd064c702011-05-01 08:41:10 +00003020 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
3021 "Cannot evaluate traits of dependent types");
Francois Pichet6ad6f282010-12-07 00:08:36 +00003022
3023 switch(BTT) {
John McCalld89d30f2011-01-28 22:02:36 +00003024 case BTT_IsBaseOf: {
Francois Pichet6ad6f282010-12-07 00:08:36 +00003025 // C++0x [meta.rel]p2
John McCalld89d30f2011-01-28 22:02:36 +00003026 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet6ad6f282010-12-07 00:08:36 +00003027 // Base and Derived are not unions and name the same class type without
3028 // regard to cv-qualifiers.
Francois Pichet6ad6f282010-12-07 00:08:36 +00003029
John McCalld89d30f2011-01-28 22:02:36 +00003030 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
3031 if (!lhsRecord) return false;
3032
3033 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
3034 if (!rhsRecord) return false;
3035
3036 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
3037 == (lhsRecord == rhsRecord));
3038
3039 if (lhsRecord == rhsRecord)
3040 return !lhsRecord->getDecl()->isUnion();
3041
3042 // C++0x [meta.rel]p2:
3043 // If Base and Derived are class types and are different types
3044 // (ignoring possible cv-qualifiers) then Derived shall be a
3045 // complete type.
3046 if (Self.RequireCompleteType(KeyLoc, RhsT,
3047 diag::err_incomplete_type_used_in_type_trait_expr))
3048 return false;
3049
3050 return cast<CXXRecordDecl>(rhsRecord->getDecl())
3051 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
3052 }
John Wiegley20c0da72011-04-27 23:09:49 +00003053 case BTT_IsSame:
3054 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichetf1872372010-12-08 22:35:30 +00003055 case BTT_TypeCompatible:
3056 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
3057 RhsT.getUnqualifiedType());
John Wiegley20c0da72011-04-27 23:09:49 +00003058 case BTT_IsConvertible:
Douglas Gregor9f361132011-01-27 20:28:01 +00003059 case BTT_IsConvertibleTo: {
3060 // C++0x [meta.rel]p4:
3061 // Given the following function prototype:
3062 //
3063 // template <class T>
3064 // typename add_rvalue_reference<T>::type create();
3065 //
3066 // the predicate condition for a template specialization
3067 // is_convertible<From, To> shall be satisfied if and only if
3068 // the return expression in the following code would be
3069 // well-formed, including any implicit conversions to the return
3070 // type of the function:
3071 //
3072 // To test() {
3073 // return create<From>();
3074 // }
3075 //
3076 // Access checking is performed as if in a context unrelated to To and
3077 // From. Only the validity of the immediate context of the expression
3078 // of the return-statement (including conversions to the return type)
3079 // is considered.
3080 //
3081 // We model the initialization as a copy-initialization of a temporary
3082 // of the appropriate type, which for this expression is identical to the
3083 // return statement (since NRVO doesn't apply).
3084 if (LhsT->isObjectType() || LhsT->isFunctionType())
3085 LhsT = Self.Context.getRValueReferenceType(LhsT);
3086
3087 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorb608b982011-01-28 02:26:04 +00003088 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor9f361132011-01-27 20:28:01 +00003089 Expr::getValueKindForType(LhsT));
3090 Expr *FromPtr = &From;
3091 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
3092 SourceLocation()));
3093
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00003094 // Perform the initialization within a SFINAE trap at translation unit
3095 // scope.
3096 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3097 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Douglas Gregor9f361132011-01-27 20:28:01 +00003098 InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003099 if (Init.Failed())
Douglas Gregor9f361132011-01-27 20:28:01 +00003100 return false;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00003101
Douglas Gregor9f361132011-01-27 20:28:01 +00003102 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
3103 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
3104 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00003105 }
3106 llvm_unreachable("Unknown type trait or not implemented");
3107}
3108
3109ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
3110 SourceLocation KWLoc,
3111 TypeSourceInfo *LhsTSInfo,
3112 TypeSourceInfo *RhsTSInfo,
3113 SourceLocation RParen) {
3114 QualType LhsT = LhsTSInfo->getType();
3115 QualType RhsT = RhsTSInfo->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003116
John McCalld89d30f2011-01-28 22:02:36 +00003117 if (BTT == BTT_TypeCompatible) {
Francois Pichetf1872372010-12-08 22:35:30 +00003118 if (getLangOptions().CPlusPlus) {
3119 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
3120 << SourceRange(KWLoc, RParen);
3121 return ExprError();
3122 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00003123 }
3124
3125 bool Value = false;
3126 if (!LhsT->isDependentType() && !RhsT->isDependentType())
3127 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
3128
Francois Pichetf1872372010-12-08 22:35:30 +00003129 // Select trait result type.
3130 QualType ResultType;
3131 switch (BTT) {
Francois Pichetf1872372010-12-08 22:35:30 +00003132 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
John Wiegley20c0da72011-04-27 23:09:49 +00003133 case BTT_IsConvertible: ResultType = Context.BoolTy; break;
3134 case BTT_IsSame: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00003135 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
Douglas Gregor9f361132011-01-27 20:28:01 +00003136 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00003137 }
3138
Francois Pichet6ad6f282010-12-07 00:08:36 +00003139 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
3140 RhsTSInfo, Value, RParen,
Francois Pichetf1872372010-12-08 22:35:30 +00003141 ResultType));
Francois Pichet6ad6f282010-12-07 00:08:36 +00003142}
3143
John Wiegley21ff2e52011-04-28 00:16:57 +00003144ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3145 SourceLocation KWLoc,
3146 ParsedType Ty,
3147 Expr* DimExpr,
3148 SourceLocation RParen) {
3149 TypeSourceInfo *TSInfo;
3150 QualType T = GetTypeFromParser(Ty, &TSInfo);
3151 if (!TSInfo)
3152 TSInfo = Context.getTrivialTypeSourceInfo(T);
3153
3154 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
3155}
3156
3157static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
3158 QualType T, Expr *DimExpr,
3159 SourceLocation KeyLoc) {
Chandler Carruthd064c702011-05-01 08:41:10 +00003160 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley21ff2e52011-04-28 00:16:57 +00003161
3162 switch(ATT) {
3163 case ATT_ArrayRank:
3164 if (T->isArrayType()) {
3165 unsigned Dim = 0;
3166 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3167 ++Dim;
3168 T = AT->getElementType();
3169 }
3170 return Dim;
John Wiegley21ff2e52011-04-28 00:16:57 +00003171 }
John Wiegleycf566412011-04-28 02:06:46 +00003172 return 0;
3173
John Wiegley21ff2e52011-04-28 00:16:57 +00003174 case ATT_ArrayExtent: {
3175 llvm::APSInt Value;
3176 uint64_t Dim;
John Wiegleycf566412011-04-28 02:06:46 +00003177 if (DimExpr->isIntegerConstantExpr(Value, Self.Context, 0, false)) {
3178 if (Value < llvm::APSInt(Value.getBitWidth(), Value.isUnsigned())) {
3179 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
3180 DimExpr->getSourceRange();
3181 return false;
3182 }
John Wiegley21ff2e52011-04-28 00:16:57 +00003183 Dim = Value.getLimitedValue();
John Wiegleycf566412011-04-28 02:06:46 +00003184 } else {
3185 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
3186 DimExpr->getSourceRange();
3187 return false;
3188 }
John Wiegley21ff2e52011-04-28 00:16:57 +00003189
3190 if (T->isArrayType()) {
3191 unsigned D = 0;
3192 bool Matched = false;
3193 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3194 if (Dim == D) {
3195 Matched = true;
3196 break;
3197 }
3198 ++D;
3199 T = AT->getElementType();
3200 }
3201
John Wiegleycf566412011-04-28 02:06:46 +00003202 if (Matched && T->isArrayType()) {
3203 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
3204 return CAT->getSize().getLimitedValue();
3205 }
John Wiegley21ff2e52011-04-28 00:16:57 +00003206 }
John Wiegleycf566412011-04-28 02:06:46 +00003207 return 0;
John Wiegley21ff2e52011-04-28 00:16:57 +00003208 }
3209 }
3210 llvm_unreachable("Unknown type trait or not implemented");
3211}
3212
3213ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
3214 SourceLocation KWLoc,
3215 TypeSourceInfo *TSInfo,
3216 Expr* DimExpr,
3217 SourceLocation RParen) {
3218 QualType T = TSInfo->getType();
John Wiegley21ff2e52011-04-28 00:16:57 +00003219
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003220 // FIXME: This should likely be tracked as an APInt to remove any host
3221 // assumptions about the width of size_t on the target.
Chandler Carruthd064c702011-05-01 08:41:10 +00003222 uint64_t Value = 0;
3223 if (!T->isDependentType())
3224 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
3225
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003226 // While the specification for these traits from the Embarcadero C++
3227 // compiler's documentation says the return type is 'unsigned int', Clang
3228 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
3229 // compiler, there is no difference. On several other platforms this is an
3230 // important distinction.
John Wiegley21ff2e52011-04-28 00:16:57 +00003231 return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value,
Chandler Carruth06207f62011-05-01 07:49:26 +00003232 DimExpr, RParen,
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003233 Context.getSizeType()));
John Wiegley21ff2e52011-04-28 00:16:57 +00003234}
3235
John Wiegley55262202011-04-25 06:54:41 +00003236ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003237 SourceLocation KWLoc,
3238 Expr *Queried,
3239 SourceLocation RParen) {
John Wiegley55262202011-04-25 06:54:41 +00003240 // If error parsing the expression, ignore.
3241 if (!Queried)
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003242 return ExprError();
John Wiegley55262202011-04-25 06:54:41 +00003243
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003244 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegley55262202011-04-25 06:54:41 +00003245
3246 return move(Result);
3247}
3248
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003249static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
3250 switch (ET) {
3251 case ET_IsLValueExpr: return E->isLValue();
3252 case ET_IsRValueExpr: return E->isRValue();
3253 }
3254 llvm_unreachable("Expression trait not covered by switch");
3255}
3256
John Wiegley55262202011-04-25 06:54:41 +00003257ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003258 SourceLocation KWLoc,
3259 Expr *Queried,
3260 SourceLocation RParen) {
John Wiegley55262202011-04-25 06:54:41 +00003261 if (Queried->isTypeDependent()) {
3262 // Delay type-checking for type-dependent expressions.
3263 } else if (Queried->getType()->isPlaceholderType()) {
3264 ExprResult PE = CheckPlaceholderExpr(Queried);
3265 if (PE.isInvalid()) return ExprError();
3266 return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen);
3267 }
3268
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003269 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf7ef0002011-05-01 08:48:19 +00003270
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003271 return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value,
3272 RParen, Context.BoolTy));
John Wiegley55262202011-04-25 06:54:41 +00003273}
3274
Richard Trieudd225092011-09-15 21:56:47 +00003275QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCallf89e55a2010-11-18 06:31:45 +00003276 ExprValueKind &VK,
3277 SourceLocation Loc,
3278 bool isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003279 assert(!LHS.get()->getType()->isPlaceholderType() &&
3280 !RHS.get()->getType()->isPlaceholderType() &&
John McCallea4aba02011-06-30 17:15:34 +00003281 "placeholders should have been weeded out by now");
3282
3283 // The LHS undergoes lvalue conversions if this is ->*.
3284 if (isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003285 LHS = DefaultLvalueConversion(LHS.take());
3286 if (LHS.isInvalid()) return QualType();
John McCallea4aba02011-06-30 17:15:34 +00003287 }
3288
3289 // The RHS always undergoes lvalue conversions.
Richard Trieudd225092011-09-15 21:56:47 +00003290 RHS = DefaultLvalueConversion(RHS.take());
3291 if (RHS.isInvalid()) return QualType();
John McCallea4aba02011-06-30 17:15:34 +00003292
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003293 const char *OpSpelling = isIndirect ? "->*" : ".*";
3294 // C++ 5.5p2
3295 // The binary operator .* [p3: ->*] binds its second operand, which shall
3296 // be of type "pointer to member of T" (where T is a completely-defined
3297 // class type) [...]
Richard Trieudd225092011-09-15 21:56:47 +00003298 QualType RHSType = RHS.get()->getType();
3299 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00003300 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003301 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieudd225092011-09-15 21:56:47 +00003302 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003303 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00003304 }
Douglas Gregore7450f52009-03-24 19:52:54 +00003305
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003306 QualType Class(MemPtr->getClass(), 0);
3307
Douglas Gregor7d520ba2010-10-13 20:41:14 +00003308 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
3309 // member pointer points must be completely-defined. However, there is no
3310 // reason for this semantic distinction, and the rule is not enforced by
3311 // other compilers. Therefore, we do not check this property, as it is
3312 // likely to be considered a defect.
Sebastian Redl59fc2692010-04-10 10:14:54 +00003313
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003314 // C++ 5.5p2
3315 // [...] to its first operand, which shall be of class T or of a class of
3316 // which T is an unambiguous and accessible base class. [p3: a pointer to
3317 // such a class]
Richard Trieudd225092011-09-15 21:56:47 +00003318 QualType LHSType = LHS.get()->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003319 if (isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003320 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
3321 LHSType = Ptr->getPointeeType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003322 else {
3323 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieudd225092011-09-15 21:56:47 +00003324 << OpSpelling << 1 << LHSType
Douglas Gregor849b2432010-03-31 17:46:05 +00003325 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003326 return QualType();
3327 }
3328 }
3329
Richard Trieudd225092011-09-15 21:56:47 +00003330 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00003331 // If we want to check the hierarchy, we need a complete type.
Richard Trieudd225092011-09-15 21:56:47 +00003332 if (RequireCompleteType(Loc, LHSType, PDiag(diag::err_bad_memptr_lhs)
Sebastian Redl17e1d352010-04-23 17:18:26 +00003333 << OpSpelling << (int)isIndirect)) {
3334 return QualType();
3335 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003336 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00003337 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00003338 // FIXME: Would it be useful to print full ambiguity paths, or is that
3339 // overkill?
Richard Trieudd225092011-09-15 21:56:47 +00003340 if (!IsDerivedFrom(LHSType, Class, Paths) ||
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003341 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
3342 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieudd225092011-09-15 21:56:47 +00003343 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003344 return QualType();
3345 }
Eli Friedman3005efe2010-01-16 00:00:48 +00003346 // Cast LHS to type of use.
3347 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00003348 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Sebastian Redl906082e2010-07-20 04:20:21 +00003349
John McCallf871d0c2010-08-07 06:22:56 +00003350 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003351 BuildBasePathArray(Paths, BasePath);
Richard Trieudd225092011-09-15 21:56:47 +00003352 LHS = ImpCastExprToType(LHS.take(), UseType, CK_DerivedToBase, VK,
3353 &BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003354 }
3355
Richard Trieudd225092011-09-15 21:56:47 +00003356 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00003357 // Diagnose use of pointer-to-member type which when used as
3358 // the functional cast in a pointer-to-member expression.
3359 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
3360 return QualType();
3361 }
John McCallf89e55a2010-11-18 06:31:45 +00003362
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003363 // C++ 5.5p2
3364 // The result is an object or a function of the type specified by the
3365 // second operand.
3366 // The cv qualifiers are the union of those in the pointer and the left side,
3367 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003368 QualType Result = MemPtr->getPointeeType();
Richard Trieudd225092011-09-15 21:56:47 +00003369 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCallf89e55a2010-11-18 06:31:45 +00003370
Douglas Gregor6b4df912011-01-26 16:40:18 +00003371 // C++0x [expr.mptr.oper]p6:
3372 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003373 // ill-formed if the second operand is a pointer to member function with
3374 // ref-qualifier &. In a ->* expression or in a .* expression whose object
3375 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor6b4df912011-01-26 16:40:18 +00003376 // is a pointer to member function with ref-qualifier &&.
3377 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
3378 switch (Proto->getRefQualifier()) {
3379 case RQ_None:
3380 // Do nothing
3381 break;
3382
3383 case RQ_LValue:
Richard Trieudd225092011-09-15 21:56:47 +00003384 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
Douglas Gregor6b4df912011-01-26 16:40:18 +00003385 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieudd225092011-09-15 21:56:47 +00003386 << RHSType << 1 << LHS.get()->getSourceRange();
Douglas Gregor6b4df912011-01-26 16:40:18 +00003387 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003388
Douglas Gregor6b4df912011-01-26 16:40:18 +00003389 case RQ_RValue:
Richard Trieudd225092011-09-15 21:56:47 +00003390 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor6b4df912011-01-26 16:40:18 +00003391 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieudd225092011-09-15 21:56:47 +00003392 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor6b4df912011-01-26 16:40:18 +00003393 break;
3394 }
3395 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003396
John McCallf89e55a2010-11-18 06:31:45 +00003397 // C++ [expr.mptr.oper]p6:
3398 // The result of a .* expression whose second operand is a pointer
3399 // to a data member is of the same value category as its
3400 // first operand. The result of a .* expression whose second
3401 // operand is a pointer to a member function is a prvalue. The
3402 // result of an ->* expression is an lvalue if its second operand
3403 // is a pointer to data member and a prvalue otherwise.
John McCall864c0412011-04-26 20:42:42 +00003404 if (Result->isFunctionType()) {
John McCallf89e55a2010-11-18 06:31:45 +00003405 VK = VK_RValue;
John McCall864c0412011-04-26 20:42:42 +00003406 return Context.BoundMemberTy;
3407 } else if (isIndirect) {
John McCallf89e55a2010-11-18 06:31:45 +00003408 VK = VK_LValue;
John McCall864c0412011-04-26 20:42:42 +00003409 } else {
Richard Trieudd225092011-09-15 21:56:47 +00003410 VK = LHS.get()->getValueKind();
John McCall864c0412011-04-26 20:42:42 +00003411 }
John McCallf89e55a2010-11-18 06:31:45 +00003412
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003413 return Result;
3414}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003415
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003416/// \brief Try to convert a type to another according to C++0x 5.16p3.
3417///
3418/// This is part of the parameter validation for the ? operator. If either
3419/// value operand is a class type, the two operands are attempted to be
3420/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003421/// It returns true if the program is ill-formed and has already been diagnosed
3422/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003423static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
3424 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00003425 bool &HaveConversion,
3426 QualType &ToType) {
3427 HaveConversion = false;
3428 ToType = To->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003429
3430 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00003431 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003432 // C++0x 5.16p3
3433 // The process for determining whether an operand expression E1 of type T1
3434 // can be converted to match an operand expression E2 of type T2 is defined
3435 // as follows:
3436 // -- If E2 is an lvalue:
John McCall7eb0a9e2010-11-24 05:12:34 +00003437 bool ToIsLvalue = To->isLValue();
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00003438 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003439 // E1 can be converted to match E2 if E1 can be implicitly converted to
3440 // type "lvalue reference to T2", subject to the constraint that in the
3441 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003442 QualType T = Self.Context.getLValueReferenceType(ToType);
3443 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003444
Douglas Gregorb70cf442010-03-26 20:14:36 +00003445 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3446 if (InitSeq.isDirectReferenceBinding()) {
3447 ToType = T;
3448 HaveConversion = true;
3449 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003450 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003451
Douglas Gregorb70cf442010-03-26 20:14:36 +00003452 if (InitSeq.isAmbiguous())
3453 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003454 }
John McCallb1bdc622010-02-25 01:37:24 +00003455
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003456 // -- If E2 is an rvalue, or if the conversion above cannot be done:
3457 // -- if E1 and E2 have class type, and the underlying class types are
3458 // the same or one is a base class of the other:
3459 QualType FTy = From->getType();
3460 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003461 const RecordType *FRec = FTy->getAs<RecordType>();
3462 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003463 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00003464 Self.IsDerivedFrom(FTy, TTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003465 if (FRec && TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00003466 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003467 // E1 can be converted to match E2 if the class of T2 is the
3468 // same type as, or a base class of, the class of T1, and
3469 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00003470 if (FRec == TRec || FDerivedFromT) {
3471 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003472 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3473 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003474 if (InitSeq) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003475 HaveConversion = true;
3476 return false;
3477 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003478
Douglas Gregorb70cf442010-03-26 20:14:36 +00003479 if (InitSeq.isAmbiguous())
3480 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003481 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003482 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003483
Douglas Gregorb70cf442010-03-26 20:14:36 +00003484 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003485 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003486
Douglas Gregorb70cf442010-03-26 20:14:36 +00003487 // -- Otherwise: E1 can be converted to match E2 if E1 can be
3488 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003489 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00003490 // an rvalue).
3491 //
3492 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
3493 // to the array-to-pointer or function-to-pointer conversions.
3494 if (!TTy->getAs<TagType>())
3495 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003496
Douglas Gregorb70cf442010-03-26 20:14:36 +00003497 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3498 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003499 HaveConversion = !InitSeq.Failed();
Douglas Gregorb70cf442010-03-26 20:14:36 +00003500 ToType = TTy;
3501 if (InitSeq.isAmbiguous())
3502 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3503
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003504 return false;
3505}
3506
3507/// \brief Try to find a common type for two according to C++0x 5.16p5.
3508///
3509/// This is part of the parameter validation for the ? operator. If either
3510/// value operand is a class type, overload resolution is used to find a
3511/// conversion to a common type.
John Wiegley429bb272011-04-08 18:41:53 +00003512static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth82214a82011-02-18 23:54:50 +00003513 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00003514 Expr *Args[2] = { LHS.get(), RHS.get() };
Chandler Carruth82214a82011-02-18 23:54:50 +00003515 OverloadCandidateSet CandidateSet(QuestionLoc);
3516 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
3517 CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003518
3519 OverloadCandidateSet::iterator Best;
Chandler Carruth82214a82011-02-18 23:54:50 +00003520 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley429bb272011-04-08 18:41:53 +00003521 case OR_Success: {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003522 // We found a match. Perform the conversions on the arguments and move on.
John Wiegley429bb272011-04-08 18:41:53 +00003523 ExprResult LHSRes =
3524 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
3525 Best->Conversions[0], Sema::AA_Converting);
3526 if (LHSRes.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003527 break;
John Wiegley429bb272011-04-08 18:41:53 +00003528 LHS = move(LHSRes);
3529
3530 ExprResult RHSRes =
3531 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
3532 Best->Conversions[1], Sema::AA_Converting);
3533 if (RHSRes.isInvalid())
3534 break;
3535 RHS = move(RHSRes);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003536 if (Best->Function)
3537 Self.MarkDeclarationReferenced(QuestionLoc, Best->Function);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003538 return false;
John Wiegley429bb272011-04-08 18:41:53 +00003539 }
3540
Douglas Gregor20093b42009-12-09 23:02:17 +00003541 case OR_No_Viable_Function:
Chandler Carruth82214a82011-02-18 23:54:50 +00003542
3543 // Emit a better diagnostic if one of the expressions is a null pointer
3544 // constant and the other is a pointer type. In this case, the user most
3545 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00003546 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00003547 return true;
3548
3549 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00003550 << LHS.get()->getType() << RHS.get()->getType()
3551 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003552 return true;
3553
Douglas Gregor20093b42009-12-09 23:02:17 +00003554 case OR_Ambiguous:
Chandler Carruth82214a82011-02-18 23:54:50 +00003555 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley429bb272011-04-08 18:41:53 +00003556 << LHS.get()->getType() << RHS.get()->getType()
3557 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00003558 // FIXME: Print the possible common types by printing the return types of
3559 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003560 break;
3561
Douglas Gregor20093b42009-12-09 23:02:17 +00003562 case OR_Deleted:
David Blaikieb219cfc2011-09-23 05:06:16 +00003563 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003564 }
3565 return true;
3566}
3567
Sebastian Redl76458502009-04-17 16:30:52 +00003568/// \brief Perform an "extended" implicit conversion as returned by
3569/// TryClassUnification.
John Wiegley429bb272011-04-08 18:41:53 +00003570static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003571 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley429bb272011-04-08 18:41:53 +00003572 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00003573 SourceLocation());
John Wiegley429bb272011-04-08 18:41:53 +00003574 Expr *Arg = E.take();
3575 InitializationSequence InitSeq(Self, Entity, Kind, &Arg, 1);
3576 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&Arg, 1));
Douglas Gregorb70cf442010-03-26 20:14:36 +00003577 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00003578 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003579
John Wiegley429bb272011-04-08 18:41:53 +00003580 E = Result;
Sebastian Redl76458502009-04-17 16:30:52 +00003581 return false;
3582}
3583
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003584/// \brief Check the operands of ?: under C++ semantics.
3585///
3586/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
3587/// extension. In this case, LHS == Cond. (But they're not aliases.)
John Wiegley429bb272011-04-08 18:41:53 +00003588QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCall56ca35d2011-02-17 10:25:35 +00003589 ExprValueKind &VK, ExprObjectKind &OK,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003590 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00003591 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
3592 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003593
3594 // C++0x 5.16p1
3595 // The first expression is contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00003596 if (!Cond.get()->isTypeDependent()) {
3597 ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
3598 if (CondRes.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003599 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003600 Cond = move(CondRes);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003601 }
3602
John McCallf89e55a2010-11-18 06:31:45 +00003603 // Assume r-value.
3604 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00003605 OK = OK_Ordinary;
John McCallf89e55a2010-11-18 06:31:45 +00003606
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003607 // Either of the arguments dependent?
John Wiegley429bb272011-04-08 18:41:53 +00003608 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003609 return Context.DependentTy;
3610
3611 // C++0x 5.16p2
3612 // If either the second or the third operand has type (cv) void, ...
John Wiegley429bb272011-04-08 18:41:53 +00003613 QualType LTy = LHS.get()->getType();
3614 QualType RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003615 bool LVoid = LTy->isVoidType();
3616 bool RVoid = RTy->isVoidType();
3617 if (LVoid || RVoid) {
3618 // ... then the [l2r] conversions are performed on the second and third
3619 // operands ...
John Wiegley429bb272011-04-08 18:41:53 +00003620 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3621 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3622 if (LHS.isInvalid() || RHS.isInvalid())
3623 return QualType();
3624 LTy = LHS.get()->getType();
3625 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003626
3627 // ... and one of the following shall hold:
3628 // -- The second or the third operand (but not both) is a throw-
3629 // expression; the result is of the type of the other and is an rvalue.
John Wiegley429bb272011-04-08 18:41:53 +00003630 bool LThrow = isa<CXXThrowExpr>(LHS.get());
3631 bool RThrow = isa<CXXThrowExpr>(RHS.get());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003632 if (LThrow && !RThrow)
3633 return RTy;
3634 if (RThrow && !LThrow)
3635 return LTy;
3636
3637 // -- Both the second and third operands have type void; the result is of
3638 // type void and is an rvalue.
3639 if (LVoid && RVoid)
3640 return Context.VoidTy;
3641
3642 // Neither holds, error.
3643 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
3644 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley429bb272011-04-08 18:41:53 +00003645 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003646 return QualType();
3647 }
3648
3649 // Neither is void.
3650
3651 // C++0x 5.16p3
3652 // Otherwise, if the second and third operand have different types, and
3653 // either has (cv) class type, and attempt is made to convert each of those
3654 // operands to the other.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003655 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003656 (LTy->isRecordType() || RTy->isRecordType())) {
3657 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
3658 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003659 QualType L2RType, R2LType;
3660 bool HaveL2R, HaveR2L;
John Wiegley429bb272011-04-08 18:41:53 +00003661 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003662 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003663 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003664 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003665
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003666 // If both can be converted, [...] the program is ill-formed.
3667 if (HaveL2R && HaveR2L) {
3668 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley429bb272011-04-08 18:41:53 +00003669 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003670 return QualType();
3671 }
3672
3673 // If exactly one conversion is possible, that conversion is applied to
3674 // the chosen operand and the converted operands are used in place of the
3675 // original operands for the remainder of this section.
3676 if (HaveL2R) {
John Wiegley429bb272011-04-08 18:41:53 +00003677 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003678 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003679 LTy = LHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003680 } else if (HaveR2L) {
John Wiegley429bb272011-04-08 18:41:53 +00003681 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003682 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003683 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003684 }
3685 }
3686
3687 // C++0x 5.16p4
John McCallf89e55a2010-11-18 06:31:45 +00003688 // If the second and third operands are glvalues of the same value
3689 // category and have the same type, the result is of that type and
3690 // value category and it is a bit-field if the second or the third
3691 // operand is a bit-field, or if both are bit-fields.
John McCall09431682010-11-18 19:01:18 +00003692 // We only extend this to bitfields, not to the crazy other kinds of
3693 // l-values.
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003694 bool Same = Context.hasSameType(LTy, RTy);
John McCallf89e55a2010-11-18 06:31:45 +00003695 if (Same &&
John Wiegley429bb272011-04-08 18:41:53 +00003696 LHS.get()->isGLValue() &&
3697 LHS.get()->getValueKind() == RHS.get()->getValueKind() &&
3698 LHS.get()->isOrdinaryOrBitFieldObject() &&
3699 RHS.get()->isOrdinaryOrBitFieldObject()) {
3700 VK = LHS.get()->getValueKind();
3701 if (LHS.get()->getObjectKind() == OK_BitField ||
3702 RHS.get()->getObjectKind() == OK_BitField)
John McCall09431682010-11-18 19:01:18 +00003703 OK = OK_BitField;
John McCallf89e55a2010-11-18 06:31:45 +00003704 return LTy;
Fariborz Jahanian3911a1a2010-09-25 01:08:05 +00003705 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003706
3707 // C++0x 5.16p5
3708 // Otherwise, the result is an rvalue. If the second and third operands
3709 // do not have the same type, and either has (cv) class type, ...
3710 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
3711 // ... overload resolution is used to determine the conversions (if any)
3712 // to be applied to the operands. If the overload resolution fails, the
3713 // program is ill-formed.
3714 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
3715 return QualType();
3716 }
3717
3718 // C++0x 5.16p6
3719 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
3720 // conversions are performed on the second and third operands.
John Wiegley429bb272011-04-08 18:41:53 +00003721 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3722 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3723 if (LHS.isInvalid() || RHS.isInvalid())
3724 return QualType();
3725 LTy = LHS.get()->getType();
3726 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003727
3728 // After those conversions, one of the following shall hold:
3729 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00003730 // is of that type. If the operands have class type, the result
3731 // is a prvalue temporary of the result type, which is
3732 // copy-initialized from either the second operand or the third
3733 // operand depending on the value of the first operand.
3734 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
3735 if (LTy->isRecordType()) {
3736 // The operands have class type. Make a temporary copy.
3737 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003738 ExprResult LHSCopy = PerformCopyInitialization(Entity,
3739 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00003740 LHS);
Douglas Gregorb65a4582010-05-19 23:40:50 +00003741 if (LHSCopy.isInvalid())
3742 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003743
3744 ExprResult RHSCopy = PerformCopyInitialization(Entity,
3745 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00003746 RHS);
Douglas Gregorb65a4582010-05-19 23:40:50 +00003747 if (RHSCopy.isInvalid())
3748 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003749
John Wiegley429bb272011-04-08 18:41:53 +00003750 LHS = LHSCopy;
3751 RHS = RHSCopy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00003752 }
3753
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003754 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00003755 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003756
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003757 // Extension: conditional operator involving vector types.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003758 if (LTy->isVectorType() || RTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00003759 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003760
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003761 // -- The second and third operands have arithmetic or enumeration type;
3762 // the usual arithmetic conversions are performed to bring them to a
3763 // common type, and the result is of that type.
3764 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
3765 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00003766 if (LHS.isInvalid() || RHS.isInvalid())
3767 return QualType();
3768 return LHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003769 }
3770
3771 // -- The second and third operands have pointer type, or one has pointer
3772 // type and the other is a null pointer constant; pointer conversions
3773 // and qualification conversions are performed to bring them to their
3774 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00003775 // -- The second and third operands have pointer to member type, or one has
3776 // pointer to member type and the other is a null pointer constant;
3777 // pointer to member conversions and qualification conversions are
3778 // performed to bring them to a common type, whose cv-qualification
3779 // shall match the cv-qualification of either the second or the third
3780 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003781 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003782 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003783 isSFINAEContext()? 0 : &NonStandardCompositeType);
3784 if (!Composite.isNull()) {
3785 if (NonStandardCompositeType)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003786 Diag(QuestionLoc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003787 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
3788 << LTy << RTy << Composite
John Wiegley429bb272011-04-08 18:41:53 +00003789 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003790
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003791 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003792 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003793
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003794 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00003795 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
3796 if (!Composite.isNull())
3797 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003798
Chandler Carruth7ef93242011-02-19 00:13:59 +00003799 // Check if we are using a null with a non-pointer type.
John Wiegley429bb272011-04-08 18:41:53 +00003800 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth7ef93242011-02-19 00:13:59 +00003801 return QualType();
3802
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003803 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00003804 << LHS.get()->getType() << RHS.get()->getType()
3805 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003806 return QualType();
3807}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003808
3809/// \brief Find a merged pointer type and convert the two expressions to it.
3810///
Douglas Gregor20b3e992009-08-24 17:42:35 +00003811/// This finds the composite pointer type (or member pointer type) for @p E1
3812/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
3813/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003814/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003815///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003816/// \param Loc The location of the operator requiring these two expressions to
3817/// be converted to the composite pointer type.
3818///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003819/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
3820/// a non-standard (but still sane) composite type to which both expressions
3821/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
3822/// will be set true.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003823QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003824 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003825 bool *NonStandardCompositeType) {
3826 if (NonStandardCompositeType)
3827 *NonStandardCompositeType = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003828
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003829 assert(getLangOptions().CPlusPlus && "This function assumes C++");
3830 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003831
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00003832 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
3833 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00003834 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003835
3836 // C++0x 5.9p2
3837 // Pointer conversions and qualification conversions are performed on
3838 // pointer operands to bring them to their composite pointer type. If
3839 // one operand is a null pointer constant, the composite pointer type is
3840 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00003841 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003842 if (T2->isMemberPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00003843 E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003844 else
John Wiegley429bb272011-04-08 18:41:53 +00003845 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003846 return T2;
3847 }
Douglas Gregorce940492009-09-25 04:25:58 +00003848 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003849 if (T1->isMemberPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00003850 E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003851 else
John Wiegley429bb272011-04-08 18:41:53 +00003852 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003853 return T1;
3854 }
Mike Stump1eb44332009-09-09 15:08:12 +00003855
Douglas Gregor20b3e992009-08-24 17:42:35 +00003856 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003857 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
3858 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003859 return QualType();
3860
3861 // Otherwise, of one of the operands has type "pointer to cv1 void," then
3862 // the other has type "pointer to cv2 T" and the composite pointer type is
3863 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
3864 // Otherwise, the composite pointer type is a pointer type similar to the
3865 // type of one of the operands, with a cv-qualification signature that is
3866 // the union of the cv-qualification signatures of the operand types.
3867 // In practice, the first part here is redundant; it's subsumed by the second.
3868 // What we do here is, we build the two possible composite types, and try the
3869 // conversions in both directions. If only one works, or if the two composite
3870 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00003871 // FIXME: extended qualifiers?
Chris Lattner5f9e2722011-07-23 10:55:15 +00003872 typedef SmallVector<unsigned, 4> QualifierVector;
Sebastian Redla439e6f2009-11-16 21:03:45 +00003873 QualifierVector QualifierUnion;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003874 typedef SmallVector<std::pair<const Type *, const Type *>, 4>
Sebastian Redla439e6f2009-11-16 21:03:45 +00003875 ContainingClassVector;
3876 ContainingClassVector MemberOfClass;
3877 QualType Composite1 = Context.getCanonicalType(T1),
3878 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003879 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00003880 do {
3881 const PointerType *Ptr1, *Ptr2;
3882 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3883 (Ptr2 = Composite2->getAs<PointerType>())) {
3884 Composite1 = Ptr1->getPointeeType();
3885 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003886
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003887 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003888 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003889 if (NonStandardCompositeType &&
3890 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3891 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003892
Douglas Gregor20b3e992009-08-24 17:42:35 +00003893 QualifierUnion.push_back(
3894 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3895 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3896 continue;
3897 }
Mike Stump1eb44332009-09-09 15:08:12 +00003898
Douglas Gregor20b3e992009-08-24 17:42:35 +00003899 const MemberPointerType *MemPtr1, *MemPtr2;
3900 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3901 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3902 Composite1 = MemPtr1->getPointeeType();
3903 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003904
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003905 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003906 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003907 if (NonStandardCompositeType &&
3908 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3909 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003910
Douglas Gregor20b3e992009-08-24 17:42:35 +00003911 QualifierUnion.push_back(
3912 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3913 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
3914 MemPtr2->getClass()));
3915 continue;
3916 }
Mike Stump1eb44332009-09-09 15:08:12 +00003917
Douglas Gregor20b3e992009-08-24 17:42:35 +00003918 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00003919
Douglas Gregor20b3e992009-08-24 17:42:35 +00003920 // Cannot unwrap any more types.
3921 break;
3922 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00003923
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003924 if (NeedConstBefore && NonStandardCompositeType) {
3925 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003926 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003927 // requirements of C++ [conv.qual]p4 bullet 3.
3928 for (unsigned I = 0; I != NeedConstBefore; ++I) {
3929 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
3930 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
3931 *NonStandardCompositeType = true;
3932 }
3933 }
3934 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003935
Douglas Gregor20b3e992009-08-24 17:42:35 +00003936 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003937 ContainingClassVector::reverse_iterator MOC
3938 = MemberOfClass.rbegin();
3939 for (QualifierVector::reverse_iterator
3940 I = QualifierUnion.rbegin(),
3941 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00003942 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00003943 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00003944 if (MOC->first && MOC->second) {
3945 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00003946 Composite1 = Context.getMemberPointerType(
3947 Context.getQualifiedType(Composite1, Quals),
3948 MOC->first);
3949 Composite2 = Context.getMemberPointerType(
3950 Context.getQualifiedType(Composite2, Quals),
3951 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00003952 } else {
3953 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00003954 Composite1
3955 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
3956 Composite2
3957 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00003958 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003959 }
3960
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003961 // Try to convert to the first composite pointer type.
3962 InitializedEntity Entity1
3963 = InitializedEntity::InitializeTemporary(Composite1);
3964 InitializationKind Kind
3965 = InitializationKind::CreateCopy(Loc, SourceLocation());
3966 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
3967 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00003968
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003969 if (E1ToC1 && E2ToC1) {
3970 // Conversion to Composite1 is viable.
3971 if (!Context.hasSameType(Composite1, Composite2)) {
3972 // Composite2 is a different type from Composite1. Check whether
3973 // Composite2 is also viable.
3974 InitializedEntity Entity2
3975 = InitializedEntity::InitializeTemporary(Composite2);
3976 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3977 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3978 if (E1ToC2 && E2ToC2) {
3979 // Both Composite1 and Composite2 are viable and are different;
3980 // this is an ambiguity.
3981 return QualType();
3982 }
3983 }
3984
3985 // Convert E1 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00003986 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00003987 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003988 if (E1Result.isInvalid())
3989 return QualType();
3990 E1 = E1Result.takeAs<Expr>();
3991
3992 // Convert E2 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00003993 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00003994 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003995 if (E2Result.isInvalid())
3996 return QualType();
3997 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003998
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003999 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004000 }
4001
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004002 // Check whether Composite2 is viable.
4003 InitializedEntity Entity2
4004 = InitializedEntity::InitializeTemporary(Composite2);
4005 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4006 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4007 if (!E1ToC2 || !E2ToC2)
4008 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004009
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004010 // Convert E1 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00004011 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00004012 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004013 if (E1Result.isInvalid())
4014 return QualType();
4015 E1 = E1Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004016
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004017 // Convert E2 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00004018 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00004019 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004020 if (E2Result.isInvalid())
4021 return QualType();
4022 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004023
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004024 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004025}
Anders Carlsson165a0a02009-05-17 18:41:29 +00004026
John McCall60d7b3a2010-08-24 06:29:42 +00004027ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor19cc1c72010-11-01 21:10:29 +00004028 if (!E)
4029 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004030
John McCallf85e1932011-06-15 23:02:42 +00004031 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
4032
4033 // If the result is a glvalue, we shouldn't bind it.
4034 if (!E->isRValue())
Anders Carlsson089c2602009-08-15 23:41:35 +00004035 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004036
John McCallf85e1932011-06-15 23:02:42 +00004037 // In ARC, calls that return a retainable type can return retained,
4038 // in which case we have to insert a consuming cast.
4039 if (getLangOptions().ObjCAutoRefCount &&
4040 E->getType()->isObjCRetainableType()) {
4041
4042 bool ReturnsRetained;
4043
4044 // For actual calls, we compute this by examining the type of the
4045 // called value.
4046 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
4047 Expr *Callee = Call->getCallee()->IgnoreParens();
4048 QualType T = Callee->getType();
4049
4050 if (T == Context.BoundMemberTy) {
4051 // Handle pointer-to-members.
4052 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
4053 T = BinOp->getRHS()->getType();
4054 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
4055 T = Mem->getMemberDecl()->getType();
4056 }
4057
4058 if (const PointerType *Ptr = T->getAs<PointerType>())
4059 T = Ptr->getPointeeType();
4060 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
4061 T = Ptr->getPointeeType();
4062 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
4063 T = MemPtr->getPointeeType();
4064
4065 const FunctionType *FTy = T->getAs<FunctionType>();
4066 assert(FTy && "call to value not of function type?");
4067 ReturnsRetained = FTy->getExtInfo().getProducesResult();
4068
4069 // ActOnStmtExpr arranges things so that StmtExprs of retainable
4070 // type always produce a +1 object.
4071 } else if (isa<StmtExpr>(E)) {
4072 ReturnsRetained = true;
4073
4074 // For message sends and property references, we try to find an
4075 // actual method. FIXME: we should infer retention by selector in
4076 // cases where we don't have an actual method.
4077 } else {
John McCallfc4b1912011-08-03 07:02:44 +00004078 ObjCMethodDecl *D = 0;
John McCallf85e1932011-06-15 23:02:42 +00004079 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
4080 D = Send->getMethodDecl();
4081 } else {
4082 CastExpr *CE = cast<CastExpr>(E);
John McCallf85e1932011-06-15 23:02:42 +00004083 assert(CE->getCastKind() == CK_GetObjCProperty);
4084 const ObjCPropertyRefExpr *PRE = CE->getSubExpr()->getObjCProperty();
4085 D = (PRE->isImplicitProperty() ? PRE->getImplicitPropertyGetter() : 0);
4086 }
4087
4088 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCallfc4b1912011-08-03 07:02:44 +00004089
4090 // Don't do reclaims on performSelector calls; despite their
4091 // return type, the invoked method doesn't necessarily actually
4092 // return an object.
4093 if (!ReturnsRetained &&
4094 D && D->getMethodFamily() == OMF_performSelector)
4095 return Owned(E);
John McCallf85e1932011-06-15 23:02:42 +00004096 }
4097
John McCall7e5e5f42011-07-07 06:58:02 +00004098 ExprNeedsCleanups = true;
4099
John McCall33e56f32011-09-10 06:18:15 +00004100 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
4101 : CK_ARCReclaimReturnedObject);
John McCall7e5e5f42011-07-07 06:58:02 +00004102 return Owned(ImplicitCastExpr::Create(Context, E->getType(), ck, E, 0,
4103 VK_RValue));
John McCallf85e1932011-06-15 23:02:42 +00004104 }
4105
4106 if (!getLangOptions().CPlusPlus)
4107 return Owned(E);
Douglas Gregor51326552009-12-24 18:51:59 +00004108
Ted Kremenek6217b802009-07-29 21:53:49 +00004109 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00004110 if (!RT)
4111 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004112
John McCall86ff3082010-02-04 22:26:26 +00004113 // That should be enough to guarantee that this type is complete.
4114 // If it has a trivial destructor, we can avoid the extra copy.
Jeffrey Yasskinb7ee2e52011-01-27 19:17:54 +00004115 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall507384f2010-08-12 02:40:37 +00004116 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall86ff3082010-02-04 22:26:26 +00004117 return Owned(E);
4118
John McCallf85e1932011-06-15 23:02:42 +00004119 CXXDestructorDecl *Destructor = LookupDestructor(RD);
4120
4121 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
4122 if (Destructor) {
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00004123 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00004124 CheckDestructorAccess(E->getExprLoc(), Destructor,
4125 PDiag(diag::err_access_dtor_temp)
4126 << E->getType());
John McCallf85e1932011-06-15 23:02:42 +00004127
4128 ExprTemporaries.push_back(Temp);
4129 ExprNeedsCleanups = true;
John McCallc91cc662010-04-07 00:41:46 +00004130 }
Anders Carlssondef11992009-05-30 20:36:53 +00004131 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
4132}
4133
John McCall4765fa02010-12-06 08:20:24 +00004134Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00004135 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00004136
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00004137 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
4138 assert(ExprTemporaries.size() >= FirstTemporary);
John McCallf85e1932011-06-15 23:02:42 +00004139 assert(ExprNeedsCleanups || ExprTemporaries.size() == FirstTemporary);
4140 if (!ExprNeedsCleanups)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00004141 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00004142
John McCall4765fa02010-12-06 08:20:24 +00004143 Expr *E = ExprWithCleanups::Create(Context, SubExpr,
John McCallf85e1932011-06-15 23:02:42 +00004144 ExprTemporaries.begin() + FirstTemporary,
John McCall4765fa02010-12-06 08:20:24 +00004145 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00004146 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
4147 ExprTemporaries.end());
John McCallf85e1932011-06-15 23:02:42 +00004148 ExprNeedsCleanups = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004149
Anders Carlsson99ba36d2009-06-05 15:38:08 +00004150 return E;
4151}
4152
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004153ExprResult
John McCall4765fa02010-12-06 08:20:24 +00004154Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregor90f93822009-12-22 22:17:25 +00004155 if (SubExpr.isInvalid())
4156 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004157
John McCall4765fa02010-12-06 08:20:24 +00004158 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregor90f93822009-12-22 22:17:25 +00004159}
4160
John McCall4765fa02010-12-06 08:20:24 +00004161Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004162 assert(SubStmt && "sub statement can't be null!");
4163
John McCallf85e1932011-06-15 23:02:42 +00004164 if (!ExprNeedsCleanups)
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004165 return SubStmt;
4166
4167 // FIXME: In order to attach the temporaries, wrap the statement into
4168 // a StmtExpr; currently this is only used for asm statements.
4169 // This is hacky, either create a new CXXStmtWithTemporaries statement or
4170 // a new AsmStmtWithTemporaries.
4171 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
4172 SourceLocation(),
4173 SourceLocation());
4174 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
4175 SourceLocation());
John McCall4765fa02010-12-06 08:20:24 +00004176 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004177}
4178
John McCall60d7b3a2010-08-24 06:29:42 +00004179ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004180Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallb3d87482010-08-24 05:47:05 +00004181 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00004182 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004183 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004184 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00004185 if (Result.isInvalid()) return ExprError();
4186 Base = Result.get();
Mike Stump1eb44332009-09-09 15:08:12 +00004187
John McCall9ae2f072010-08-23 23:25:46 +00004188 QualType BaseType = Base->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00004189 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004190 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00004191 // If we have a pointer to a dependent type and are using the -> operator,
4192 // the object type is the type that the pointer points to. We might still
4193 // have enough information about that type to do something useful.
4194 if (OpKind == tok::arrow)
4195 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4196 BaseType = Ptr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004197
John McCallb3d87482010-08-24 05:47:05 +00004198 ObjectType = ParsedType::make(BaseType);
Douglas Gregord4dca082010-02-24 18:44:31 +00004199 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00004200 return Owned(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004201 }
Mike Stump1eb44332009-09-09 15:08:12 +00004202
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004203 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00004204 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004205 // returned, with the original second operand.
4206 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00004207 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00004208 llvm::SmallPtrSet<CanQualType,8> CTypes;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004209 SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00004210 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004211
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004212 while (BaseType->isRecordType()) {
John McCall9ae2f072010-08-23 23:25:46 +00004213 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
4214 if (Result.isInvalid())
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004215 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00004216 Base = Result.get();
4217 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonde699e52009-10-13 22:55:59 +00004218 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCall9ae2f072010-08-23 23:25:46 +00004219 BaseType = Base->getType();
John McCallc4e83212009-09-30 01:01:30 +00004220 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00004221 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00004222 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00004223 for (unsigned i = 0; i < Locations.size(); i++)
4224 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00004225 return ExprError();
4226 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004227 }
Mike Stump1eb44332009-09-09 15:08:12 +00004228
Douglas Gregor31658df2009-11-20 19:58:21 +00004229 if (BaseType->isPointerType())
4230 BaseType = BaseType->getPointeeType();
4231 }
Mike Stump1eb44332009-09-09 15:08:12 +00004232
4233 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004234 // vector types or Objective-C interfaces. Just return early and let
4235 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00004236 if (!BaseType->isRecordType()) {
4237 // C++ [basic.lookup.classref]p2:
4238 // [...] If the type of the object expression is of pointer to scalar
4239 // type, the unqualified-id is looked up in the context of the complete
4240 // postfix-expression.
Douglas Gregord4dca082010-02-24 18:44:31 +00004241 //
4242 // This also indicates that we should be parsing a
4243 // pseudo-destructor-name.
John McCallb3d87482010-08-24 05:47:05 +00004244 ObjectType = ParsedType();
Douglas Gregord4dca082010-02-24 18:44:31 +00004245 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00004246 return Owned(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00004247 }
Mike Stump1eb44332009-09-09 15:08:12 +00004248
Douglas Gregor03c57052009-11-17 05:17:33 +00004249 // The object type must be complete (or dependent).
4250 if (!BaseType->isDependentType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004251 RequireCompleteType(OpLoc, BaseType,
Douglas Gregor03c57052009-11-17 05:17:33 +00004252 PDiag(diag::err_incomplete_member_access)))
4253 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004254
Douglas Gregorc68afe22009-09-03 21:38:09 +00004255 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004256 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00004257 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00004258 // type C (or of pointer to a class type C), the unqualified-id is looked
4259 // up in the scope of class C. [...]
John McCallb3d87482010-08-24 05:47:05 +00004260 ObjectType = ParsedType::make(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00004261 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004262}
4263
John McCall60d7b3a2010-08-24 06:29:42 +00004264ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCall9ae2f072010-08-23 23:25:46 +00004265 Expr *MemExpr) {
Douglas Gregor77549082010-02-24 21:29:12 +00004266 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCall9ae2f072010-08-23 23:25:46 +00004267 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
4268 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregor849b2432010-03-31 17:46:05 +00004269 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004270
Douglas Gregor77549082010-02-24 21:29:12 +00004271 return ActOnCallExpr(/*Scope*/ 0,
John McCall9ae2f072010-08-23 23:25:46 +00004272 MemExpr,
Douglas Gregor77549082010-02-24 21:29:12 +00004273 /*LPLoc*/ ExpectedLParenLoc,
John McCallf312b1e2010-08-26 23:41:50 +00004274 MultiExprArg(),
Douglas Gregor77549082010-02-24 21:29:12 +00004275 /*RPLoc*/ ExpectedLParenLoc);
4276}
Douglas Gregord4dca082010-02-24 18:44:31 +00004277
John McCall60d7b3a2010-08-24 06:29:42 +00004278ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00004279 SourceLocation OpLoc,
4280 tok::TokenKind OpKind,
4281 const CXXScopeSpec &SS,
4282 TypeSourceInfo *ScopeTypeInfo,
4283 SourceLocation CCLoc,
4284 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004285 PseudoDestructorTypeStorage Destructed,
John McCall2d9f5fa2011-02-25 05:21:17 +00004286 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004287 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004288
Douglas Gregorb57fb492010-02-24 22:38:50 +00004289 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004290 // The left-hand side of the dot operator shall be of scalar type. The
Douglas Gregorb57fb492010-02-24 22:38:50 +00004291 // left-hand side of the arrow operator shall be of pointer to scalar type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004292 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00004293 QualType ObjectType = Base->getType();
Douglas Gregorb57fb492010-02-24 22:38:50 +00004294 if (OpKind == tok::arrow) {
4295 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4296 ObjectType = Ptr->getPointeeType();
John McCall9ae2f072010-08-23 23:25:46 +00004297 } else if (!Base->isTypeDependent()) {
Douglas Gregorb57fb492010-02-24 22:38:50 +00004298 // The user wrote "p->" when she probably meant "p."; fix it.
4299 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4300 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00004301 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb57fb492010-02-24 22:38:50 +00004302 if (isSFINAEContext())
4303 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004304
Douglas Gregorb57fb492010-02-24 22:38:50 +00004305 OpKind = tok::period;
4306 }
4307 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004308
Douglas Gregorb57fb492010-02-24 22:38:50 +00004309 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
4310 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
John McCall9ae2f072010-08-23 23:25:46 +00004311 << ObjectType << Base->getSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00004312 return ExprError();
4313 }
4314
4315 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004316 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb57fb492010-02-24 22:38:50 +00004317 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004318 if (DestructedTypeInfo) {
4319 QualType DestructedType = DestructedTypeInfo->getType();
4320 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004321 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCallf85e1932011-06-15 23:02:42 +00004322 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
4323 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
4324 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
4325 << ObjectType << DestructedType << Base->getSourceRange()
4326 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004327
John McCallf85e1932011-06-15 23:02:42 +00004328 // Recover by setting the destructed type to the object type.
4329 DestructedType = ObjectType;
4330 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004331 DestructedTypeStart);
John McCallf85e1932011-06-15 23:02:42 +00004332 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4333 } else if (DestructedType.getObjCLifetime() !=
4334 ObjectType.getObjCLifetime()) {
4335
4336 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
4337 // Okay: just pretend that the user provided the correctly-qualified
4338 // type.
4339 } else {
4340 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
4341 << ObjectType << DestructedType << Base->getSourceRange()
4342 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
4343 }
4344
4345 // Recover by setting the destructed type to the object type.
4346 DestructedType = ObjectType;
4347 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
4348 DestructedTypeStart);
4349 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4350 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004351 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00004352 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004353
Douglas Gregorb57fb492010-02-24 22:38:50 +00004354 // C++ [expr.pseudo]p2:
4355 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
4356 // form
4357 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004358 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb57fb492010-02-24 22:38:50 +00004359 //
4360 // shall designate the same scalar type.
4361 if (ScopeTypeInfo) {
4362 QualType ScopeType = ScopeTypeInfo->getType();
4363 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00004364 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004365
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004366 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00004367 diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00004368 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004369 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004370
Douglas Gregorb57fb492010-02-24 22:38:50 +00004371 ScopeType = QualType();
4372 ScopeTypeInfo = 0;
4373 }
4374 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004375
John McCall9ae2f072010-08-23 23:25:46 +00004376 Expr *Result
4377 = new (Context) CXXPseudoDestructorExpr(Context, Base,
4378 OpKind == tok::arrow, OpLoc,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00004379 SS.getWithLocInContext(Context),
John McCall9ae2f072010-08-23 23:25:46 +00004380 ScopeTypeInfo,
4381 CCLoc,
4382 TildeLoc,
4383 Destructed);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004384
Douglas Gregorb57fb492010-02-24 22:38:50 +00004385 if (HasTrailingLParen)
John McCall9ae2f072010-08-23 23:25:46 +00004386 return Owned(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004387
John McCall9ae2f072010-08-23 23:25:46 +00004388 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor77549082010-02-24 21:29:12 +00004389}
4390
John McCall60d7b3a2010-08-24 06:29:42 +00004391ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00004392 SourceLocation OpLoc,
4393 tok::TokenKind OpKind,
4394 CXXScopeSpec &SS,
4395 UnqualifiedId &FirstTypeName,
4396 SourceLocation CCLoc,
4397 SourceLocation TildeLoc,
4398 UnqualifiedId &SecondTypeName,
4399 bool HasTrailingLParen) {
Douglas Gregor77549082010-02-24 21:29:12 +00004400 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4401 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4402 "Invalid first type name in pseudo-destructor");
4403 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4404 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4405 "Invalid second type name in pseudo-destructor");
4406
Douglas Gregor77549082010-02-24 21:29:12 +00004407 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004408 // The left-hand side of the dot operator shall be of scalar type. The
Douglas Gregor77549082010-02-24 21:29:12 +00004409 // left-hand side of the arrow operator shall be of pointer to scalar type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004410 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00004411 QualType ObjectType = Base->getType();
Douglas Gregor77549082010-02-24 21:29:12 +00004412 if (OpKind == tok::arrow) {
4413 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4414 ObjectType = Ptr->getPointeeType();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004415 } else if (!ObjectType->isDependentType()) {
Douglas Gregor77549082010-02-24 21:29:12 +00004416 // The user wrote "p->" when she probably meant "p."; fix it.
4417 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004418 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00004419 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor77549082010-02-24 21:29:12 +00004420 if (isSFINAEContext())
4421 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004422
Douglas Gregor77549082010-02-24 21:29:12 +00004423 OpKind = tok::period;
4424 }
4425 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004426
4427 // Compute the object type that we should use for name lookup purposes. Only
4428 // record types and dependent types matter.
John McCallb3d87482010-08-24 05:47:05 +00004429 ParsedType ObjectTypePtrForLookup;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004430 if (!SS.isSet()) {
John McCall2d9f5fa2011-02-25 05:21:17 +00004431 if (ObjectType->isRecordType())
4432 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallb3d87482010-08-24 05:47:05 +00004433 else if (ObjectType->isDependentType())
4434 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004435 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004436
4437 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb57fb492010-02-24 22:38:50 +00004438 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00004439 QualType DestructedType;
4440 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004441 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00004442 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004443 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00004444 SecondTypeName.StartLocation,
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +00004445 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004446 if (!T &&
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004447 ((SS.isSet() && !computeDeclContext(SS, false)) ||
4448 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004449 // The name of the type being destroyed is a dependent name, and we
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004450 // couldn't find anything useful in scope. Just store the identifier and
4451 // it's location, and we'll perform (qualified) name lookup again at
4452 // template instantiation time.
4453 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
4454 SecondTypeName.StartLocation);
4455 } else if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004456 Diag(SecondTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00004457 diag::err_pseudo_dtor_destructor_non_type)
4458 << SecondTypeName.Identifier << ObjectType;
4459 if (isSFINAEContext())
4460 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004461
Douglas Gregor77549082010-02-24 21:29:12 +00004462 // Recover by assuming we had the right type all along.
4463 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004464 } else
Douglas Gregor77549082010-02-24 21:29:12 +00004465 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004466 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00004467 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00004468 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004469 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4470 TemplateId->getTemplateArgs(),
4471 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00004472 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4473 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004474 TemplateId->TemplateNameLoc,
4475 TemplateId->LAngleLoc,
4476 TemplateArgsPtr,
4477 TemplateId->RAngleLoc);
4478 if (T.isInvalid() || !T.get()) {
4479 // Recover by assuming we had the right type all along.
4480 DestructedType = ObjectType;
4481 } else
4482 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004483 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004484
4485 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb57fb492010-02-24 22:38:50 +00004486 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004487 if (!DestructedType.isNull()) {
4488 if (!DestructedTypeInfo)
4489 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004490 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004491 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4492 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004493
Douglas Gregorb57fb492010-02-24 22:38:50 +00004494 // Convert the name of the scope type (the type prior to '::') into a type.
4495 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00004496 QualType ScopeType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004497 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor77549082010-02-24 21:29:12 +00004498 FirstTypeName.Identifier) {
4499 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004500 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00004501 FirstTypeName.StartLocation,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00004502 S, &SS, true, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00004503 if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004504 Diag(FirstTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00004505 diag::err_pseudo_dtor_destructor_non_type)
4506 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004507
Douglas Gregorb57fb492010-02-24 22:38:50 +00004508 if (isSFINAEContext())
4509 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004510
Douglas Gregorb57fb492010-02-24 22:38:50 +00004511 // Just drop this type. It's unnecessary anyway.
4512 ScopeType = QualType();
4513 } else
4514 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004515 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00004516 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00004517 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004518 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4519 TemplateId->getTemplateArgs(),
4520 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00004521 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4522 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004523 TemplateId->TemplateNameLoc,
4524 TemplateId->LAngleLoc,
4525 TemplateArgsPtr,
4526 TemplateId->RAngleLoc);
4527 if (T.isInvalid() || !T.get()) {
4528 // Recover by dropping this type.
4529 ScopeType = QualType();
4530 } else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004531 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004532 }
4533 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004534
Douglas Gregorb4a418f2010-02-24 23:02:30 +00004535 if (!ScopeType.isNull() && !ScopeTypeInfo)
4536 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
4537 FirstTypeName.StartLocation);
4538
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004539
John McCall9ae2f072010-08-23 23:25:46 +00004540 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00004541 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004542 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00004543}
4544
John Wiegley429bb272011-04-08 18:41:53 +00004545ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004546 CXXMethodDecl *Method,
4547 bool HadMultipleCandidates) {
John Wiegley429bb272011-04-08 18:41:53 +00004548 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
4549 FoundDecl, Method);
4550 if (Exp.isInvalid())
Douglas Gregorf2ae5262011-01-20 00:18:04 +00004551 return true;
Eli Friedman772fffa2009-12-09 04:53:56 +00004552
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004553 MemberExpr *ME =
John Wiegley429bb272011-04-08 18:41:53 +00004554 new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
John McCallf89e55a2010-11-18 06:31:45 +00004555 SourceLocation(), Method->getType(),
4556 VK_RValue, OK_Ordinary);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004557 if (HadMultipleCandidates)
4558 ME->setHadMultipleCandidates(true);
4559
John McCallf89e55a2010-11-18 06:31:45 +00004560 QualType ResultType = Method->getResultType();
4561 ExprValueKind VK = Expr::getValueKindForType(ResultType);
4562 ResultType = ResultType.getNonLValueExprType(Context);
4563
John Wiegley429bb272011-04-08 18:41:53 +00004564 MarkDeclarationReferenced(Exp.get()->getLocStart(), Method);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004565 CXXMemberCallExpr *CE =
John McCallf89e55a2010-11-18 06:31:45 +00004566 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
John Wiegley429bb272011-04-08 18:41:53 +00004567 Exp.get()->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00004568 return CE;
4569}
4570
Sebastian Redl2e156222010-09-10 20:55:43 +00004571ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4572 SourceLocation RParen) {
Sebastian Redl2e156222010-09-10 20:55:43 +00004573 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
4574 Operand->CanThrow(Context),
4575 KeyLoc, RParen));
4576}
4577
4578ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
4579 Expr *Operand, SourceLocation RParen) {
4580 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl02bc21a2010-09-10 20:55:37 +00004581}
4582
John McCallf6a16482010-12-04 03:47:34 +00004583/// Perform the conversions required for an expression used in a
4584/// context that ignores the result.
John Wiegley429bb272011-04-08 18:41:53 +00004585ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCalla878cda2010-12-02 02:07:15 +00004586 // C99 6.3.2.1:
4587 // [Except in specific positions,] an lvalue that does not have
4588 // array type is converted to the value stored in the
4589 // designated object (and is no longer an lvalue).
John McCalle6d134b2011-06-27 21:24:11 +00004590 if (E->isRValue()) {
4591 // In C, function designators (i.e. expressions of function type)
4592 // are r-values, but we still want to do function-to-pointer decay
4593 // on them. This is both technically correct and convenient for
4594 // some clients.
4595 if (!getLangOptions().CPlusPlus && E->getType()->isFunctionType())
4596 return DefaultFunctionArrayConversion(E);
4597
4598 return Owned(E);
4599 }
John McCalla878cda2010-12-02 02:07:15 +00004600
John McCallf6a16482010-12-04 03:47:34 +00004601 // We always want to do this on ObjC property references.
4602 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley429bb272011-04-08 18:41:53 +00004603 ExprResult Res = ConvertPropertyForRValue(E);
4604 if (Res.isInvalid()) return Owned(E);
4605 E = Res.take();
4606 if (E->isRValue()) return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004607 }
4608
4609 // Otherwise, this rule does not apply in C++, at least not for the moment.
John Wiegley429bb272011-04-08 18:41:53 +00004610 if (getLangOptions().CPlusPlus) return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004611
4612 // GCC seems to also exclude expressions of incomplete enum type.
4613 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
4614 if (!T->getDecl()->isComplete()) {
4615 // FIXME: stupid workaround for a codegen bug!
John Wiegley429bb272011-04-08 18:41:53 +00004616 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
4617 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004618 }
4619 }
4620
John Wiegley429bb272011-04-08 18:41:53 +00004621 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
4622 if (Res.isInvalid())
4623 return Owned(E);
4624 E = Res.take();
4625
John McCall85515d62010-12-04 12:29:11 +00004626 if (!E->getType()->isVoidType())
4627 RequireCompleteType(E->getExprLoc(), E->getType(),
4628 diag::err_incomplete_type);
John Wiegley429bb272011-04-08 18:41:53 +00004629 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004630}
4631
John Wiegley429bb272011-04-08 18:41:53 +00004632ExprResult Sema::ActOnFinishFullExpr(Expr *FE) {
4633 ExprResult FullExpr = Owned(FE);
4634
4635 if (!FullExpr.get())
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00004636 return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00004637
John Wiegley429bb272011-04-08 18:41:53 +00004638 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregord0937222010-12-13 22:49:22 +00004639 return ExprError();
4640
John McCallfb8721c2011-04-10 19:13:55 +00004641 FullExpr = CheckPlaceholderExpr(FullExpr.take());
4642 if (FullExpr.isInvalid())
4643 return ExprError();
Douglas Gregor353ee242011-03-07 02:05:23 +00004644
John Wiegley429bb272011-04-08 18:41:53 +00004645 FullExpr = IgnoredValueConversions(FullExpr.take());
4646 if (FullExpr.isInvalid())
4647 return ExprError();
4648
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004649 CheckImplicitConversions(FullExpr.get(), FullExpr.get()->getExprLoc());
John McCall4765fa02010-12-06 08:20:24 +00004650 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson165a0a02009-05-17 18:41:29 +00004651}
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004652
4653StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
4654 if (!FullStmt) return StmtError();
4655
John McCall4765fa02010-12-06 08:20:24 +00004656 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004657}
Francois Pichet1e862692011-05-06 20:48:22 +00004658
4659bool Sema::CheckMicrosoftIfExistsSymbol(CXXScopeSpec &SS,
4660 UnqualifiedId &Name) {
4661 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
4662 DeclarationName TargetName = TargetNameInfo.getName();
4663 if (!TargetName)
4664 return false;
4665
4666 // Do the redeclaration lookup in the current scope.
4667 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
4668 Sema::NotForRedeclaration);
4669 R.suppressDiagnostics();
4670 LookupParsedName(R, getCurScope(), &SS);
4671 return !R.empty();
4672}