blob: 919ef06957c42da225ea2383e8e8c0bd43cdec01 [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"
Nick Lewyckyfca84b22012-01-24 21:15:41 +000023#include "clang/AST/CharUnits.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000024#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000025#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000026#include "clang/AST/ExprCXX.h"
Fariborz Jahaniand4266622010-06-16 18:56:04 +000027#include "clang/AST/ExprObjC.h"
Douglas Gregorb57fb492010-02-24 22:38:50 +000028#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000029#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000030#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000031#include "clang/Lex/Preprocessor.h"
David Blaikie91ec7892011-12-16 16:03:09 +000032#include "TypeLocBuilder.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000033#include "llvm/ADT/STLExtras.h"
Chandler Carruth73e0a912011-05-01 07:23:17 +000034#include "llvm/Support/ErrorHandling.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000035using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000036using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000037
John McCallb3d87482010-08-24 05:47:05 +000038ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000039 IdentifierInfo &II,
John McCallb3d87482010-08-24 05:47:05 +000040 SourceLocation NameLoc,
41 Scope *S, CXXScopeSpec &SS,
42 ParsedType ObjectTypePtr,
43 bool EnteringContext) {
Douglas Gregor124b8782010-02-16 19:09:40 +000044 // Determine where to perform name lookup.
45
46 // FIXME: This area of the standard is very messy, and the current
47 // wording is rather unclear about which scopes we search for the
48 // destructor name; see core issues 399 and 555. Issue 399 in
49 // particular shows where the current description of destructor name
50 // lookup is completely out of line with existing practice, e.g.,
51 // this appears to be ill-formed:
52 //
53 // namespace N {
54 // template <typename T> struct S {
55 // ~S();
56 // };
57 // }
58 //
59 // void f(N::S<int>* s) {
60 // s->N::S<int>::~S();
61 // }
62 //
Douglas Gregor93649fd2010-02-23 00:15:22 +000063 // See also PR6358 and PR6359.
Sebastian Redlc0fee502010-07-07 23:17:38 +000064 // For this reason, we're currently only doing the C++03 version of this
65 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregor124b8782010-02-16 19:09:40 +000066 QualType SearchType;
67 DeclContext *LookupCtx = 0;
68 bool isDependent = false;
69 bool LookInScope = false;
70
71 // If we have an object type, it's because we are in a
72 // pseudo-destructor-expression or a member access expression, and
73 // we know what type we're looking for.
74 if (ObjectTypePtr)
75 SearchType = GetTypeFromParser(ObjectTypePtr);
76
77 if (SS.isSet()) {
Douglas Gregor93649fd2010-02-23 00:15:22 +000078 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000079
Douglas Gregor93649fd2010-02-23 00:15:22 +000080 bool AlreadySearched = false;
81 bool LookAtPrefix = true;
Sebastian Redlc0fee502010-07-07 23:17:38 +000082 // C++ [basic.lookup.qual]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000083 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redlc0fee502010-07-07 23:17:38 +000084 // the type-names are looked up as types in the scope designated by the
85 // nested-name-specifier. In a qualified-id of the form:
NAKAMURA Takumi00995302011-01-27 07:09:49 +000086 //
87 // ::[opt] nested-name-specifier ~ class-name
Sebastian Redlc0fee502010-07-07 23:17:38 +000088 //
89 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth5e895a82010-02-21 10:19:54 +000090 // a qualified-id of the form:
Douglas Gregor124b8782010-02-16 19:09:40 +000091 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +000092 // ::opt nested-name-specifier class-name :: ~ class-name
Douglas Gregor124b8782010-02-16 19:09:40 +000093 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000094 // the class-names are looked up as types in the scope designated by
Sebastian Redlc0fee502010-07-07 23:17:38 +000095 // the nested-name-specifier.
Douglas Gregor124b8782010-02-16 19:09:40 +000096 //
Sebastian Redlc0fee502010-07-07 23:17:38 +000097 // Here, we check the first case (completely) and determine whether the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000098 // code below is permitted to look at the prefix of the
Sebastian Redlc0fee502010-07-07 23:17:38 +000099 // nested-name-specifier.
100 DeclContext *DC = computeDeclContext(SS, EnteringContext);
101 if (DC && DC->isFileContext()) {
102 AlreadySearched = true;
103 LookupCtx = DC;
104 isDependent = false;
105 } else if (DC && isa<CXXRecordDecl>(DC))
106 LookAtPrefix = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000107
Sebastian Redlc0fee502010-07-07 23:17:38 +0000108 // The second case from the C++03 rules quoted further above.
Douglas Gregor93649fd2010-02-23 00:15:22 +0000109 NestedNameSpecifier *Prefix = 0;
110 if (AlreadySearched) {
111 // Nothing left to do.
112 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
113 CXXScopeSpec PrefixSS;
Douglas Gregor7e384942011-02-25 16:07:42 +0000114 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor93649fd2010-02-23 00:15:22 +0000115 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
116 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000117 } else if (ObjectTypePtr) {
Douglas Gregor124b8782010-02-16 19:09:40 +0000118 LookupCtx = computeDeclContext(SearchType);
119 isDependent = SearchType->isDependentType();
120 } else {
121 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000122 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregor124b8782010-02-16 19:09:40 +0000123 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000124
Douglas Gregoredc90502010-02-25 04:46:04 +0000125 LookInScope = false;
Douglas Gregor124b8782010-02-16 19:09:40 +0000126 } else if (ObjectTypePtr) {
127 // C++ [basic.lookup.classref]p3:
128 // If the unqualified-id is ~type-name, the type-name is looked up
129 // in the context of the entire postfix-expression. If the type T
130 // of the object expression is of a class type C, the type-name is
131 // also looked up in the scope of class C. At least one of the
132 // lookups shall find a name that refers to (possibly
133 // cv-qualified) T.
134 LookupCtx = computeDeclContext(SearchType);
135 isDependent = SearchType->isDependentType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000136 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregor124b8782010-02-16 19:09:40 +0000137 "Caller should have completed object type");
138
139 LookInScope = true;
140 } else {
141 // Perform lookup into the current scope (only).
142 LookInScope = true;
143 }
144
Douglas Gregor7ec18732011-03-04 22:32:08 +0000145 TypeDecl *NonMatchingTypeDecl = 0;
Douglas Gregor124b8782010-02-16 19:09:40 +0000146 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
147 for (unsigned Step = 0; Step != 2; ++Step) {
148 // Look for the name first in the computed lookup context (if we
Douglas Gregor7ec18732011-03-04 22:32:08 +0000149 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregor124b8782010-02-16 19:09:40 +0000150 // we're allowed to look there).
151 Found.clear();
152 if (Step == 0 && LookupCtx)
153 LookupQualifiedName(Found, LookupCtx);
Douglas Gregora2e7dd22010-02-25 01:56:36 +0000154 else if (Step == 1 && LookInScope && S)
Douglas Gregor124b8782010-02-16 19:09:40 +0000155 LookupName(Found, S);
156 else
157 continue;
158
159 // FIXME: Should we be suppressing ambiguities here?
160 if (Found.isAmbiguous())
John McCallb3d87482010-08-24 05:47:05 +0000161 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000162
163 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
164 QualType T = Context.getTypeDeclType(Type);
Douglas Gregor124b8782010-02-16 19:09:40 +0000165
166 if (SearchType.isNull() || SearchType->isDependentType() ||
167 Context.hasSameUnqualifiedType(T, SearchType)) {
168 // We found our type!
169
John McCallb3d87482010-08-24 05:47:05 +0000170 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000171 }
John Wiegley36784e72011-03-08 08:13:22 +0000172
Douglas Gregor7ec18732011-03-04 22:32:08 +0000173 if (!SearchType.isNull())
174 NonMatchingTypeDecl = Type;
Douglas Gregor124b8782010-02-16 19:09:40 +0000175 }
176
177 // If the name that we found is a class template name, and it is
178 // the same name as the template name in the last part of the
179 // nested-name-specifier (if present) or the object type, then
180 // this is the destructor for that class.
181 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000182 // issue 399, for which there isn't even an obvious direction.
Douglas Gregor124b8782010-02-16 19:09:40 +0000183 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
184 QualType MemberOfType;
185 if (SS.isSet()) {
186 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
187 // Figure out the type of the context, if it has one.
John McCall3cb0ebd2010-03-10 03:28:59 +0000188 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
189 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregor124b8782010-02-16 19:09:40 +0000190 }
191 }
192 if (MemberOfType.isNull())
193 MemberOfType = SearchType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000194
Douglas Gregor124b8782010-02-16 19:09:40 +0000195 if (MemberOfType.isNull())
196 continue;
197
198 // We're referring into a class template specialization. If the
199 // class template we found is the same as the template being
200 // specialized, we found what we are looking for.
201 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
202 if (ClassTemplateSpecializationDecl *Spec
203 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
204 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
205 Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000206 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000207 }
208
209 continue;
210 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000211
Douglas Gregor124b8782010-02-16 19:09:40 +0000212 // We're referring to an unresolved class template
213 // specialization. Determine whether we class template we found
214 // is the same as the template being specialized or, if we don't
215 // know which template is being specialized, that it at least
216 // has the same name.
217 if (const TemplateSpecializationType *SpecType
218 = MemberOfType->getAs<TemplateSpecializationType>()) {
219 TemplateName SpecName = SpecType->getTemplateName();
220
221 // The class template we found is the same template being
222 // specialized.
223 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
224 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000225 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000226
227 continue;
228 }
229
230 // The class template we found has the same name as the
231 // (dependent) template name being specialized.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000232 if (DependentTemplateName *DepTemplate
Douglas Gregor124b8782010-02-16 19:09:40 +0000233 = SpecName.getAsDependentTemplateName()) {
234 if (DepTemplate->isIdentifier() &&
235 DepTemplate->getIdentifier() == Template->getIdentifier())
John McCallb3d87482010-08-24 05:47:05 +0000236 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000237
238 continue;
239 }
240 }
241 }
242 }
243
244 if (isDependent) {
245 // We didn't find our type, but that's okay: it's dependent
246 // anyway.
Douglas Gregore29425b2011-02-28 22:42:13 +0000247
248 // FIXME: What if we have no nested-name-specifier?
249 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
250 SS.getWithLocInContext(Context),
251 II, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000252 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000253 }
254
Douglas Gregor7ec18732011-03-04 22:32:08 +0000255 if (NonMatchingTypeDecl) {
256 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
257 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
258 << T << SearchType;
259 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
260 << T;
261 } else if (ObjectTypePtr)
262 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000263 << &II;
Douglas Gregor124b8782010-02-16 19:09:40 +0000264 else
265 Diag(NameLoc, diag::err_destructor_class_name);
266
John McCallb3d87482010-08-24 05:47:05 +0000267 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000268}
269
David Blaikie53a75c02011-12-08 16:13:53 +0000270ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) {
David Blaikie4db8c442011-12-12 04:13:55 +0000271 if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType)
David Blaikie53a75c02011-12-08 16:13:53 +0000272 return ParsedType();
273 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype
274 && "only get destructor types from declspecs");
275 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
276 QualType SearchType = GetTypeFromParser(ObjectType);
277 if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(SearchType, T)) {
278 return ParsedType::make(T);
279 }
280
281 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
282 << T << SearchType;
283 return ParsedType();
284}
285
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000286/// \brief Build a C++ typeid expression with a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000287ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000288 SourceLocation TypeidLoc,
289 TypeSourceInfo *Operand,
290 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000291 // C++ [expr.typeid]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000292 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000293 // that is the operand of typeid are always ignored.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000294 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000295 // type, the class shall be completely-defined.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000296 Qualifiers Quals;
297 QualType T
298 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
299 Quals);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000300 if (T->getAs<RecordType>() &&
301 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
302 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000303
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000304 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
305 Operand,
306 SourceRange(TypeidLoc, RParenLoc)));
307}
308
309/// \brief Build a C++ typeid expression with an expression operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000310ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000311 SourceLocation TypeidLoc,
312 Expr *E,
313 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000314 if (E && !E->isTypeDependent()) {
John McCall6dbba4f2011-10-11 23:14:30 +0000315 if (E->getType()->isPlaceholderType()) {
316 ExprResult result = CheckPlaceholderExpr(E);
317 if (result.isInvalid()) return ExprError();
318 E = result.take();
319 }
320
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000321 QualType T = E->getType();
322 if (const RecordType *RecordT = T->getAs<RecordType>()) {
323 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
324 // C++ [expr.typeid]p3:
325 // [...] If the type of the expression is a class type, the class
326 // shall be completely-defined.
327 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
328 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000329
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000330 // C++ [expr.typeid]p3:
Sebastian Redl906082e2010-07-20 04:20:21 +0000331 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000332 // polymorphic class type [...] [the] expression is an unevaluated
333 // operand. [...]
Sebastian Redl906082e2010-07-20 04:20:21 +0000334 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
Eli Friedmanef331b72012-01-20 01:26:23 +0000335 // The subexpression is potentially evaluated; switch the context
336 // and recheck the subexpression.
337 ExprResult Result = TranformToPotentiallyEvaluated(E);
338 if (Result.isInvalid()) return ExprError();
339 E = Result.take();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000340
341 // We require a vtable to query the type at run time.
342 MarkVTableUsed(TypeidLoc, RecordD);
343 }
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000344 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000345
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000346 // C++ [expr.typeid]p4:
347 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000348 // cv-qualified type, the result of the typeid expression refers to a
349 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000350 // type.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000351 Qualifiers Quals;
352 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
353 if (!Context.hasSameType(T, UnqualT)) {
354 T = UnqualT;
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +0000355 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).take();
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000356 }
357 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000358
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000359 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCall9ae2f072010-08-23 23:25:46 +0000360 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000361 SourceRange(TypeidLoc, RParenLoc)));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000362}
363
364/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCall60d7b3a2010-08-24 06:29:42 +0000365ExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000366Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
367 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000368 // Find the std::type_info type.
Sebastian Redlce0682f2011-03-31 19:29:24 +0000369 if (!getStdNamespace())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000370 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000371
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000372 if (!CXXTypeInfoDecl) {
373 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
374 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
375 LookupQualifiedName(R, getStdNamespace());
376 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
377 if (!CXXTypeInfoDecl)
378 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
379 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000380
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000381 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000382
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000383 if (isType) {
384 // The operand is a type; handle it as such.
385 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +0000386 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
387 &TInfo);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000388 if (T.isNull())
389 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000390
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000391 if (!TInfo)
392 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000393
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000394 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000395 }
Mike Stump1eb44332009-09-09 15:08:12 +0000396
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000397 // The operand is an expression.
John McCall9ae2f072010-08-23 23:25:46 +0000398 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000399}
400
Francois Pichet6915c522010-12-27 01:32:00 +0000401/// Retrieve the UuidAttr associated with QT.
402static UuidAttr *GetUuidAttrOfType(QualType QT) {
403 // Optionally remove one level of pointer, reference or array indirection.
John McCallf4c73712011-01-19 06:33:43 +0000404 const Type *Ty = QT.getTypePtr();;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000405 if (QT->isPointerType() || QT->isReferenceType())
406 Ty = QT->getPointeeType().getTypePtr();
407 else if (QT->isArrayType())
408 Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
409
Francois Pichet8db75a22011-05-08 10:02:20 +0000410 // Loop all record redeclaration looking for an uuid attribute.
Francois Pichet6915c522010-12-27 01:32:00 +0000411 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Francois Pichet8db75a22011-05-08 10:02:20 +0000412 for (CXXRecordDecl::redecl_iterator I = RD->redecls_begin(),
413 E = RD->redecls_end(); I != E; ++I) {
414 if (UuidAttr *Uuid = I->getAttr<UuidAttr>())
Francois Pichet6915c522010-12-27 01:32:00 +0000415 return Uuid;
Francois Pichet6915c522010-12-27 01:32:00 +0000416 }
Francois Pichet8db75a22011-05-08 10:02:20 +0000417
Francois Pichet6915c522010-12-27 01:32:00 +0000418 return 0;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000419}
420
Francois Pichet01b7c302010-09-08 12:20:18 +0000421/// \brief Build a Microsoft __uuidof expression with a type operand.
422ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
423 SourceLocation TypeidLoc,
424 TypeSourceInfo *Operand,
425 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000426 if (!Operand->getType()->isDependentType()) {
427 if (!GetUuidAttrOfType(Operand->getType()))
428 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
429 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000430
Francois Pichet01b7c302010-09-08 12:20:18 +0000431 // FIXME: add __uuidof semantic analysis for type operand.
432 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
433 Operand,
434 SourceRange(TypeidLoc, RParenLoc)));
435}
436
437/// \brief Build a Microsoft __uuidof expression with an expression operand.
438ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
439 SourceLocation TypeidLoc,
440 Expr *E,
441 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000442 if (!E->getType()->isDependentType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000443 if (!GetUuidAttrOfType(E->getType()) &&
Francois Pichet6915c522010-12-27 01:32:00 +0000444 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
445 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
446 }
447 // FIXME: add __uuidof semantic analysis for type operand.
Francois Pichet01b7c302010-09-08 12:20:18 +0000448 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
449 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000450 SourceRange(TypeidLoc, RParenLoc)));
Francois Pichet01b7c302010-09-08 12:20:18 +0000451}
452
453/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
454ExprResult
455Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
456 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000457 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet01b7c302010-09-08 12:20:18 +0000458 if (!MSVCGuidDecl) {
459 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
460 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
461 LookupQualifiedName(R, Context.getTranslationUnitDecl());
462 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
463 if (!MSVCGuidDecl)
464 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000465 }
466
Francois Pichet01b7c302010-09-08 12:20:18 +0000467 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000468
Francois Pichet01b7c302010-09-08 12:20:18 +0000469 if (isType) {
470 // The operand is a type; handle it as such.
471 TypeSourceInfo *TInfo = 0;
472 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
473 &TInfo);
474 if (T.isNull())
475 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000476
Francois Pichet01b7c302010-09-08 12:20:18 +0000477 if (!TInfo)
478 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
479
480 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
481 }
482
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000483 // The operand is an expression.
Francois Pichet01b7c302010-09-08 12:20:18 +0000484 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
485}
486
Steve Naroff1b273c42007-09-16 14:56:35 +0000487/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCall60d7b3a2010-08-24 06:29:42 +0000488ExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000489Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000490 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000491 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000492 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
493 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000494}
Chris Lattner50dd2892008-02-26 00:51:44 +0000495
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000496/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCall60d7b3a2010-08-24 06:29:42 +0000497ExprResult
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000498Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
499 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
500}
501
Chris Lattner50dd2892008-02-26 00:51:44 +0000502/// ActOnCXXThrow - Parse throw expressions.
John McCall60d7b3a2010-08-24 06:29:42 +0000503ExprResult
Douglas Gregorbca01b42011-07-06 22:04:06 +0000504Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
505 bool IsThrownVarInScope = false;
506 if (Ex) {
507 // C++0x [class.copymove]p31:
508 // When certain criteria are met, an implementation is allowed to omit the
509 // copy/move construction of a class object [...]
510 //
511 // - in a throw-expression, when the operand is the name of a
512 // non-volatile automatic object (other than a function or catch-
513 // clause parameter) whose scope does not extend beyond the end of the
514 // innermost enclosing try-block (if there is one), the copy/move
515 // operation from the operand to the exception object (15.1) can be
516 // omitted by constructing the automatic object directly into the
517 // exception object
518 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
519 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
520 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
521 for( ; S; S = S->getParent()) {
522 if (S->isDeclScope(Var)) {
523 IsThrownVarInScope = true;
524 break;
525 }
526
527 if (S->getFlags() &
528 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
529 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
530 Scope::TryScope))
531 break;
532 }
533 }
534 }
535 }
536
537 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
538}
539
540ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
541 bool IsThrownVarInScope) {
Anders Carlsson729b8532011-02-23 03:46:46 +0000542 // Don't report an error if 'throw' is used in system headers.
Anders Carlsson15348ae2011-02-28 02:27:16 +0000543 if (!getLangOptions().CXXExceptions &&
Anders Carlsson729b8532011-02-23 03:46:46 +0000544 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb1fba312011-02-19 21:53:09 +0000545 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Douglas Gregorbca01b42011-07-06 22:04:06 +0000546
John Wiegley429bb272011-04-08 18:41:53 +0000547 if (Ex && !Ex->isTypeDependent()) {
Douglas Gregorbca01b42011-07-06 22:04:06 +0000548 ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex, IsThrownVarInScope);
John Wiegley429bb272011-04-08 18:41:53 +0000549 if (ExRes.isInvalid())
550 return ExprError();
551 Ex = ExRes.take();
552 }
Douglas Gregorbca01b42011-07-06 22:04:06 +0000553
554 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc,
555 IsThrownVarInScope));
Sebastian Redl972041f2009-04-27 20:27:31 +0000556}
557
558/// CheckCXXThrowOperand - Validate the operand of a throw.
Douglas Gregorbca01b42011-07-06 22:04:06 +0000559ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
560 bool IsThrownVarInScope) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000561 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000562 // A throw-expression initializes a temporary object, called the exception
563 // object, the type of which is determined by removing any top-level
564 // cv-qualifiers from the static type of the operand of throw and adjusting
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000565 // the type from "array of T" or "function returning T" to "pointer to T"
Douglas Gregor154fe982009-12-23 22:04:40 +0000566 // or "pointer to function returning T", [...]
567 if (E->getType().hasQualifiers())
John Wiegley429bb272011-04-08 18:41:53 +0000568 E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +0000569 E->getValueKind()).take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000570
John Wiegley429bb272011-04-08 18:41:53 +0000571 ExprResult Res = DefaultFunctionArrayConversion(E);
572 if (Res.isInvalid())
573 return ExprError();
574 E = Res.take();
Sebastian Redl972041f2009-04-27 20:27:31 +0000575
576 // If the type of the exception would be an incomplete type or a pointer
577 // to an incomplete type other than (cv) void the program is ill-formed.
578 QualType Ty = E->getType();
John McCallac418162010-04-22 01:10:34 +0000579 bool isPointer = false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000580 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000581 Ty = Ptr->getPointeeType();
John McCallac418162010-04-22 01:10:34 +0000582 isPointer = true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000583 }
584 if (!isPointer || !Ty->isVoidType()) {
585 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000586 PDiag(isPointer ? diag::err_throw_incomplete_ptr
587 : diag::err_throw_incomplete)
588 << E->getSourceRange()))
John Wiegley429bb272011-04-08 18:41:53 +0000589 return ExprError();
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000590
Douglas Gregorbf422f92010-04-15 18:05:39 +0000591 if (RequireNonAbstractType(ThrowLoc, E->getType(),
592 PDiag(diag::err_throw_abstract_type)
593 << E->getSourceRange()))
John Wiegley429bb272011-04-08 18:41:53 +0000594 return ExprError();
Sebastian Redl972041f2009-04-27 20:27:31 +0000595 }
596
John McCallac418162010-04-22 01:10:34 +0000597 // Initialize the exception result. This implicitly weeds out
598 // abstract types or types with inaccessible copy constructors.
Douglas Gregorbca01b42011-07-06 22:04:06 +0000599
600 // C++0x [class.copymove]p31:
601 // When certain criteria are met, an implementation is allowed to omit the
602 // copy/move construction of a class object [...]
603 //
604 // - in a throw-expression, when the operand is the name of a
605 // non-volatile automatic object (other than a function or catch-clause
606 // parameter) whose scope does not extend beyond the end of the
607 // innermost enclosing try-block (if there is one), the copy/move
608 // operation from the operand to the exception object (15.1) can be
609 // omitted by constructing the automatic object directly into the
610 // exception object
611 const VarDecl *NRVOVariable = 0;
612 if (IsThrownVarInScope)
613 NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
614
John McCallac418162010-04-22 01:10:34 +0000615 InitializedEntity Entity =
Douglas Gregor72dfa272011-01-21 22:46:35 +0000616 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
Douglas Gregorbca01b42011-07-06 22:04:06 +0000617 /*NRVO=*/NRVOVariable != 0);
John Wiegley429bb272011-04-08 18:41:53 +0000618 Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
Douglas Gregorbca01b42011-07-06 22:04:06 +0000619 QualType(), E,
620 IsThrownVarInScope);
John McCallac418162010-04-22 01:10:34 +0000621 if (Res.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000622 return ExprError();
623 E = Res.take();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000624
Eli Friedman5ed9b932010-06-03 20:39:03 +0000625 // If the exception has class type, we need additional handling.
626 const RecordType *RecordTy = Ty->getAs<RecordType>();
627 if (!RecordTy)
John Wiegley429bb272011-04-08 18:41:53 +0000628 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000629 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
630
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000631 // If we are throwing a polymorphic class type or pointer thereof,
632 // exception handling will make use of the vtable.
Eli Friedman5ed9b932010-06-03 20:39:03 +0000633 MarkVTableUsed(ThrowLoc, RD);
634
Eli Friedman98efb9f2010-10-12 20:32:36 +0000635 // If a pointer is thrown, the referenced object will not be destroyed.
636 if (isPointer)
John Wiegley429bb272011-04-08 18:41:53 +0000637 return Owned(E);
Eli Friedman98efb9f2010-10-12 20:32:36 +0000638
Eli Friedman5ed9b932010-06-03 20:39:03 +0000639 // If the class has a non-trivial destructor, we must be able to call it.
640 if (RD->hasTrivialDestructor())
John Wiegley429bb272011-04-08 18:41:53 +0000641 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000642
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000643 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +0000644 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman5ed9b932010-06-03 20:39:03 +0000645 if (!Destructor)
John Wiegley429bb272011-04-08 18:41:53 +0000646 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000647
648 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
649 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregored8abf12010-07-08 06:14:04 +0000650 PDiag(diag::err_access_dtor_exception) << Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000651 return Owned(E);
Chris Lattner50dd2892008-02-26 00:51:44 +0000652}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000653
Eli Friedman72899c32012-01-07 04:59:52 +0000654QualType Sema::getCurrentThisType() {
655 DeclContext *DC = getFunctionLevelDeclContext();
Richard Smith7a614d82011-06-11 17:19:42 +0000656 QualType ThisTy;
657 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
658 if (method && method->isInstance())
659 ThisTy = method->getThisType(Context);
660 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
661 // C++0x [expr.prim]p4:
662 // Otherwise, if a member-declarator declares a non-static data member
663 // of a class X, the expression this is a prvalue of type "pointer to X"
664 // within the optional brace-or-equal-initializer.
665 Scope *S = getScopeForContext(DC);
666 if (!S || S->getFlags() & Scope::ThisScope)
667 ThisTy = Context.getPointerType(Context.getRecordType(RD));
668 }
John McCall469a1eb2011-02-02 13:00:07 +0000669
Richard Smith7a614d82011-06-11 17:19:42 +0000670 return ThisTy;
John McCall5808ce42011-02-03 08:15:49 +0000671}
672
Eli Friedman72899c32012-01-07 04:59:52 +0000673void Sema::CheckCXXThisCapture(SourceLocation Loc) {
674 // We don't need to capture this in an unevaluated context.
675 if (ExprEvalContexts.back().Context == Unevaluated)
676 return;
677
678 // Otherwise, check that we can capture 'this'.
679 unsigned NumClosures = 0;
680 for (unsigned idx = FunctionScopes.size() - 1; idx != 0; idx--) {
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000681 if (CapturingScopeInfo *CSI =
682 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
683 if (CSI->CXXThisCaptureIndex != 0) {
684 // 'this' is already being captured; there isn't anything more to do.
Eli Friedman72899c32012-01-07 04:59:52 +0000685 break;
686 }
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000687 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
688 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block) {
689 // This closure can implicitly capture 'this'; continue looking upwards.
Eli Friedman72899c32012-01-07 04:59:52 +0000690 // FIXME: Is this check correct? The rules in the standard are a bit
691 // unclear.
692 NumClosures++;
693 continue;
694 }
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000695 // This context can't implicitly capture 'this'; fail out.
Eli Friedmanef331b72012-01-20 01:26:23 +0000696 Diag(Loc, diag::err_implicit_this_capture);
Eli Friedman72899c32012-01-07 04:59:52 +0000697 return;
698 }
Eli Friedman72899c32012-01-07 04:59:52 +0000699 break;
700 }
701
702 // Mark that we're implicitly capturing 'this' in all the scopes we skipped.
703 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
704 // contexts.
705 for (unsigned idx = FunctionScopes.size() - 1;
706 NumClosures; --idx, --NumClosures) {
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000707 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
708 bool isNested = NumClosures > 1;
709 CSI->AddThisCapture(isNested);
Eli Friedman72899c32012-01-07 04:59:52 +0000710 }
711}
712
Richard Smith7a614d82011-06-11 17:19:42 +0000713ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCall5808ce42011-02-03 08:15:49 +0000714 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
715 /// is a non-lvalue expression whose value is the address of the object for
716 /// which the function is called.
717
Douglas Gregor341350e2011-10-18 16:47:30 +0000718 QualType ThisTy = getCurrentThisType();
Richard Smith7a614d82011-06-11 17:19:42 +0000719 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCall5808ce42011-02-03 08:15:49 +0000720
Eli Friedman72899c32012-01-07 04:59:52 +0000721 CheckCXXThisCapture(Loc);
Richard Smith7a614d82011-06-11 17:19:42 +0000722 return Owned(new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000723}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000724
John McCall60d7b3a2010-08-24 06:29:42 +0000725ExprResult
Douglas Gregorab6677e2010-09-08 00:15:04 +0000726Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000727 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000728 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000729 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000730 if (!TypeRep)
731 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000732
John McCall9d125032010-01-15 18:39:57 +0000733 TypeSourceInfo *TInfo;
734 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
735 if (!TInfo)
736 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregorab6677e2010-09-08 00:15:04 +0000737
738 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
739}
740
741/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
742/// Can be interpreted either as function-style casting ("int(x)")
743/// or class type construction ("ClassType(x,y,z)")
744/// or creation of a value-initialized type ("int()").
745ExprResult
746Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
747 SourceLocation LParenLoc,
748 MultiExprArg exprs,
749 SourceLocation RParenLoc) {
750 QualType Ty = TInfo->getType();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000751 unsigned NumExprs = exprs.size();
752 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000753 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000754 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
755
Sebastian Redlf53597f2009-03-15 17:47:39 +0000756 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000757 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000758 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000759
Douglas Gregorab6677e2010-09-08 00:15:04 +0000760 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000761 LParenLoc,
762 Exprs, NumExprs,
763 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000764 }
765
Anders Carlssonbb60a502009-08-27 03:53:50 +0000766 if (Ty->isArrayType())
767 return ExprError(Diag(TyBeginLoc,
768 diag::err_value_init_for_array_type) << FullRange);
769 if (!Ty->isVoidType() &&
770 RequireCompleteType(TyBeginLoc, Ty,
771 PDiag(diag::err_invalid_incomplete_type_use)
772 << FullRange))
773 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000774
Anders Carlssonbb60a502009-08-27 03:53:50 +0000775 if (RequireNonAbstractType(TyBeginLoc, Ty,
776 diag::err_allocation_of_abstract_type))
777 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000778
779
Douglas Gregor506ae412009-01-16 18:33:17 +0000780 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000781 // If the expression list is a single expression, the type conversion
782 // expression is equivalent (in definedness, and if defined in meaning) to the
783 // corresponding cast expression.
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000784 if (NumExprs == 1) {
John McCallb45ae252011-10-05 07:41:44 +0000785 Expr *Arg = Exprs[0];
Anders Carlsson0aebc812009-09-09 21:33:21 +0000786 exprs.release();
John McCallb45ae252011-10-05 07:41:44 +0000787 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000788 }
789
Douglas Gregor19311e72010-09-08 21:40:08 +0000790 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
791 InitializationKind Kind
792 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
793 LParenLoc, RParenLoc)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000794 : InitializationKind::CreateValue(TyBeginLoc,
Douglas Gregor19311e72010-09-08 21:40:08 +0000795 LParenLoc, RParenLoc);
796 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
797 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redlf53597f2009-03-15 17:47:39 +0000798
Douglas Gregor19311e72010-09-08 21:40:08 +0000799 // FIXME: Improve AST representation?
800 return move(Result);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000801}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000802
John McCall6ec278d2011-01-27 09:37:56 +0000803/// doesUsualArrayDeleteWantSize - Answers whether the usual
804/// operator delete[] for the given type has a size_t parameter.
805static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
806 QualType allocType) {
807 const RecordType *record =
808 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
809 if (!record) return false;
810
811 // Try to find an operator delete[] in class scope.
812
813 DeclarationName deleteName =
814 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
815 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
816 S.LookupQualifiedName(ops, record->getDecl());
817
818 // We're just doing this for information.
819 ops.suppressDiagnostics();
820
821 // Very likely: there's no operator delete[].
822 if (ops.empty()) return false;
823
824 // If it's ambiguous, it should be illegal to call operator delete[]
825 // on this thing, so it doesn't matter if we allocate extra space or not.
826 if (ops.isAmbiguous()) return false;
827
828 LookupResult::Filter filter = ops.makeFilter();
829 while (filter.hasNext()) {
830 NamedDecl *del = filter.next()->getUnderlyingDecl();
831
832 // C++0x [basic.stc.dynamic.deallocation]p2:
833 // A template instance is never a usual deallocation function,
834 // regardless of its signature.
835 if (isa<FunctionTemplateDecl>(del)) {
836 filter.erase();
837 continue;
838 }
839
840 // C++0x [basic.stc.dynamic.deallocation]p2:
841 // If class T does not declare [an operator delete[] with one
842 // parameter] but does declare a member deallocation function
843 // named operator delete[] with exactly two parameters, the
844 // second of which has type std::size_t, then this function
845 // is a usual deallocation function.
846 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
847 filter.erase();
848 continue;
849 }
850 }
851 filter.done();
852
853 if (!ops.isSingleResult()) return false;
854
855 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
856 return (del->getNumParams() == 2);
857}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000858
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000859/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
860/// @code new (memory) int[size][4] @endcode
861/// or
862/// @code ::new Foo(23, "hello") @endcode
863/// For the interpretation of this heap of arguments, consult the base version.
John McCall60d7b3a2010-08-24 06:29:42 +0000864ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000865Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000866 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000867 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000868 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000869 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000870 SourceLocation ConstructorRParen) {
Richard Smith34b41d92011-02-20 03:19:35 +0000871 bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
872
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000873 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000874 // If the specified type is an array, unwrap it and save the expression.
875 if (D.getNumTypeObjects() > 0 &&
876 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
877 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smith34b41d92011-02-20 03:19:35 +0000878 if (TypeContainsAuto)
879 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
880 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000881 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000882 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
883 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000884 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000885 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
886 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000887
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000888 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000889 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000890 }
891
Douglas Gregor043cad22009-09-11 00:18:58 +0000892 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000893 if (ArraySize) {
894 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000895 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
896 break;
897
898 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
899 if (Expr *NumElts = (Expr *)Array.NumElts) {
900 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
901 !NumElts->isIntegerConstantExpr(Context)) {
902 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
903 << NumElts->getSourceRange();
904 return ExprError();
905 }
906 }
907 }
908 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000909
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +0000910 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
John McCallbf1a0282010-06-04 23:28:52 +0000911 QualType AllocType = TInfo->getType();
Chris Lattnereaaebc72009-04-25 08:06:05 +0000912 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000913 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000914
Mike Stump1eb44332009-09-09 15:08:12 +0000915 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000916 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000917 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000918 PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000919 TypeIdParens,
Mike Stump1eb44332009-09-09 15:08:12 +0000920 AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000921 TInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000922 ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000923 ConstructorLParen,
924 move(ConstructorArgs),
Richard Smith34b41d92011-02-20 03:19:35 +0000925 ConstructorRParen,
926 TypeContainsAuto);
Douglas Gregor3433cf72009-05-21 00:00:09 +0000927}
928
John McCall60d7b3a2010-08-24 06:29:42 +0000929ExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000930Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
931 SourceLocation PlacementLParen,
932 MultiExprArg PlacementArgs,
933 SourceLocation PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000934 SourceRange TypeIdParens,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000935 QualType AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000936 TypeSourceInfo *AllocTypeInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000937 Expr *ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000938 SourceLocation ConstructorLParen,
939 MultiExprArg ConstructorArgs,
Richard Smith34b41d92011-02-20 03:19:35 +0000940 SourceLocation ConstructorRParen,
941 bool TypeMayContainAuto) {
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000942 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000943
Richard Smith34b41d92011-02-20 03:19:35 +0000944 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
945 if (TypeMayContainAuto && AllocType->getContainedAutoType()) {
946 if (ConstructorArgs.size() == 0)
947 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
948 << AllocType << TypeRange);
949 if (ConstructorArgs.size() != 1) {
950 Expr *FirstBad = ConstructorArgs.get()[1];
951 return ExprError(Diag(FirstBad->getSourceRange().getBegin(),
952 diag::err_auto_new_ctor_multiple_expressions)
953 << AllocType << TypeRange);
954 }
Richard Smitha085da82011-03-17 16:11:59 +0000955 TypeSourceInfo *DeducedType = 0;
Sebastian Redlb832f6d2012-01-23 22:09:39 +0000956 if (DeduceAutoType(AllocTypeInfo, ConstructorArgs.get()[0], DeducedType) ==
957 DAR_Failed)
Richard Smith34b41d92011-02-20 03:19:35 +0000958 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
959 << AllocType
960 << ConstructorArgs.get()[0]->getType()
961 << TypeRange
962 << ConstructorArgs.get()[0]->getSourceRange());
Richard Smitha085da82011-03-17 16:11:59 +0000963 if (!DeducedType)
964 return ExprError();
Richard Smith34b41d92011-02-20 03:19:35 +0000965
Richard Smitha085da82011-03-17 16:11:59 +0000966 AllocTypeInfo = DeducedType;
967 AllocType = AllocTypeInfo->getType();
Richard Smith34b41d92011-02-20 03:19:35 +0000968 }
969
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000970 // Per C++0x [expr.new]p5, the type being constructed may be a
971 // typedef of an array type.
John McCall9ae2f072010-08-23 23:25:46 +0000972 if (!ArraySize) {
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000973 if (const ConstantArrayType *Array
974 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000975 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
976 Context.getSizeType(),
977 TypeRange.getEnd());
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000978 AllocType = Array->getElementType();
979 }
980 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000981
Douglas Gregora0750762010-10-06 16:00:31 +0000982 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
983 return ExprError();
984
John McCallf85e1932011-06-15 23:02:42 +0000985 // In ARC, infer 'retaining' for the allocated
986 if (getLangOptions().ObjCAutoRefCount &&
987 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
988 AllocType->isObjCLifetimeType()) {
989 AllocType = Context.getLifetimeQualifiedType(AllocType,
990 AllocType->getObjCARCImplicitLifetime());
991 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000992
John McCallf85e1932011-06-15 23:02:42 +0000993 QualType ResultType = Context.getPointerType(AllocType);
994
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000995 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
996 // or enumeration type with a non-negative value."
Sebastian Redl28507842009-02-26 14:39:58 +0000997 if (ArraySize && !ArraySize->isTypeDependent()) {
Eli Friedman8c382062012-01-23 02:35:22 +0000998 ExprResult ConvertedSize = DefaultFunctionArrayLvalueConversion(ArraySize);
John McCall806054d2012-01-11 00:14:46 +0000999 if (ConvertedSize.isInvalid())
1000 return ExprError();
1001 ArraySize = ConvertedSize.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001002
John McCall806054d2012-01-11 00:14:46 +00001003 ConvertedSize = ConvertToIntegralOrEnumerationType(
Richard Smithebaf0e62011-10-18 20:49:44 +00001004 StartLoc, ArraySize,
1005 PDiag(diag::err_array_size_not_integral),
1006 PDiag(diag::err_array_size_incomplete_type)
1007 << ArraySize->getSourceRange(),
1008 PDiag(diag::err_array_size_explicit_conversion),
1009 PDiag(diag::note_array_size_conversion),
1010 PDiag(diag::err_array_size_ambiguous_conversion),
1011 PDiag(diag::note_array_size_conversion),
1012 PDiag(getLangOptions().CPlusPlus0x ?
1013 diag::warn_cxx98_compat_array_size_conversion :
1014 diag::ext_array_size_conversion));
Douglas Gregor6bc574d2010-06-30 00:20:43 +00001015 if (ConvertedSize.isInvalid())
1016 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001017
John McCall9ae2f072010-08-23 23:25:46 +00001018 ArraySize = ConvertedSize.take();
John McCall806054d2012-01-11 00:14:46 +00001019 QualType SizeType = ArraySize->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001020 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor6bc574d2010-06-30 00:20:43 +00001021 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001022
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001023 // Let's see if this is a constant < 0. If so, we reject it out of hand.
1024 // We don't care about special rules, so we tell the machinery it's not
1025 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +00001026 if (!ArraySize->isValueDependent()) {
1027 llvm::APSInt Value;
1028 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
1029 if (Value < llvm::APSInt(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001030 llvm::APInt::getNullValue(Value.getBitWidth()),
Anders Carlssonac18b2e2009-09-23 00:37:25 +00001031 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +00001032 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +00001033 diag::err_typecheck_negative_array_size)
Sebastian Redlf53597f2009-03-15 17:47:39 +00001034 << ArraySize->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001035
Douglas Gregor2767ce22010-08-18 00:39:00 +00001036 if (!AllocType->isDependentType()) {
1037 unsigned ActiveSizeBits
1038 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1039 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001040 Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +00001041 diag::err_array_too_large)
1042 << Value.toString(10)
1043 << ArraySize->getSourceRange();
1044 return ExprError();
1045 }
1046 }
Douglas Gregor4bd40312010-07-13 15:54:32 +00001047 } else if (TypeIdParens.isValid()) {
1048 // Can't have dynamic array size when the type-id is in parentheses.
1049 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1050 << ArraySize->getSourceRange()
1051 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1052 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001053
Douglas Gregor4bd40312010-07-13 15:54:32 +00001054 TypeIdParens = SourceRange();
Sebastian Redl28507842009-02-26 14:39:58 +00001055 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001056 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001057
John McCallf85e1932011-06-15 23:02:42 +00001058 // ARC: warn about ABI issues.
1059 if (getLangOptions().ObjCAutoRefCount) {
1060 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1061 if (BaseAllocType.hasStrongOrWeakObjCLifetime())
1062 Diag(StartLoc, diag::warn_err_new_delete_object_array)
1063 << 0 << BaseAllocType;
1064 }
1065
John McCall7d166272011-05-15 07:14:44 +00001066 // Note that we do *not* convert the argument in any way. It can
1067 // be signed, larger than size_t, whatever.
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001068 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001069
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001070 FunctionDecl *OperatorNew = 0;
1071 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +00001072 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
1073 unsigned NumPlaceArgs = PlacementArgs.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001074
Sebastian Redl28507842009-02-26 14:39:58 +00001075 if (!AllocType->isDependentType() &&
1076 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
1077 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +00001078 SourceRange(PlacementLParen, PlacementRParen),
1079 UseGlobal, AllocType, ArraySize, PlaceArgs,
1080 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +00001081 return ExprError();
John McCall6ec278d2011-01-27 09:37:56 +00001082
1083 // If this is an array allocation, compute whether the usual array
1084 // deallocation function for the type has a size_t parameter.
1085 bool UsualArrayDeleteWantsSize = false;
1086 if (ArraySize && !AllocType->isDependentType())
1087 UsualArrayDeleteWantsSize
1088 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1089
Chris Lattner5f9e2722011-07-23 10:55:15 +00001090 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001091 if (OperatorNew) {
1092 // Add default arguments, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001093 const FunctionProtoType *Proto =
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001094 OperatorNew->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001095 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00001096 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001097
Anders Carlsson28e94832010-05-03 02:07:56 +00001098 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001099 Proto, 1, PlaceArgs, NumPlaceArgs,
Anders Carlsson28e94832010-05-03 02:07:56 +00001100 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001101 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001102
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001103 NumPlaceArgs = AllPlaceArgs.size();
1104 if (NumPlaceArgs > 0)
1105 PlaceArgs = &AllPlaceArgs[0];
1106 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001107
Nick Lewyckyfca84b22012-01-24 21:15:41 +00001108 // Warn if the type is over-aligned and is being allocated by global operator
1109 // new.
1110 if (OperatorNew &&
1111 (OperatorNew->isImplicit() ||
1112 getSourceManager().isInSystemHeader(OperatorNew->getLocStart()))) {
1113 if (unsigned Align = Context.getPreferredTypeAlign(AllocType.getTypePtr())){
1114 unsigned SuitableAlign = Context.getTargetInfo().getSuitableAlign();
1115 if (Align > SuitableAlign)
1116 Diag(StartLoc, diag::warn_overaligned_type)
1117 << AllocType
1118 << unsigned(Align / Context.getCharWidth())
1119 << unsigned(SuitableAlign / Context.getCharWidth());
1120 }
1121 }
1122
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001123 bool Init = ConstructorLParen.isValid();
1124 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001125 CXXConstructorDecl *Constructor = 0;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001126 bool HadMultipleCandidates = false;
Sebastian Redlf53597f2009-03-15 17:47:39 +00001127 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
1128 unsigned NumConsArgs = ConstructorArgs.size();
John McCallca0408f2010-08-23 06:44:23 +00001129 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmana8ce9ec2009-11-08 22:15:39 +00001130
Anders Carlsson48c95012010-05-03 15:45:23 +00001131 // Array 'new' can't have any initializers.
Anders Carlsson55cbd6e2010-05-16 16:24:20 +00001132 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlsson48c95012010-05-03 15:45:23 +00001133 SourceRange InitRange(ConsArgs[0]->getLocStart(),
1134 ConsArgs[NumConsArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001135
Anders Carlsson48c95012010-05-03 15:45:23 +00001136 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1137 return ExprError();
1138 }
1139
Douglas Gregor99a2e602009-12-16 01:38:02 +00001140 if (!AllocType->isDependentType() &&
1141 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
1142 // C++0x [expr.new]p15:
1143 // A new-expression that creates an object of type T initializes that
1144 // object as follows:
1145 InitializationKind Kind
1146 // - If the new-initializer is omitted, the object is default-
1147 // initialized (8.5); if no initialization is performed,
1148 // the object has indeterminate value
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001149 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001150 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor99a2e602009-12-16 01:38:02 +00001151 // initialization rules of 8.5 for direct-initialization.
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001152 : InitializationKind::CreateDirect(TypeRange.getBegin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001153 ConstructorLParen,
Douglas Gregor99a2e602009-12-16 01:38:02 +00001154 ConstructorRParen);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001155
Douglas Gregor99a2e602009-12-16 01:38:02 +00001156 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00001157 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001158 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001159 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor99a2e602009-12-16 01:38:02 +00001160 move(ConstructorArgs));
1161 if (FullInit.isInvalid())
1162 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001163
1164 // FullInit is our initializer; walk through it to determine if it's a
Douglas Gregor99a2e602009-12-16 01:38:02 +00001165 // constructor call, which CXXNewExpr handles directly.
1166 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
1167 if (CXXBindTemporaryExpr *Binder
1168 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
1169 FullInitExpr = Binder->getSubExpr();
1170 if (CXXConstructExpr *Construct
1171 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
1172 Constructor = Construct->getConstructor();
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001173 HadMultipleCandidates = Construct->hadMultipleCandidates();
Douglas Gregor99a2e602009-12-16 01:38:02 +00001174 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
1175 AEnd = Construct->arg_end();
1176 A != AEnd; ++A)
John McCall3fa5cae2010-10-26 07:05:15 +00001177 ConvertedConstructorArgs.push_back(*A);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001178 } else {
1179 // Take the converted initializer.
1180 ConvertedConstructorArgs.push_back(FullInit.release());
1181 }
1182 } else {
1183 // No initialization required.
1184 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001185
Douglas Gregor99a2e602009-12-16 01:38:02 +00001186 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +00001187 NumConsArgs = ConvertedConstructorArgs.size();
1188 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001189 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001190
Douglas Gregor6d908702010-02-26 05:06:18 +00001191 // Mark the new and delete operators as referenced.
1192 if (OperatorNew)
1193 MarkDeclarationReferenced(StartLoc, OperatorNew);
1194 if (OperatorDelete)
1195 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1196
John McCall84ff0fc2011-07-13 20:12:57 +00001197 // C++0x [expr.new]p17:
1198 // If the new expression creates an array of objects of class type,
1199 // access and ambiguity control are done for the destructor.
1200 if (ArraySize && Constructor) {
1201 if (CXXDestructorDecl *dtor = LookupDestructor(Constructor->getParent())) {
1202 MarkDeclarationReferenced(StartLoc, dtor);
1203 CheckDestructorAccess(StartLoc, dtor,
1204 PDiag(diag::err_access_dtor)
1205 << Context.getBaseElementType(AllocType));
1206 }
1207 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001208
Sebastian Redlf53597f2009-03-15 17:47:39 +00001209 PlacementArgs.release();
1210 ConstructorArgs.release();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001211
Ted Kremenekad7fe862010-02-11 22:51:03 +00001212 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregor4bd40312010-07-13 15:54:32 +00001213 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001214 ArraySize, Constructor, Init,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001215 ConsArgs, NumConsArgs,
1216 HadMultipleCandidates,
1217 OperatorDelete,
John McCall6ec278d2011-01-27 09:37:56 +00001218 UsualArrayDeleteWantsSize,
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001219 ResultType, AllocTypeInfo,
1220 StartLoc,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001221 Init ? ConstructorRParen :
Chandler Carruth428edaf2010-10-25 08:47:36 +00001222 TypeRange.getEnd(),
1223 ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001224}
1225
1226/// CheckAllocatedType - Checks that a type is suitable as the allocated type
1227/// in a new-expression.
1228/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +00001229bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00001230 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001231 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1232 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +00001233 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001234 return Diag(Loc, diag::err_bad_new_type)
1235 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001236 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001237 return Diag(Loc, diag::err_bad_new_type)
1238 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001239 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +00001240 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001241 PDiag(diag::err_new_incomplete_type)
1242 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001243 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +00001244 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +00001245 diag::err_allocation_of_abstract_type))
1246 return true;
Douglas Gregora0750762010-10-06 16:00:31 +00001247 else if (AllocType->isVariablyModifiedType())
1248 return Diag(Loc, diag::err_variably_modified_new_type)
1249 << AllocType;
Douglas Gregor5666d362011-04-15 19:46:20 +00001250 else if (unsigned AddressSpace = AllocType.getAddressSpace())
1251 return Diag(Loc, diag::err_address_space_qualified_new)
1252 << AllocType.getUnqualifiedType() << AddressSpace;
John McCallf85e1932011-06-15 23:02:42 +00001253 else if (getLangOptions().ObjCAutoRefCount) {
1254 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
1255 QualType BaseAllocType = Context.getBaseElementType(AT);
1256 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1257 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001258 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001259 << BaseAllocType;
1260 }
1261 }
Douglas Gregor5666d362011-04-15 19:46:20 +00001262
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001263 return false;
1264}
1265
Douglas Gregor6d908702010-02-26 05:06:18 +00001266/// \brief Determine whether the given function is a non-placement
1267/// deallocation function.
1268static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1269 if (FD->isInvalidDecl())
1270 return false;
1271
1272 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1273 return Method->isUsualDeallocationFunction();
1274
1275 return ((FD->getOverloadedOperator() == OO_Delete ||
1276 FD->getOverloadedOperator() == OO_Array_Delete) &&
1277 FD->getNumParams() == 1);
1278}
1279
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001280/// FindAllocationFunctions - Finds the overloads of operator new and delete
1281/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001282bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1283 bool UseGlobal, QualType AllocType,
1284 bool IsArray, Expr **PlaceArgs,
1285 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001286 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +00001287 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001288 // --- Choosing an allocation function ---
1289 // C++ 5.3.4p8 - 14 & 18
1290 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1291 // in the scope of the allocated class.
1292 // 2) If an array size is given, look for operator new[], else look for
1293 // operator new.
1294 // 3) The first argument is always size_t. Append the arguments from the
1295 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001296
Chris Lattner5f9e2722011-07-23 10:55:15 +00001297 SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001298 // We don't care about the actual value of this argument.
1299 // FIXME: Should the Sema create the expression and embed it in the syntax
1300 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00001301 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001302 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssond67c4c32009-08-16 20:29:29 +00001303 Context.getSizeType(),
1304 SourceLocation());
1305 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001306 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1307
Douglas Gregor6d908702010-02-26 05:06:18 +00001308 // C++ [expr.new]p8:
1309 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001310 // function's name is operator new and the deallocation function's
Douglas Gregor6d908702010-02-26 05:06:18 +00001311 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001312 // type, the allocation function's name is operator new[] and the
1313 // deallocation function's name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001314 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1315 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +00001316 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1317 IsArray ? OO_Array_Delete : OO_Delete);
1318
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001319 QualType AllocElemType = Context.getBaseElementType(AllocType);
1320
1321 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +00001322 CXXRecordDecl *Record
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001323 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +00001324 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001325 AllocArgs.size(), Record, /*AllowMissing=*/true,
1326 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001327 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001328 }
1329 if (!OperatorNew) {
1330 // Didn't find a member overload. Look for a global one.
1331 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +00001332 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +00001333 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001334 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1335 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001336 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001337 }
1338
John McCall9c82afc2010-04-20 02:18:25 +00001339 // We don't need an operator delete if we're running under
1340 // -fno-exceptions.
1341 if (!getLangOptions().Exceptions) {
1342 OperatorDelete = 0;
1343 return false;
1344 }
1345
Anders Carlssond9583892009-05-31 20:26:12 +00001346 // FindAllocationOverload can change the passed in arguments, so we need to
1347 // copy them back.
1348 if (NumPlaceArgs > 0)
1349 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001350
Douglas Gregor6d908702010-02-26 05:06:18 +00001351 // C++ [expr.new]p19:
1352 //
1353 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001354 // deallocation function's name is looked up in the global
Douglas Gregor6d908702010-02-26 05:06:18 +00001355 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001356 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6d908702010-02-26 05:06:18 +00001357 // the scope of T. If this lookup fails to find the name, or if
1358 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001359 // deallocation function's name is looked up in the global scope.
Douglas Gregor6d908702010-02-26 05:06:18 +00001360 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001361 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001362 CXXRecordDecl *RD
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001363 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6d908702010-02-26 05:06:18 +00001364 LookupQualifiedName(FoundDelete, RD);
1365 }
John McCall90c8c572010-03-18 08:19:33 +00001366 if (FoundDelete.isAmbiguous())
1367 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +00001368
1369 if (FoundDelete.empty()) {
1370 DeclareGlobalNewDelete();
1371 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1372 }
1373
1374 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +00001375
Chris Lattner5f9e2722011-07-23 10:55:15 +00001376 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCall9aa472c2010-03-19 07:35:19 +00001377
John McCalledeb6c92010-09-14 21:34:24 +00001378 // Whether we're looking for a placement operator delete is dictated
1379 // by whether we selected a placement operator new, not by whether
1380 // we had explicit placement arguments. This matters for things like
1381 // struct A { void *operator new(size_t, int = 0); ... };
1382 // A *a = new A()
1383 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1384
1385 if (isPlacementNew) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001386 // C++ [expr.new]p20:
1387 // A declaration of a placement deallocation function matches the
1388 // declaration of a placement allocation function if it has the
1389 // same number of parameters and, after parameter transformations
1390 // (8.3.5), all parameter types except the first are
1391 // identical. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001392 //
Douglas Gregor6d908702010-02-26 05:06:18 +00001393 // To perform this comparison, we compute the function type that
1394 // the deallocation function should have, and use that type both
1395 // for template argument deduction and for comparison purposes.
John McCalle23cf432010-12-14 08:05:40 +00001396 //
1397 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6d908702010-02-26 05:06:18 +00001398 QualType ExpectedFunctionType;
1399 {
1400 const FunctionProtoType *Proto
1401 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00001402
Chris Lattner5f9e2722011-07-23 10:55:15 +00001403 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001404 ArgTypes.push_back(Context.VoidPtrTy);
Douglas Gregor6d908702010-02-26 05:06:18 +00001405 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1406 ArgTypes.push_back(Proto->getArgType(I));
1407
John McCalle23cf432010-12-14 08:05:40 +00001408 FunctionProtoType::ExtProtoInfo EPI;
1409 EPI.Variadic = Proto->isVariadic();
1410
Douglas Gregor6d908702010-02-26 05:06:18 +00001411 ExpectedFunctionType
1412 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
John McCalle23cf432010-12-14 08:05:40 +00001413 ArgTypes.size(), EPI);
Douglas Gregor6d908702010-02-26 05:06:18 +00001414 }
1415
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001416 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001417 DEnd = FoundDelete.end();
1418 D != DEnd; ++D) {
1419 FunctionDecl *Fn = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001420 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6d908702010-02-26 05:06:18 +00001421 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1422 // Perform template argument deduction to try to match the
1423 // expected function type.
1424 TemplateDeductionInfo Info(Context, StartLoc);
1425 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1426 continue;
1427 } else
1428 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1429
1430 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001431 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001432 }
1433 } else {
1434 // C++ [expr.new]p20:
1435 // [...] Any non-placement deallocation function matches a
1436 // non-placement allocation function. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001437 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001438 DEnd = FoundDelete.end();
1439 D != DEnd; ++D) {
1440 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1441 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001442 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001443 }
1444 }
1445
1446 // C++ [expr.new]p20:
1447 // [...] If the lookup finds a single matching deallocation
1448 // function, that function will be called; otherwise, no
1449 // deallocation function will be called.
1450 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001451 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001452
1453 // C++0x [expr.new]p20:
1454 // If the lookup finds the two-parameter form of a usual
1455 // deallocation function (3.7.4.2) and that function, considered
1456 // as a placement deallocation function, would have been
1457 // selected as a match for the allocation function, the program
1458 // is ill-formed.
1459 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1460 isNonPlacementDeallocationFunction(OperatorDelete)) {
1461 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001462 << SourceRange(PlaceArgs[0]->getLocStart(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001463 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1464 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1465 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001466 } else {
1467 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001468 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001469 }
1470 }
1471
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001472 return false;
1473}
1474
Sebastian Redl7f662392008-12-04 22:20:51 +00001475/// FindAllocationOverload - Find an fitting overload for the allocation
1476/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001477bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1478 DeclarationName Name, Expr** Args,
1479 unsigned NumArgs, DeclContext *Ctx,
Sean Hunt2be7e902011-05-12 22:46:29 +00001480 bool AllowMissing, FunctionDecl *&Operator,
1481 bool Diagnose) {
John McCalla24dc2e2009-11-17 02:14:36 +00001482 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1483 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001484 if (R.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001485 if (AllowMissing || !Diagnose)
Sebastian Redl7f662392008-12-04 22:20:51 +00001486 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001487 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001488 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001489 }
1490
John McCall90c8c572010-03-18 08:19:33 +00001491 if (R.isAmbiguous())
1492 return true;
1493
1494 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001495
John McCall5769d612010-02-08 23:07:23 +00001496 OverloadCandidateSet Candidates(StartLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001497 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001498 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001499 // Even member operator new/delete are implicitly treated as
1500 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001501 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001502
John McCall9aa472c2010-03-19 07:35:19 +00001503 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1504 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001505 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1506 Candidates,
1507 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001508 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001509 }
1510
John McCall9aa472c2010-03-19 07:35:19 +00001511 FunctionDecl *Fn = cast<FunctionDecl>(D);
1512 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001513 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001514 }
1515
1516 // Do the resolution.
1517 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00001518 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001519 case OR_Success: {
1520 // Got one!
1521 FunctionDecl *FnDecl = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00001522 MarkDeclarationReferenced(StartLoc, FnDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001523 // The first argument is size_t, and the first parameter must be size_t,
1524 // too. This is checked on declaration and can be assumed. (It can't be
1525 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001526 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001527 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1528 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001529 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1530 FnDecl->getParamDecl(i));
1531
1532 if (!Diagnose && !CanPerformCopyInitialization(Entity, Owned(Args[i])))
1533 return true;
1534
John McCall60d7b3a2010-08-24 06:29:42 +00001535 ExprResult Result
Sean Hunt2be7e902011-05-12 22:46:29 +00001536 = PerformCopyInitialization(Entity, SourceLocation(), Owned(Args[i]));
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001537 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001538 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001539
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001540 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001541 }
1542 Operator = FnDecl;
Sean Hunt2be7e902011-05-12 22:46:29 +00001543 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl,
1544 Diagnose);
Sebastian Redl7f662392008-12-04 22:20:51 +00001545 return false;
1546 }
1547
1548 case OR_No_Viable_Function:
Chandler Carruth361d3802011-06-08 10:26:03 +00001549 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001550 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1551 << Name << Range;
Chandler Carruth361d3802011-06-08 10:26:03 +00001552 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1553 }
Sebastian Redl7f662392008-12-04 22:20:51 +00001554 return true;
1555
1556 case OR_Ambiguous:
Chandler Carruth361d3802011-06-08 10:26:03 +00001557 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001558 Diag(StartLoc, diag::err_ovl_ambiguous_call)
1559 << Name << Range;
Chandler Carruth361d3802011-06-08 10:26:03 +00001560 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
1561 }
Sebastian Redl7f662392008-12-04 22:20:51 +00001562 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001563
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001564 case OR_Deleted: {
Chandler Carruth361d3802011-06-08 10:26:03 +00001565 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001566 Diag(StartLoc, diag::err_ovl_deleted_call)
1567 << Best->Function->isDeleted()
1568 << Name
1569 << getDeletedOrUnavailableSuffix(Best->Function)
1570 << Range;
Chandler Carruth361d3802011-06-08 10:26:03 +00001571 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1572 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001573 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001574 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001575 }
David Blaikieb219cfc2011-09-23 05:06:16 +00001576 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Sebastian Redl7f662392008-12-04 22:20:51 +00001577}
1578
1579
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001580/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1581/// delete. These are:
1582/// @code
Sebastian Redl8999fe12011-03-14 18:08:30 +00001583/// // C++03:
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001584/// void* operator new(std::size_t) throw(std::bad_alloc);
1585/// void* operator new[](std::size_t) throw(std::bad_alloc);
1586/// void operator delete(void *) throw();
1587/// void operator delete[](void *) throw();
Sebastian Redl8999fe12011-03-14 18:08:30 +00001588/// // C++0x:
1589/// void* operator new(std::size_t);
1590/// void* operator new[](std::size_t);
1591/// void operator delete(void *);
1592/// void operator delete[](void *);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001593/// @endcode
Sebastian Redl8999fe12011-03-14 18:08:30 +00001594/// C++0x operator delete is implicitly noexcept.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001595/// Note that the placement and nothrow forms of new are *not* implicitly
1596/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001597void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001598 if (GlobalNewDeleteDeclared)
1599 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001600
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001601 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001602 // [...] The following allocation and deallocation functions (18.4) are
1603 // implicitly declared in global scope in each translation unit of a
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001604 // program
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001605 //
Sebastian Redl8999fe12011-03-14 18:08:30 +00001606 // C++03:
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001607 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001608 // void* operator new[](std::size_t) throw(std::bad_alloc);
1609 // void operator delete(void*) throw();
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001610 // void operator delete[](void*) throw();
Sebastian Redl8999fe12011-03-14 18:08:30 +00001611 // C++0x:
1612 // void* operator new(std::size_t);
1613 // void* operator new[](std::size_t);
1614 // void operator delete(void*);
1615 // void operator delete[](void*);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001616 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001617 // These implicit declarations introduce only the function names operator
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001618 // new, operator new[], operator delete, operator delete[].
1619 //
1620 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1621 // "std" or "bad_alloc" as necessary to form the exception specification.
1622 // However, we do not make these implicit declarations visible to name
1623 // lookup.
Sebastian Redl8999fe12011-03-14 18:08:30 +00001624 // Note that the C++0x versions of operator delete are deallocation functions,
1625 // and thus are implicitly noexcept.
1626 if (!StdBadAlloc && !getLangOptions().CPlusPlus0x) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001627 // The "std::bad_alloc" class has not yet been declared, so build it
1628 // implicitly.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001629 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1630 getOrCreateStdNamespace(),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001631 SourceLocation(), SourceLocation(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001632 &PP.getIdentifierTable().get("bad_alloc"),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001633 0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001634 getStdBadAlloc()->setImplicit(true);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001635 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001636
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001637 GlobalNewDeleteDeclared = true;
1638
1639 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1640 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001641 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001642
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001643 DeclareGlobalAllocationFunction(
1644 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001645 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001646 DeclareGlobalAllocationFunction(
1647 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001648 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001649 DeclareGlobalAllocationFunction(
1650 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1651 Context.VoidTy, VoidPtr);
1652 DeclareGlobalAllocationFunction(
1653 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1654 Context.VoidTy, VoidPtr);
1655}
1656
1657/// DeclareGlobalAllocationFunction - Declares a single implicit global
1658/// allocation function if it doesn't already exist.
1659void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001660 QualType Return, QualType Argument,
1661 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001662 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1663
1664 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001665 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001666 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001667 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001668 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001669 // Only look at non-template functions, as it is the predefined,
1670 // non-templated allocation function we are trying to declare here.
1671 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1672 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001673 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001674 Func->getParamDecl(0)->getType().getUnqualifiedType());
1675 // FIXME: Do we need to check for default arguments here?
Douglas Gregor7b868622010-08-18 15:06:25 +00001676 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1677 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00001678 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001679 return;
Douglas Gregor7b868622010-08-18 15:06:25 +00001680 }
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001681 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001682 }
1683 }
1684
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001685 QualType BadAllocType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001686 bool HasBadAllocExceptionSpec
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001687 = (Name.getCXXOverloadedOperator() == OO_New ||
1688 Name.getCXXOverloadedOperator() == OO_Array_New);
Sebastian Redl8999fe12011-03-14 18:08:30 +00001689 if (HasBadAllocExceptionSpec && !getLangOptions().CPlusPlus0x) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001690 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001691 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001692 }
John McCalle23cf432010-12-14 08:05:40 +00001693
1694 FunctionProtoType::ExtProtoInfo EPI;
John McCalle23cf432010-12-14 08:05:40 +00001695 if (HasBadAllocExceptionSpec) {
Sebastian Redl8999fe12011-03-14 18:08:30 +00001696 if (!getLangOptions().CPlusPlus0x) {
1697 EPI.ExceptionSpecType = EST_Dynamic;
1698 EPI.NumExceptions = 1;
1699 EPI.Exceptions = &BadAllocType;
1700 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00001701 } else {
Sebastian Redl8999fe12011-03-14 18:08:30 +00001702 EPI.ExceptionSpecType = getLangOptions().CPlusPlus0x ?
1703 EST_BasicNoexcept : EST_DynamicNone;
John McCalle23cf432010-12-14 08:05:40 +00001704 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001705
John McCalle23cf432010-12-14 08:05:40 +00001706 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001707 FunctionDecl *Alloc =
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001708 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
1709 SourceLocation(), Name,
John McCalld931b082010-08-26 03:08:43 +00001710 FnType, /*TInfo=*/0, SC_None,
1711 SC_None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001712 Alloc->setImplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001713
Nuno Lopesfc284482009-12-16 16:59:22 +00001714 if (AddMallocAttr)
Sean Huntcf807c42010-08-18 23:23:40 +00001715 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001716
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001717 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001718 SourceLocation(), 0,
1719 Argument, /*TInfo=*/0,
1720 SC_None, SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00001721 Alloc->setParams(Param);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001722
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001723 // FIXME: Also add this declaration to the IdentifierResolver, but
1724 // make sure it is at the end of the chain to coincide with the
1725 // global scope.
John McCall5f1e0942010-08-24 08:50:51 +00001726 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001727}
1728
Anders Carlsson78f74552009-11-15 18:45:20 +00001729bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1730 DeclarationName Name,
Sean Hunt2be7e902011-05-12 22:46:29 +00001731 FunctionDecl* &Operator, bool Diagnose) {
John McCalla24dc2e2009-11-17 02:14:36 +00001732 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001733 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001734 LookupQualifiedName(Found, RD);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001735
John McCalla24dc2e2009-11-17 02:14:36 +00001736 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001737 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001738
Chandler Carruth23893242010-06-28 00:30:51 +00001739 Found.suppressDiagnostics();
1740
Chris Lattner5f9e2722011-07-23 10:55:15 +00001741 SmallVector<DeclAccessPair,4> Matches;
Anders Carlsson78f74552009-11-15 18:45:20 +00001742 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1743 F != FEnd; ++F) {
Chandler Carruth09556fd2010-08-08 07:04:00 +00001744 NamedDecl *ND = (*F)->getUnderlyingDecl();
1745
1746 // Ignore template operator delete members from the check for a usual
1747 // deallocation function.
1748 if (isa<FunctionTemplateDecl>(ND))
1749 continue;
1750
1751 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall046a7462010-08-04 00:31:26 +00001752 Matches.push_back(F.getPair());
1753 }
1754
1755 // There's exactly one suitable operator; pick it.
1756 if (Matches.size() == 1) {
1757 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
Sean Hunt2be7e902011-05-12 22:46:29 +00001758
1759 if (Operator->isDeleted()) {
1760 if (Diagnose) {
1761 Diag(StartLoc, diag::err_deleted_function_use);
1762 Diag(Operator->getLocation(), diag::note_unavailable_here) << true;
1763 }
1764 return true;
1765 }
1766
John McCall046a7462010-08-04 00:31:26 +00001767 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Sean Hunt2be7e902011-05-12 22:46:29 +00001768 Matches[0], Diagnose);
John McCall046a7462010-08-04 00:31:26 +00001769 return false;
1770
1771 // We found multiple suitable operators; complain about the ambiguity.
1772 } else if (!Matches.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001773 if (Diagnose) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00001774 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1775 << Name << RD;
John McCall046a7462010-08-04 00:31:26 +00001776
Chris Lattner5f9e2722011-07-23 10:55:15 +00001777 for (SmallVectorImpl<DeclAccessPair>::iterator
Sean Huntcb45a0f2011-05-12 22:46:25 +00001778 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1779 Diag((*F)->getUnderlyingDecl()->getLocation(),
1780 diag::note_member_declared_here) << Name;
1781 }
John McCall046a7462010-08-04 00:31:26 +00001782 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001783 }
1784
1785 // We did find operator delete/operator delete[] declarations, but
1786 // none of them were suitable.
1787 if (!Found.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001788 if (Diagnose) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00001789 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1790 << Name << RD;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001791
Sean Huntcb45a0f2011-05-12 22:46:25 +00001792 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1793 F != FEnd; ++F)
1794 Diag((*F)->getUnderlyingDecl()->getLocation(),
1795 diag::note_member_declared_here) << Name;
1796 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001797 return true;
1798 }
1799
1800 // Look for a global declaration.
1801 DeclareGlobalNewDelete();
1802 DeclContext *TUDecl = Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001803
Anders Carlsson78f74552009-11-15 18:45:20 +00001804 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1805 Expr* DeallocArgs[1];
1806 DeallocArgs[0] = &Null;
1807 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
Sean Hunt2be7e902011-05-12 22:46:29 +00001808 DeallocArgs, 1, TUDecl, !Diagnose,
1809 Operator, Diagnose))
Anders Carlsson78f74552009-11-15 18:45:20 +00001810 return true;
1811
1812 assert(Operator && "Did not find a deallocation function!");
1813 return false;
1814}
1815
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001816/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1817/// @code ::delete ptr; @endcode
1818/// or
1819/// @code delete [] ptr; @endcode
John McCall60d7b3a2010-08-24 06:29:42 +00001820ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001821Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley429bb272011-04-08 18:41:53 +00001822 bool ArrayForm, Expr *ExE) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001823 // C++ [expr.delete]p1:
1824 // The operand shall have a pointer type, or a class type having a single
1825 // conversion function to a pointer type. The result has type void.
1826 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001827 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1828
John Wiegley429bb272011-04-08 18:41:53 +00001829 ExprResult Ex = Owned(ExE);
Anders Carlssond67c4c32009-08-16 20:29:29 +00001830 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001831 bool ArrayFormAsWritten = ArrayForm;
John McCall6ec278d2011-01-27 09:37:56 +00001832 bool UsualArrayDeleteWantsSize = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001833
John Wiegley429bb272011-04-08 18:41:53 +00001834 if (!Ex.get()->isTypeDependent()) {
1835 QualType Type = Ex.get()->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001836
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001837 if (const RecordType *Record = Type->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001838 if (RequireCompleteType(StartLoc, Type,
Douglas Gregor254a9422010-07-29 14:44:35 +00001839 PDiag(diag::err_delete_incomplete_class_type)))
1840 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001841
Chris Lattner5f9e2722011-07-23 10:55:15 +00001842 SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
John McCall32daa422010-03-31 01:36:47 +00001843
Fariborz Jahanian53462782009-09-11 21:44:33 +00001844 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001845 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001846 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001847 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001848 NamedDecl *D = I.getDecl();
1849 if (isa<UsingShadowDecl>(D))
1850 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1851
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001852 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001853 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001854 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001855
John McCall32daa422010-03-31 01:36:47 +00001856 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001857
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001858 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1859 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedman13578692010-08-05 02:49:48 +00001860 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001861 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001862 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001863 if (ObjectPtrConversions.size() == 1) {
1864 // We have a single conversion to a pointer-to-object type. Perform
1865 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001866 // TODO: don't redo the conversion calculation.
John Wiegley429bb272011-04-08 18:41:53 +00001867 ExprResult Res =
1868 PerformImplicitConversion(Ex.get(),
John McCall32daa422010-03-31 01:36:47 +00001869 ObjectPtrConversions.front()->getConversionType(),
John Wiegley429bb272011-04-08 18:41:53 +00001870 AA_Converting);
1871 if (Res.isUsable()) {
1872 Ex = move(Res);
1873 Type = Ex.get()->getType();
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001874 }
1875 }
1876 else if (ObjectPtrConversions.size() > 1) {
1877 Diag(StartLoc, diag::err_ambiguous_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001878 << Type << Ex.get()->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001879 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1880 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001881 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001882 }
Sebastian Redl28507842009-02-26 14:39:58 +00001883 }
1884
Sebastian Redlf53597f2009-03-15 17:47:39 +00001885 if (!Type->isPointerType())
1886 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001887 << Type << Ex.get()->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001888
Ted Kremenek6217b802009-07-29 21:53:49 +00001889 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmane52c9142011-07-26 22:25:31 +00001890 QualType PointeeElem = Context.getBaseElementType(Pointee);
1891
1892 if (unsigned AddressSpace = Pointee.getAddressSpace())
1893 return Diag(Ex.get()->getLocStart(),
1894 diag::err_address_space_qualified_delete)
1895 << Pointee.getUnqualifiedType() << AddressSpace;
1896
1897 CXXRecordDecl *PointeeRD = 0;
Douglas Gregor94a61572010-05-24 17:01:56 +00001898 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001899 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregor94a61572010-05-24 17:01:56 +00001900 // effectively bans deletion of "void*". However, most compilers support
1901 // this, so we treat it as a warning unless we're in a SFINAE context.
1902 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001903 << Type << Ex.get()->getSourceRange();
Eli Friedmane52c9142011-07-26 22:25:31 +00001904 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00001905 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001906 << Type << Ex.get()->getSourceRange());
Eli Friedmane52c9142011-07-26 22:25:31 +00001907 } else if (!Pointee->isDependentType()) {
1908 if (!RequireCompleteType(StartLoc, Pointee,
1909 PDiag(diag::warn_delete_incomplete)
1910 << Ex.get()->getSourceRange())) {
1911 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
1912 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
1913 }
1914 }
1915
Abramo Bagnara30bb4202011-11-16 15:42:13 +00001916 // Perform lvalue-to-rvalue cast, if needed.
1917 Ex = DefaultLvalueConversion(Ex.take());
1918
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001919 // C++ [expr.delete]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001920 // [Note: a pointer to a const type can be the operand of a
1921 // delete-expression; it is not necessary to cast away the constness
1922 // (5.2.11) of the pointer expression before it is used as the operand
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001923 // of the delete-expression. ]
John McCallf85e1932011-06-15 23:02:42 +00001924 if (!Context.hasSameType(Ex.get()->getType(), Context.VoidPtrTy))
Abramo Bagnara30bb4202011-11-16 15:42:13 +00001925 Ex = Owned(ImplicitCastExpr::Create(Context, Context.VoidPtrTy,
1926 CK_BitCast, Ex.take(), 0, VK_RValue));
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001927
1928 if (Pointee->isArrayType() && !ArrayForm) {
1929 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley429bb272011-04-08 18:41:53 +00001930 << Type << Ex.get()->getSourceRange()
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001931 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1932 ArrayForm = true;
1933 }
1934
Anders Carlssond67c4c32009-08-16 20:29:29 +00001935 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1936 ArrayForm ? OO_Array_Delete : OO_Delete);
1937
Eli Friedmane52c9142011-07-26 22:25:31 +00001938 if (PointeeRD) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001939 if (!UseGlobal &&
Eli Friedmane52c9142011-07-26 22:25:31 +00001940 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
1941 OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001942 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001943
John McCall6ec278d2011-01-27 09:37:56 +00001944 // If we're allocating an array of records, check whether the
1945 // usual operator delete[] has a size_t parameter.
1946 if (ArrayForm) {
1947 // If the user specifically asked to use the global allocator,
1948 // we'll need to do the lookup into the class.
1949 if (UseGlobal)
1950 UsualArrayDeleteWantsSize =
1951 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
1952
1953 // Otherwise, the usual operator delete[] should be the
1954 // function we just found.
1955 else if (isa<CXXMethodDecl>(OperatorDelete))
1956 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
1957 }
1958
Eli Friedmane52c9142011-07-26 22:25:31 +00001959 if (!PointeeRD->hasTrivialDestructor())
1960 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001961 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001962 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor9b623632010-10-12 23:32:35 +00001963 DiagnoseUseOfDecl(Dtor, StartLoc);
1964 }
Argyrios Kyrtzidis6f0074a2011-05-24 19:53:26 +00001965
1966 // C++ [expr.delete]p3:
1967 // In the first alternative (delete object), if the static type of the
1968 // object to be deleted is different from its dynamic type, the static
1969 // type shall be a base class of the dynamic type of the object to be
1970 // deleted and the static type shall have a virtual destructor or the
1971 // behavior is undefined.
1972 //
1973 // Note: a final class cannot be derived from, no issue there
Eli Friedmanef8c79c2011-07-26 23:27:24 +00001974 if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) {
Eli Friedmane52c9142011-07-26 22:25:31 +00001975 CXXDestructorDecl *dtor = PointeeRD->getDestructor();
Eli Friedmanef8c79c2011-07-26 23:27:24 +00001976 if (dtor && !dtor->isVirtual()) {
1977 if (PointeeRD->isAbstract()) {
1978 // If the class is abstract, we warn by default, because we're
1979 // sure the code has undefined behavior.
1980 Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor)
1981 << PointeeElem;
1982 } else if (!ArrayForm) {
1983 // Otherwise, if this is not an array delete, it's a bit suspect,
1984 // but not necessarily wrong.
1985 Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
1986 }
1987 }
Argyrios Kyrtzidis6f0074a2011-05-24 19:53:26 +00001988 }
John McCallf85e1932011-06-15 23:02:42 +00001989
1990 } else if (getLangOptions().ObjCAutoRefCount &&
1991 PointeeElem->isObjCLifetimeType() &&
1992 (PointeeElem.getObjCLifetime() == Qualifiers::OCL_Strong ||
1993 PointeeElem.getObjCLifetime() == Qualifiers::OCL_Weak) &&
1994 ArrayForm) {
1995 Diag(StartLoc, diag::warn_err_new_delete_object_array)
1996 << 1 << PointeeElem;
Anders Carlssond67c4c32009-08-16 20:29:29 +00001997 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001998
Anders Carlssond67c4c32009-08-16 20:29:29 +00001999 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00002000 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00002001 DeclareGlobalNewDelete();
2002 DeclContext *TUDecl = Context.getTranslationUnitDecl();
John Wiegley429bb272011-04-08 18:41:53 +00002003 Expr *Arg = Ex.get();
Mike Stump1eb44332009-09-09 15:08:12 +00002004 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
John Wiegley429bb272011-04-08 18:41:53 +00002005 &Arg, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00002006 OperatorDelete))
2007 return ExprError();
2008 }
Mike Stump1eb44332009-09-09 15:08:12 +00002009
John McCall9c82afc2010-04-20 02:18:25 +00002010 MarkDeclarationReferenced(StartLoc, OperatorDelete);
John McCall6ec278d2011-01-27 09:37:56 +00002011
Douglas Gregord880f522011-02-01 15:50:11 +00002012 // Check access and ambiguity of operator delete and destructor.
Eli Friedmane52c9142011-07-26 22:25:31 +00002013 if (PointeeRD) {
2014 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
John Wiegley429bb272011-04-08 18:41:53 +00002015 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregord880f522011-02-01 15:50:11 +00002016 PDiag(diag::err_access_dtor) << PointeeElem);
2017 }
2018 }
2019
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002020 }
2021
Sebastian Redlf53597f2009-03-15 17:47:39 +00002022 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
John McCall6ec278d2011-01-27 09:37:56 +00002023 ArrayFormAsWritten,
2024 UsualArrayDeleteWantsSize,
John Wiegley429bb272011-04-08 18:41:53 +00002025 OperatorDelete, Ex.take(), StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002026}
2027
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002028/// \brief Check the use of the given variable as a C++ condition in an if,
2029/// while, do-while, or switch statement.
John McCall60d7b3a2010-08-24 06:29:42 +00002030ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCallf89e55a2010-11-18 06:31:45 +00002031 SourceLocation StmtLoc,
2032 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002033 QualType T = ConditionVar->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002034
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002035 // C++ [stmt.select]p2:
2036 // The declarator shall not specify a function or an array.
2037 if (T->isFunctionType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002038 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002039 diag::err_invalid_use_of_function_type)
2040 << ConditionVar->getSourceRange());
2041 else if (T->isArrayType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002042 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002043 diag::err_invalid_use_of_array_type)
2044 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00002045
John Wiegley429bb272011-04-08 18:41:53 +00002046 ExprResult Condition =
2047 Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
Douglas Gregor40d96a62011-02-28 21:54:11 +00002048 ConditionVar,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002049 ConditionVar->getLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00002050 ConditionVar->getType().getNonReferenceType(),
John Wiegley429bb272011-04-08 18:41:53 +00002051 VK_LValue));
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002052
2053 MarkDeclarationReferenced(ConditionVar->getLocation(), ConditionVar);
2054
John Wiegley429bb272011-04-08 18:41:53 +00002055 if (ConvertToBoolean) {
2056 Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
2057 if (Condition.isInvalid())
2058 return ExprError();
2059 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002060
John Wiegley429bb272011-04-08 18:41:53 +00002061 return move(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002062}
2063
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002064/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
John Wiegley429bb272011-04-08 18:41:53 +00002065ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002066 // C++ 6.4p4:
2067 // The value of a condition that is an initialized declaration in a statement
2068 // other than a switch statement is the value of the declared variable
2069 // implicitly converted to type bool. If that conversion is ill-formed, the
2070 // program is ill-formed.
2071 // The value of a condition that is an expression is the value of the
2072 // expression, implicitly converted to bool.
2073 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002074 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002075}
Douglas Gregor77a52232008-09-12 00:47:35 +00002076
2077/// Helper function to determine whether this is the (deprecated) C++
2078/// conversion from a string literal to a pointer to non-const char or
2079/// non-const wchar_t (for narrow and wide string literals,
2080/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00002081bool
Douglas Gregor77a52232008-09-12 00:47:35 +00002082Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
2083 // Look inside the implicit cast, if it exists.
2084 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
2085 From = Cast->getSubExpr();
2086
2087 // A string literal (2.13.4) that is not a wide string literal can
2088 // be converted to an rvalue of type "pointer to char"; a wide
2089 // string literal can be converted to an rvalue of type "pointer
2090 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00002091 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00002092 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00002093 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00002094 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00002095 // This conversion is considered only when there is an
2096 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregor5cee1192011-07-27 05:40:30 +00002097 if (!ToPtrType->getPointeeType().hasQualifiers()) {
2098 switch (StrLit->getKind()) {
2099 case StringLiteral::UTF8:
2100 case StringLiteral::UTF16:
2101 case StringLiteral::UTF32:
2102 // We don't allow UTF literals to be implicitly converted
2103 break;
2104 case StringLiteral::Ascii:
2105 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
2106 ToPointeeType->getKind() == BuiltinType::Char_S);
2107 case StringLiteral::Wide:
2108 return ToPointeeType->isWideCharType();
2109 }
2110 }
Douglas Gregor77a52232008-09-12 00:47:35 +00002111 }
2112
2113 return false;
2114}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002115
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002116static ExprResult BuildCXXCastArgument(Sema &S,
John McCall2de56d12010-08-25 11:45:40 +00002117 SourceLocation CastLoc,
2118 QualType Ty,
2119 CastKind Kind,
2120 CXXMethodDecl *Method,
John McCallca82a822011-09-21 08:36:56 +00002121 DeclAccessPair FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002122 bool HadMultipleCandidates,
John McCall2de56d12010-08-25 11:45:40 +00002123 Expr *From) {
Douglas Gregorba70ab62010-04-16 22:17:36 +00002124 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002125 default: llvm_unreachable("Unhandled cast kind!");
John McCall2de56d12010-08-25 11:45:40 +00002126 case CK_ConstructorConversion: {
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002127 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
John McCallca0408f2010-08-23 06:44:23 +00002128 ASTOwningVector<Expr*> ConstructorArgs(S);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002129
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002130 if (S.CompleteConstructorCall(Constructor,
John McCallf312b1e2010-08-26 23:41:50 +00002131 MultiExprArg(&From, 1),
Douglas Gregorba70ab62010-04-16 22:17:36 +00002132 CastLoc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00002133 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002134
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002135 S.CheckConstructorAccess(CastLoc, Constructor, Constructor->getAccess(),
2136 S.PDiag(diag::err_access_ctor));
2137
2138 ExprResult Result
2139 = S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2140 move_arg(ConstructorArgs),
2141 HadMultipleCandidates, /*ZeroInit*/ false,
2142 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregorba70ab62010-04-16 22:17:36 +00002143 if (Result.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00002144 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002145
Douglas Gregorba70ab62010-04-16 22:17:36 +00002146 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
2147 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002148
John McCall2de56d12010-08-25 11:45:40 +00002149 case CK_UserDefinedConversion: {
Douglas Gregorba70ab62010-04-16 22:17:36 +00002150 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002151
Douglas Gregorba70ab62010-04-16 22:17:36 +00002152 // Create an implicit call expr that calls it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002153 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method,
2154 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00002155 if (Result.isInvalid())
2156 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00002157 // Record usage of conversion in an implicit cast.
2158 Result = S.Owned(ImplicitCastExpr::Create(S.Context,
2159 Result.get()->getType(),
2160 CK_UserDefinedConversion,
2161 Result.get(), 0,
2162 Result.get()->getValueKind()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002163
John McCallca82a822011-09-21 08:36:56 +00002164 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ 0, FoundDecl);
2165
Douglas Gregorf2ae5262011-01-20 00:18:04 +00002166 return S.MaybeBindToTemporary(Result.get());
Douglas Gregorba70ab62010-04-16 22:17:36 +00002167 }
2168 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002169}
Douglas Gregorba70ab62010-04-16 22:17:36 +00002170
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002171/// PerformImplicitConversion - Perform an implicit conversion of the
2172/// expression From to the type ToType using the pre-computed implicit
John Wiegley429bb272011-04-08 18:41:53 +00002173/// conversion sequence ICS. Returns the converted
Douglas Gregor68647482009-12-16 03:45:30 +00002174/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002175/// used in the error message.
John Wiegley429bb272011-04-08 18:41:53 +00002176ExprResult
2177Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002178 const ImplicitConversionSequence &ICS,
John McCallf85e1932011-06-15 23:02:42 +00002179 AssignmentAction Action,
2180 CheckedConversionKind CCK) {
John McCall1d318332010-01-12 00:44:57 +00002181 switch (ICS.getKind()) {
John Wiegley429bb272011-04-08 18:41:53 +00002182 case ImplicitConversionSequence::StandardConversion: {
Richard Smithc8d7f582011-11-29 22:48:16 +00002183 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
2184 Action, CCK);
John Wiegley429bb272011-04-08 18:41:53 +00002185 if (Res.isInvalid())
2186 return ExprError();
2187 From = Res.take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002188 break;
John Wiegley429bb272011-04-08 18:41:53 +00002189 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002190
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002191 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002192
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00002193 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCalldaa8e4e2010-11-15 09:13:47 +00002194 CastKind CastKind;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002195 QualType BeforeToType;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00002196 assert(FD && "FIXME: aggregate initialization from init list");
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002197 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCall2de56d12010-08-25 11:45:40 +00002198 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002199
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002200 // If the user-defined conversion is specified by a conversion function,
2201 // the initial standard conversion sequence converts the source type to
2202 // the implicit object parameter of the conversion function.
2203 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCall9ec94452010-12-04 09:57:16 +00002204 } else {
2205 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCall2de56d12010-08-25 11:45:40 +00002206 CastKind = CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002207 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00002208 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002209 // If the user-defined conversion is specified by a constructor, the
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002210 // initial standard conversion sequence converts the source type to the
2211 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00002212 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
2213 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002214 }
Douglas Gregora3998bd2010-12-02 21:47:04 +00002215 // Watch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00002216 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley429bb272011-04-08 18:41:53 +00002217 ExprResult Res =
Richard Smithc8d7f582011-11-29 22:48:16 +00002218 PerformImplicitConversion(From, BeforeToType,
2219 ICS.UserDefined.Before, AA_Converting,
2220 CCK);
John Wiegley429bb272011-04-08 18:41:53 +00002221 if (Res.isInvalid())
2222 return ExprError();
2223 From = Res.take();
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002224 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002225
2226 ExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00002227 = BuildCXXCastArgument(*this,
2228 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00002229 ToType.getNonReferenceType(),
Douglas Gregor83eecbe2011-01-20 01:32:05 +00002230 CastKind, cast<CXXMethodDecl>(FD),
2231 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002232 ICS.UserDefined.HadMultipleCandidates,
John McCall9ae2f072010-08-23 23:25:46 +00002233 From);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002234
2235 if (CastArg.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00002236 return ExprError();
Eli Friedmand8889622009-11-27 04:41:50 +00002237
John Wiegley429bb272011-04-08 18:41:53 +00002238 From = CastArg.take();
Eli Friedmand8889622009-11-27 04:41:50 +00002239
Richard Smithc8d7f582011-11-29 22:48:16 +00002240 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
2241 AA_Converting, CCK);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00002242 }
John McCall1d318332010-01-12 00:44:57 +00002243
2244 case ImplicitConversionSequence::AmbiguousConversion:
John McCall120d63c2010-08-24 20:38:10 +00002245 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall1d318332010-01-12 00:44:57 +00002246 PDiag(diag::err_typecheck_ambiguous_condition)
2247 << From->getSourceRange());
John Wiegley429bb272011-04-08 18:41:53 +00002248 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002249
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002250 case ImplicitConversionSequence::EllipsisConversion:
David Blaikieb219cfc2011-09-23 05:06:16 +00002251 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002252
2253 case ImplicitConversionSequence::BadConversion:
John Wiegley429bb272011-04-08 18:41:53 +00002254 return ExprError();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002255 }
2256
2257 // Everything went well.
John Wiegley429bb272011-04-08 18:41:53 +00002258 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002259}
2260
Richard Smithc8d7f582011-11-29 22:48:16 +00002261/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002262/// expression From to the type ToType by following the standard
John Wiegley429bb272011-04-08 18:41:53 +00002263/// conversion sequence SCS. Returns the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00002264/// expression. Flavor is the context in which we're performing this
2265/// conversion, for use in error messages.
John Wiegley429bb272011-04-08 18:41:53 +00002266ExprResult
Richard Smithc8d7f582011-11-29 22:48:16 +00002267Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00002268 const StandardConversionSequence& SCS,
John McCallf85e1932011-06-15 23:02:42 +00002269 AssignmentAction Action,
2270 CheckedConversionKind CCK) {
2271 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
2272
Mike Stump390b4cc2009-05-16 07:39:55 +00002273 // Overall FIXME: we are recomputing too many types here and doing far too
2274 // much extra work. What this means is that we need to keep track of more
2275 // information that is computed when we try the implicit conversion initially,
2276 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002277 QualType FromType = From->getType();
John McCallf85e1932011-06-15 23:02:42 +00002278
Douglas Gregor225c41e2008-11-03 19:09:14 +00002279 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00002280 // FIXME: When can ToType be a reference type?
2281 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002282 if (SCS.Second == ICK_Derived_To_Base) {
John McCallca0408f2010-08-23 06:44:23 +00002283 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002284 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCallca0408f2010-08-23 06:44:23 +00002285 MultiExprArg(*this, &From, 1),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002286 /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002287 ConstructorArgs))
John Wiegley429bb272011-04-08 18:41:53 +00002288 return ExprError();
2289 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2290 ToType, SCS.CopyConstructor,
2291 move_arg(ConstructorArgs),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002292 /*HadMultipleCandidates*/ false,
John Wiegley429bb272011-04-08 18:41:53 +00002293 /*ZeroInit*/ false,
2294 CXXConstructExpr::CK_Complete,
2295 SourceRange());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002296 }
John Wiegley429bb272011-04-08 18:41:53 +00002297 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2298 ToType, SCS.CopyConstructor,
2299 MultiExprArg(*this, &From, 1),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002300 /*HadMultipleCandidates*/ false,
John Wiegley429bb272011-04-08 18:41:53 +00002301 /*ZeroInit*/ false,
2302 CXXConstructExpr::CK_Complete,
2303 SourceRange());
Douglas Gregor225c41e2008-11-03 19:09:14 +00002304 }
2305
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002306 // Resolve overloaded function references.
2307 if (Context.hasSameType(FromType, Context.OverloadTy)) {
2308 DeclAccessPair Found;
2309 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2310 true, Found);
2311 if (!Fn)
John Wiegley429bb272011-04-08 18:41:53 +00002312 return ExprError();
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002313
2314 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
John Wiegley429bb272011-04-08 18:41:53 +00002315 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002316
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002317 From = FixOverloadedFunctionReference(From, Found, Fn);
2318 FromType = From->getType();
2319 }
2320
Richard Smithc8d7f582011-11-29 22:48:16 +00002321 // Perform the first implicit conversion.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002322 switch (SCS.First) {
2323 case ICK_Identity:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002324 // Nothing to do.
2325 break;
2326
John McCallf6a16482010-12-04 03:47:34 +00002327 case ICK_Lvalue_To_Rvalue:
John McCall3c3b7f92011-10-25 17:37:35 +00002328 assert(From->getObjectKind() != OK_ObjCProperty);
John McCallf6a16482010-12-04 03:47:34 +00002329 FromType = FromType.getUnqualifiedType();
2330 From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
2331 From, 0, VK_RValue);
2332 break;
2333
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002334 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002335 FromType = Context.getArrayDecayedType(FromType);
Richard Smithc8d7f582011-11-29 22:48:16 +00002336 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
2337 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002338 break;
2339
2340 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002341 FromType = Context.getPointerType(FromType);
Richard Smithc8d7f582011-11-29 22:48:16 +00002342 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
2343 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002344 break;
2345
2346 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002347 llvm_unreachable("Improper first standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002348 }
2349
Richard Smithc8d7f582011-11-29 22:48:16 +00002350 // Perform the second implicit conversion
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002351 switch (SCS.Second) {
2352 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002353 // If both sides are functions (or pointers/references to them), there could
2354 // be incompatible exception declarations.
2355 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002356 return ExprError();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002357 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002358 break;
2359
Douglas Gregor43c79c22009-12-09 00:47:37 +00002360 case ICK_NoReturn_Adjustment:
2361 // If both sides are functions (or pointers/references to them), there could
2362 // be incompatible exception declarations.
2363 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002364 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002365
Richard Smithc8d7f582011-11-29 22:48:16 +00002366 From = ImpCastExprToType(From, ToType, CK_NoOp,
2367 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor43c79c22009-12-09 00:47:37 +00002368 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002369
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002370 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002371 case ICK_Integral_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002372 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
2373 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002374 break;
2375
2376 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002377 case ICK_Floating_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002378 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
2379 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002380 break;
2381
2382 case ICK_Complex_Promotion:
John McCalldaa8e4e2010-11-15 09:13:47 +00002383 case ICK_Complex_Conversion: {
2384 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2385 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2386 CastKind CK;
2387 if (FromEl->isRealFloatingType()) {
2388 if (ToEl->isRealFloatingType())
2389 CK = CK_FloatingComplexCast;
2390 else
2391 CK = CK_FloatingComplexToIntegralComplex;
2392 } else if (ToEl->isRealFloatingType()) {
2393 CK = CK_IntegralComplexToFloatingComplex;
2394 } else {
2395 CK = CK_IntegralComplexCast;
2396 }
Richard Smithc8d7f582011-11-29 22:48:16 +00002397 From = ImpCastExprToType(From, ToType, CK,
2398 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002399 break;
John McCalldaa8e4e2010-11-15 09:13:47 +00002400 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00002401
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002402 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00002403 if (ToType->isRealFloatingType())
Richard Smithc8d7f582011-11-29 22:48:16 +00002404 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
2405 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002406 else
Richard Smithc8d7f582011-11-29 22:48:16 +00002407 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
2408 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002409 break;
2410
Douglas Gregorf9201e02009-02-11 23:02:49 +00002411 case ICK_Compatible_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002412 From = ImpCastExprToType(From, ToType, CK_NoOp,
2413 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002414 break;
2415
John McCallf85e1932011-06-15 23:02:42 +00002416 case ICK_Writeback_Conversion:
Anders Carlsson61faec12009-09-12 04:46:44 +00002417 case ICK_Pointer_Conversion: {
Douglas Gregora3998bd2010-12-02 21:47:04 +00002418 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor45920e82008-12-19 17:40:08 +00002419 // Diagnose incompatible Objective-C conversions
Douglas Gregor8cf0d222011-06-11 04:42:12 +00002420 if (Action == AA_Initializing || Action == AA_Assigning)
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002421 Diag(From->getSourceRange().getBegin(),
2422 diag::ext_typecheck_convert_incompatible_pointer)
2423 << ToType << From->getType() << Action
Anna Zaks67221552011-07-28 19:51:27 +00002424 << From->getSourceRange() << 0;
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002425 else
2426 Diag(From->getSourceRange().getBegin(),
2427 diag::ext_typecheck_convert_incompatible_pointer)
2428 << From->getType() << ToType << Action
Anna Zaks67221552011-07-28 19:51:27 +00002429 << From->getSourceRange() << 0;
John McCallf85e1932011-06-15 23:02:42 +00002430
Douglas Gregor926df6c2011-06-11 01:09:30 +00002431 if (From->getType()->isObjCObjectPointerType() &&
2432 ToType->isObjCObjectPointerType())
2433 EmitRelatedResultTypeNote(From);
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002434 }
2435 else if (getLangOptions().ObjCAutoRefCount &&
2436 !CheckObjCARCUnavailableWeakConversion(ToType,
2437 From->getType())) {
John McCall7f3a6d32011-09-09 06:12:06 +00002438 if (Action == AA_Initializing)
2439 Diag(From->getSourceRange().getBegin(),
2440 diag::err_arc_weak_unavailable_assign);
2441 else
2442 Diag(From->getSourceRange().getBegin(),
2443 diag::err_arc_convesion_of_weak_unavailable)
2444 << (Action == AA_Casting) << From->getType() << ToType
2445 << From->getSourceRange();
2446 }
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002447
John McCalldaa8e4e2010-11-15 09:13:47 +00002448 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002449 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002450 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002451 return ExprError();
John McCalldc05b112011-09-10 01:16:55 +00002452
2453 // Make sure we extend blocks if necessary.
2454 // FIXME: doing this here is really ugly.
2455 if (Kind == CK_BlockPointerToObjCPointerCast) {
2456 ExprResult E = From;
2457 (void) PrepareCastToObjCObjectPointer(E);
2458 From = E.take();
2459 }
2460
Richard Smithc8d7f582011-11-29 22:48:16 +00002461 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2462 .take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002463 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00002464 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002465
Anders Carlsson61faec12009-09-12 04:46:44 +00002466 case ICK_Pointer_Member: {
John McCalldaa8e4e2010-11-15 09:13:47 +00002467 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002468 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002469 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002470 return ExprError();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002471 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002472 return ExprError();
Richard Smithc8d7f582011-11-29 22:48:16 +00002473 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2474 .take();
Anders Carlsson61faec12009-09-12 04:46:44 +00002475 break;
2476 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002477
Abramo Bagnara737d5442011-04-07 09:26:19 +00002478 case ICK_Boolean_Conversion:
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00002479 // Perform half-to-boolean conversion via float.
2480 if (From->getType()->isHalfType()) {
2481 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).take();
2482 FromType = Context.FloatTy;
2483 }
2484
Richard Smithc8d7f582011-11-29 22:48:16 +00002485 From = ImpCastExprToType(From, Context.BoolTy,
2486 ScalarTypeToBooleanCastKind(FromType),
2487 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002488 break;
2489
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002490 case ICK_Derived_To_Base: {
John McCallf871d0c2010-08-07 06:22:56 +00002491 CXXCastPath BasePath;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002492 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002493 ToType.getNonReferenceType(),
2494 From->getLocStart(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002495 From->getSourceRange(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002496 &BasePath,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002497 CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002498 return ExprError();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002499
Richard Smithc8d7f582011-11-29 22:48:16 +00002500 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
2501 CK_DerivedToBase, From->getValueKind(),
2502 &BasePath, CCK).take();
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002503 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002504 }
2505
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002506 case ICK_Vector_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002507 From = ImpCastExprToType(From, ToType, CK_BitCast,
2508 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002509 break;
2510
2511 case ICK_Vector_Splat:
Richard Smithc8d7f582011-11-29 22:48:16 +00002512 From = ImpCastExprToType(From, ToType, CK_VectorSplat,
2513 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002514 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002515
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002516 case ICK_Complex_Real:
John McCalldaa8e4e2010-11-15 09:13:47 +00002517 // Case 1. x -> _Complex y
2518 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2519 QualType ElType = ToComplex->getElementType();
2520 bool isFloatingComplex = ElType->isRealFloatingType();
2521
2522 // x -> y
2523 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2524 // do nothing
2525 } else if (From->getType()->isRealFloatingType()) {
Richard Smithc8d7f582011-11-29 22:48:16 +00002526 From = ImpCastExprToType(From, ElType,
2527 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002528 } else {
2529 assert(From->getType()->isIntegerType());
Richard Smithc8d7f582011-11-29 22:48:16 +00002530 From = ImpCastExprToType(From, ElType,
2531 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002532 }
2533 // y -> _Complex y
Richard Smithc8d7f582011-11-29 22:48:16 +00002534 From = ImpCastExprToType(From, ToType,
2535 isFloatingComplex ? CK_FloatingRealToComplex
2536 : CK_IntegralRealToComplex).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002537
2538 // Case 2. _Complex x -> y
2539 } else {
2540 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2541 assert(FromComplex);
2542
2543 QualType ElType = FromComplex->getElementType();
2544 bool isFloatingComplex = ElType->isRealFloatingType();
2545
2546 // _Complex x -> x
Richard Smithc8d7f582011-11-29 22:48:16 +00002547 From = ImpCastExprToType(From, ElType,
2548 isFloatingComplex ? CK_FloatingComplexToReal
2549 : CK_IntegralComplexToReal,
2550 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002551
2552 // x -> y
2553 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2554 // do nothing
2555 } else if (ToType->isRealFloatingType()) {
Richard Smithc8d7f582011-11-29 22:48:16 +00002556 From = ImpCastExprToType(From, ToType,
2557 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
2558 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002559 } else {
2560 assert(ToType->isIntegerType());
Richard Smithc8d7f582011-11-29 22:48:16 +00002561 From = ImpCastExprToType(From, ToType,
2562 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
2563 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002564 }
2565 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002566 break;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002567
2568 case ICK_Block_Pointer_Conversion: {
Richard Smithc8d7f582011-11-29 22:48:16 +00002569 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
2570 VK_RValue, /*BasePath=*/0, CCK).take();
John McCallf85e1932011-06-15 23:02:42 +00002571 break;
2572 }
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002573
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002574 case ICK_TransparentUnionConversion: {
John Wiegley429bb272011-04-08 18:41:53 +00002575 ExprResult FromRes = Owned(From);
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002576 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00002577 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
2578 if (FromRes.isInvalid())
2579 return ExprError();
2580 From = FromRes.take();
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002581 assert ((ConvTy == Sema::Compatible) &&
2582 "Improper transparent union conversion");
2583 (void)ConvTy;
2584 break;
2585 }
2586
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002587 case ICK_Lvalue_To_Rvalue:
2588 case ICK_Array_To_Pointer:
2589 case ICK_Function_To_Pointer:
2590 case ICK_Qualification:
2591 case ICK_Num_Conversion_Kinds:
David Blaikieb219cfc2011-09-23 05:06:16 +00002592 llvm_unreachable("Improper second standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002593 }
2594
2595 switch (SCS.Third) {
2596 case ICK_Identity:
2597 // Nothing to do.
2598 break;
2599
Sebastian Redl906082e2010-07-20 04:20:21 +00002600 case ICK_Qualification: {
2601 // The qualification keeps the category of the inner expression, unless the
2602 // target type isn't a reference.
John McCall5baba9d2010-08-25 10:28:54 +00002603 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00002604 From->getValueKind() : VK_RValue;
Richard Smithc8d7f582011-11-29 22:48:16 +00002605 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
2606 CK_NoOp, VK, /*BasePath=*/0, CCK).take();
Douglas Gregora9bff302010-02-28 18:30:25 +00002607
Douglas Gregor069a6da2011-03-14 16:13:32 +00002608 if (SCS.DeprecatedStringLiteralToCharPtr &&
2609 !getLangOptions().WritableStrings)
Douglas Gregora9bff302010-02-28 18:30:25 +00002610 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2611 << ToType.getNonReferenceType();
2612
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002613 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002614 }
2615
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002616 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002617 llvm_unreachable("Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002618 }
2619
John Wiegley429bb272011-04-08 18:41:53 +00002620 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002621}
2622
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002623ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002624 SourceLocation KWLoc,
2625 ParsedType Ty,
2626 SourceLocation RParen) {
2627 TypeSourceInfo *TSInfo;
2628 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002629
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002630 if (!TSInfo)
2631 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002632 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002633}
2634
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002635/// \brief Check the completeness of a type in a unary type trait.
2636///
2637/// If the particular type trait requires a complete type, tries to complete
2638/// it. If completing the type fails, a diagnostic is emitted and false
2639/// returned. If completing the type succeeds or no completion was required,
2640/// returns true.
2641static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S,
2642 UnaryTypeTrait UTT,
2643 SourceLocation Loc,
2644 QualType ArgTy) {
2645 // C++0x [meta.unary.prop]p3:
2646 // For all of the class templates X declared in this Clause, instantiating
2647 // that template with a template argument that is a class template
2648 // specialization may result in the implicit instantiation of the template
2649 // argument if and only if the semantics of X require that the argument
2650 // must be a complete type.
2651 // We apply this rule to all the type trait expressions used to implement
2652 // these class templates. We also try to follow any GCC documented behavior
2653 // in these expressions to ensure portability of standard libraries.
2654 switch (UTT) {
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002655 // is_complete_type somewhat obviously cannot require a complete type.
2656 case UTT_IsCompleteType:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002657 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002658
2659 // These traits are modeled on the type predicates in C++0x
2660 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
2661 // requiring a complete type, as whether or not they return true cannot be
2662 // impacted by the completeness of the type.
2663 case UTT_IsVoid:
2664 case UTT_IsIntegral:
2665 case UTT_IsFloatingPoint:
2666 case UTT_IsArray:
2667 case UTT_IsPointer:
2668 case UTT_IsLvalueReference:
2669 case UTT_IsRvalueReference:
2670 case UTT_IsMemberFunctionPointer:
2671 case UTT_IsMemberObjectPointer:
2672 case UTT_IsEnum:
2673 case UTT_IsUnion:
2674 case UTT_IsClass:
2675 case UTT_IsFunction:
2676 case UTT_IsReference:
2677 case UTT_IsArithmetic:
2678 case UTT_IsFundamental:
2679 case UTT_IsObject:
2680 case UTT_IsScalar:
2681 case UTT_IsCompound:
2682 case UTT_IsMemberPointer:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002683 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002684
2685 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
2686 // which requires some of its traits to have the complete type. However,
2687 // the completeness of the type cannot impact these traits' semantics, and
2688 // so they don't require it. This matches the comments on these traits in
2689 // Table 49.
2690 case UTT_IsConst:
2691 case UTT_IsVolatile:
2692 case UTT_IsSigned:
2693 case UTT_IsUnsigned:
2694 return true;
2695
2696 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002697 // applied to a complete type.
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002698 case UTT_IsTrivial:
Sean Huntfeb375d2011-05-13 00:31:07 +00002699 case UTT_IsTriviallyCopyable:
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002700 case UTT_IsStandardLayout:
2701 case UTT_IsPOD:
2702 case UTT_IsLiteral:
2703 case UTT_IsEmpty:
2704 case UTT_IsPolymorphic:
2705 case UTT_IsAbstract:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002706 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002707
Douglas Gregor5e9392b2011-12-03 18:14:24 +00002708 // These traits require a complete type.
2709 case UTT_IsFinal:
2710
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002711 // These trait expressions are designed to help implement predicates in
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002712 // [meta.unary.prop] despite not being named the same. They are specified
2713 // by both GCC and the Embarcadero C++ compiler, and require the complete
2714 // type due to the overarching C++0x type predicates being implemented
2715 // requiring the complete type.
2716 case UTT_HasNothrowAssign:
2717 case UTT_HasNothrowConstructor:
2718 case UTT_HasNothrowCopy:
2719 case UTT_HasTrivialAssign:
Sean Hunt023df372011-05-09 18:22:59 +00002720 case UTT_HasTrivialDefaultConstructor:
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002721 case UTT_HasTrivialCopy:
2722 case UTT_HasTrivialDestructor:
2723 case UTT_HasVirtualDestructor:
2724 // Arrays of unknown bound are expressly allowed.
2725 QualType ElTy = ArgTy;
2726 if (ArgTy->isIncompleteArrayType())
2727 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
2728
2729 // The void type is expressly allowed.
2730 if (ElTy->isVoidType())
2731 return true;
2732
2733 return !S.RequireCompleteType(
2734 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleycf566412011-04-28 02:06:46 +00002735 }
Chandler Carruth73e0a912011-05-01 07:23:17 +00002736 llvm_unreachable("Type trait not handled by switch");
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002737}
2738
2739static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT,
2740 SourceLocation KeyLoc, QualType T) {
Chandler Carruthd064c702011-05-01 08:41:10 +00002741 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleycf566412011-04-28 02:06:46 +00002742
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002743 ASTContext &C = Self.Context;
2744 switch(UTT) {
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002745 // Type trait expressions corresponding to the primary type category
2746 // predicates in C++0x [meta.unary.cat].
2747 case UTT_IsVoid:
2748 return T->isVoidType();
2749 case UTT_IsIntegral:
2750 return T->isIntegralType(C);
2751 case UTT_IsFloatingPoint:
2752 return T->isFloatingType();
2753 case UTT_IsArray:
2754 return T->isArrayType();
2755 case UTT_IsPointer:
2756 return T->isPointerType();
2757 case UTT_IsLvalueReference:
2758 return T->isLValueReferenceType();
2759 case UTT_IsRvalueReference:
2760 return T->isRValueReferenceType();
2761 case UTT_IsMemberFunctionPointer:
2762 return T->isMemberFunctionPointerType();
2763 case UTT_IsMemberObjectPointer:
2764 return T->isMemberDataPointerType();
2765 case UTT_IsEnum:
2766 return T->isEnumeralType();
Chandler Carruth28eeb382011-05-01 06:11:03 +00002767 case UTT_IsUnion:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002768 return T->isUnionType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002769 case UTT_IsClass:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002770 return T->isClassType() || T->isStructureType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002771 case UTT_IsFunction:
2772 return T->isFunctionType();
2773
2774 // Type trait expressions which correspond to the convenient composition
2775 // predicates in C++0x [meta.unary.comp].
2776 case UTT_IsReference:
2777 return T->isReferenceType();
2778 case UTT_IsArithmetic:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002779 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002780 case UTT_IsFundamental:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002781 return T->isFundamentalType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002782 case UTT_IsObject:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002783 return T->isObjectType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002784 case UTT_IsScalar:
John McCallf85e1932011-06-15 23:02:42 +00002785 // Note: semantic analysis depends on Objective-C lifetime types to be
2786 // considered scalar types. However, such types do not actually behave
2787 // like scalar types at run time (since they may require retain/release
2788 // operations), so we report them as non-scalar.
2789 if (T->isObjCLifetimeType()) {
2790 switch (T.getObjCLifetime()) {
2791 case Qualifiers::OCL_None:
2792 case Qualifiers::OCL_ExplicitNone:
2793 return true;
2794
2795 case Qualifiers::OCL_Strong:
2796 case Qualifiers::OCL_Weak:
2797 case Qualifiers::OCL_Autoreleasing:
2798 return false;
2799 }
2800 }
2801
Chandler Carruthcec0ced2011-05-01 09:29:55 +00002802 return T->isScalarType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002803 case UTT_IsCompound:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002804 return T->isCompoundType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002805 case UTT_IsMemberPointer:
2806 return T->isMemberPointerType();
2807
2808 // Type trait expressions which correspond to the type property predicates
2809 // in C++0x [meta.unary.prop].
2810 case UTT_IsConst:
2811 return T.isConstQualified();
2812 case UTT_IsVolatile:
2813 return T.isVolatileQualified();
2814 case UTT_IsTrivial:
John McCallf85e1932011-06-15 23:02:42 +00002815 return T.isTrivialType(Self.Context);
Sean Huntfeb375d2011-05-13 00:31:07 +00002816 case UTT_IsTriviallyCopyable:
John McCallf85e1932011-06-15 23:02:42 +00002817 return T.isTriviallyCopyableType(Self.Context);
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002818 case UTT_IsStandardLayout:
2819 return T->isStandardLayoutType();
2820 case UTT_IsPOD:
John McCallf85e1932011-06-15 23:02:42 +00002821 return T.isPODType(Self.Context);
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002822 case UTT_IsLiteral:
2823 return T->isLiteralType();
2824 case UTT_IsEmpty:
2825 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2826 return !RD->isUnion() && RD->isEmpty();
2827 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002828 case UTT_IsPolymorphic:
Chandler Carruth28eeb382011-05-01 06:11:03 +00002829 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2830 return RD->isPolymorphic();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002831 return false;
2832 case UTT_IsAbstract:
Chandler Carruth28eeb382011-05-01 06:11:03 +00002833 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2834 return RD->isAbstract();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002835 return false;
Douglas Gregor5e9392b2011-12-03 18:14:24 +00002836 case UTT_IsFinal:
2837 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2838 return RD->hasAttr<FinalAttr>();
2839 return false;
John Wiegley20c0da72011-04-27 23:09:49 +00002840 case UTT_IsSigned:
2841 return T->isSignedIntegerType();
John Wiegley20c0da72011-04-27 23:09:49 +00002842 case UTT_IsUnsigned:
2843 return T->isUnsignedIntegerType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002844
2845 // Type trait expressions which query classes regarding their construction,
2846 // destruction, and copying. Rather than being based directly on the
2847 // related type predicates in the standard, they are specified by both
2848 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
2849 // specifications.
2850 //
2851 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
2852 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Sean Hunt023df372011-05-09 18:22:59 +00002853 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002854 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2855 // If __is_pod (type) is true then the trait is true, else if type is
2856 // a cv class or union type (or array thereof) with a trivial default
2857 // constructor ([class.ctor]) then the trait is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00002858 if (T.isPODType(Self.Context))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002859 return true;
2860 if (const RecordType *RT =
2861 C.getBaseElementType(T)->getAs<RecordType>())
Sean Hunt023df372011-05-09 18:22:59 +00002862 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDefaultConstructor();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002863 return false;
2864 case UTT_HasTrivialCopy:
2865 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2866 // If __is_pod (type) is true or type is a reference type then
2867 // the trait is true, else if type is a cv class or union type
2868 // with a trivial copy constructor ([class.copy]) then the trait
2869 // is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00002870 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002871 return true;
2872 if (const RecordType *RT = T->getAs<RecordType>())
2873 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2874 return false;
2875 case UTT_HasTrivialAssign:
2876 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2877 // If type is const qualified or is a reference type then the
2878 // trait is false. Otherwise if __is_pod (type) is true then the
2879 // trait is true, else if type is a cv class or union type with
2880 // a trivial copy assignment ([class.copy]) then the trait is
2881 // true, else it is false.
2882 // Note: the const and reference restrictions are interesting,
2883 // given that const and reference members don't prevent a class
2884 // from having a trivial copy assignment operator (but do cause
2885 // errors if the copy assignment operator is actually used, q.v.
2886 // [class.copy]p12).
2887
2888 if (C.getBaseElementType(T).isConstQualified())
2889 return false;
John McCallf85e1932011-06-15 23:02:42 +00002890 if (T.isPODType(Self.Context))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002891 return true;
2892 if (const RecordType *RT = T->getAs<RecordType>())
2893 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2894 return false;
2895 case UTT_HasTrivialDestructor:
2896 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2897 // If __is_pod (type) is true or type is a reference type
2898 // then the trait is true, else if type is a cv class or union
2899 // type (or array thereof) with a trivial destructor
2900 // ([class.dtor]) then the trait is true, else it is
2901 // false.
John McCallf85e1932011-06-15 23:02:42 +00002902 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002903 return true;
John McCallf85e1932011-06-15 23:02:42 +00002904
2905 // Objective-C++ ARC: autorelease types don't require destruction.
2906 if (T->isObjCLifetimeType() &&
2907 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
2908 return true;
2909
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002910 if (const RecordType *RT =
2911 C.getBaseElementType(T)->getAs<RecordType>())
2912 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2913 return false;
2914 // TODO: Propagate nothrowness for implicitly declared special members.
2915 case UTT_HasNothrowAssign:
2916 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2917 // If type is const qualified or is a reference type then the
2918 // trait is false. Otherwise if __has_trivial_assign (type)
2919 // is true then the trait is true, else if type is a cv class
2920 // or union type with copy assignment operators that are known
2921 // not to throw an exception then the trait is true, else it is
2922 // false.
2923 if (C.getBaseElementType(T).isConstQualified())
2924 return false;
2925 if (T->isReferenceType())
2926 return false;
John McCallf85e1932011-06-15 23:02:42 +00002927 if (T.isPODType(Self.Context) || T->isObjCLifetimeType())
2928 return true;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002929 if (const RecordType *RT = T->getAs<RecordType>()) {
2930 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2931 if (RD->hasTrivialCopyAssignment())
2932 return true;
2933
2934 bool FoundAssign = false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002935 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redlf8aca862010-09-14 23:40:14 +00002936 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2937 Sema::LookupOrdinaryName);
2938 if (Self.LookupQualifiedName(Res, RD)) {
Douglas Gregord41679d2011-10-12 15:40:49 +00002939 Res.suppressDiagnostics();
Sebastian Redlf8aca862010-09-14 23:40:14 +00002940 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2941 Op != OpEnd; ++Op) {
Douglas Gregord41679d2011-10-12 15:40:49 +00002942 if (isa<FunctionTemplateDecl>(*Op))
2943 continue;
2944
Sebastian Redlf8aca862010-09-14 23:40:14 +00002945 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2946 if (Operator->isCopyAssignmentOperator()) {
2947 FoundAssign = true;
2948 const FunctionProtoType *CPT
2949 = Operator->getType()->getAs<FunctionProtoType>();
Richard Smith7a614d82011-06-11 17:19:42 +00002950 if (CPT->getExceptionSpecType() == EST_Delayed)
2951 return false;
2952 if (!CPT->isNothrow(Self.Context))
2953 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002954 }
2955 }
2956 }
Douglas Gregord41679d2011-10-12 15:40:49 +00002957
Richard Smith7a614d82011-06-11 17:19:42 +00002958 return FoundAssign;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002959 }
2960 return false;
2961 case UTT_HasNothrowCopy:
2962 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2963 // If __has_trivial_copy (type) is true then the trait is true, else
2964 // if type is a cv class or union type with copy constructors that are
2965 // known not to throw an exception then the trait is true, else it is
2966 // false.
John McCallf85e1932011-06-15 23:02:42 +00002967 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002968 return true;
2969 if (const RecordType *RT = T->getAs<RecordType>()) {
2970 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2971 if (RD->hasTrivialCopyConstructor())
2972 return true;
2973
2974 bool FoundConstructor = false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002975 unsigned FoundTQs;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002976 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl5f4e8992010-09-13 21:10:20 +00002977 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002978 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002979 // A template constructor is never a copy constructor.
2980 // FIXME: However, it may actually be selected at the actual overload
2981 // resolution point.
2982 if (isa<FunctionTemplateDecl>(*Con))
2983 continue;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002984 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2985 if (Constructor->isCopyConstructor(FoundTQs)) {
2986 FoundConstructor = true;
2987 const FunctionProtoType *CPT
2988 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smith7a614d82011-06-11 17:19:42 +00002989 if (CPT->getExceptionSpecType() == EST_Delayed)
2990 return false;
Sebastian Redl60618fa2011-03-12 11:50:43 +00002991 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redl751025d2010-09-13 22:02:47 +00002992 // For now, we'll be conservative and assume that they can throw.
Richard Smith7a614d82011-06-11 17:19:42 +00002993 if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1)
2994 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002995 }
2996 }
2997
Richard Smith7a614d82011-06-11 17:19:42 +00002998 return FoundConstructor;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002999 }
3000 return false;
3001 case UTT_HasNothrowConstructor:
3002 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3003 // If __has_trivial_constructor (type) is true then the trait is
3004 // true, else if type is a cv class or union type (or array
3005 // thereof) with a default constructor that is known not to
3006 // throw an exception then the trait is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00003007 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003008 return true;
3009 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
3010 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Hunt023df372011-05-09 18:22:59 +00003011 if (RD->hasTrivialDefaultConstructor())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003012 return true;
3013
Sebastian Redl751025d2010-09-13 22:02:47 +00003014 DeclContext::lookup_const_iterator Con, ConEnd;
3015 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
3016 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00003017 // FIXME: In C++0x, a constructor template can be a default constructor.
3018 if (isa<FunctionTemplateDecl>(*Con))
3019 continue;
Sebastian Redl751025d2010-09-13 22:02:47 +00003020 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3021 if (Constructor->isDefaultConstructor()) {
3022 const FunctionProtoType *CPT
3023 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smith7a614d82011-06-11 17:19:42 +00003024 if (CPT->getExceptionSpecType() == EST_Delayed)
3025 return false;
Sebastian Redl751025d2010-09-13 22:02:47 +00003026 // TODO: check whether evaluating default arguments can throw.
3027 // For now, we'll be conservative and assume that they can throw.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00003028 return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
Sebastian Redl751025d2010-09-13 22:02:47 +00003029 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003030 }
3031 }
3032 return false;
3033 case UTT_HasVirtualDestructor:
3034 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3035 // If type is a class type with a virtual destructor ([class.dtor])
3036 // then the trait is true, else it is false.
3037 if (const RecordType *Record = T->getAs<RecordType>()) {
3038 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redlf8aca862010-09-14 23:40:14 +00003039 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003040 return Destructor->isVirtual();
3041 }
3042 return false;
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003043
3044 // These type trait expressions are modeled on the specifications for the
3045 // Embarcadero C++0x type trait functions:
3046 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
3047 case UTT_IsCompleteType:
3048 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
3049 // Returns True if and only if T is a complete type at the point of the
3050 // function call.
3051 return !T->isIncompleteType();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003052 }
Chandler Carruth83f563c2011-05-01 07:44:17 +00003053 llvm_unreachable("Type trait not covered by switch");
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003054}
3055
3056ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00003057 SourceLocation KWLoc,
3058 TypeSourceInfo *TSInfo,
3059 SourceLocation RParen) {
3060 QualType T = TSInfo->getType();
Chandler Carrutheb65a102011-04-30 10:07:32 +00003061 if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T))
3062 return ExprError();
Sebastian Redl64b45f72009-01-05 20:52:13 +00003063
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003064 bool Value = false;
3065 if (!T->isDependentType())
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00003066 Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003067
3068 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson3292d5c2009-07-07 19:06:02 +00003069 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00003070}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003071
Francois Pichet6ad6f282010-12-07 00:08:36 +00003072ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
3073 SourceLocation KWLoc,
3074 ParsedType LhsTy,
3075 ParsedType RhsTy,
3076 SourceLocation RParen) {
3077 TypeSourceInfo *LhsTSInfo;
3078 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
3079 if (!LhsTSInfo)
3080 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
3081
3082 TypeSourceInfo *RhsTSInfo;
3083 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
3084 if (!RhsTSInfo)
3085 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
3086
3087 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
3088}
3089
3090static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
3091 QualType LhsT, QualType RhsT,
3092 SourceLocation KeyLoc) {
Chandler Carruthd064c702011-05-01 08:41:10 +00003093 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
3094 "Cannot evaluate traits of dependent types");
Francois Pichet6ad6f282010-12-07 00:08:36 +00003095
3096 switch(BTT) {
John McCalld89d30f2011-01-28 22:02:36 +00003097 case BTT_IsBaseOf: {
Francois Pichet6ad6f282010-12-07 00:08:36 +00003098 // C++0x [meta.rel]p2
John McCalld89d30f2011-01-28 22:02:36 +00003099 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet6ad6f282010-12-07 00:08:36 +00003100 // Base and Derived are not unions and name the same class type without
3101 // regard to cv-qualifiers.
Francois Pichet6ad6f282010-12-07 00:08:36 +00003102
John McCalld89d30f2011-01-28 22:02:36 +00003103 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
3104 if (!lhsRecord) return false;
3105
3106 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
3107 if (!rhsRecord) return false;
3108
3109 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
3110 == (lhsRecord == rhsRecord));
3111
3112 if (lhsRecord == rhsRecord)
3113 return !lhsRecord->getDecl()->isUnion();
3114
3115 // C++0x [meta.rel]p2:
3116 // If Base and Derived are class types and are different types
3117 // (ignoring possible cv-qualifiers) then Derived shall be a
3118 // complete type.
3119 if (Self.RequireCompleteType(KeyLoc, RhsT,
3120 diag::err_incomplete_type_used_in_type_trait_expr))
3121 return false;
3122
3123 return cast<CXXRecordDecl>(rhsRecord->getDecl())
3124 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
3125 }
John Wiegley20c0da72011-04-27 23:09:49 +00003126 case BTT_IsSame:
3127 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichetf1872372010-12-08 22:35:30 +00003128 case BTT_TypeCompatible:
3129 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
3130 RhsT.getUnqualifiedType());
John Wiegley20c0da72011-04-27 23:09:49 +00003131 case BTT_IsConvertible:
Douglas Gregor9f361132011-01-27 20:28:01 +00003132 case BTT_IsConvertibleTo: {
3133 // C++0x [meta.rel]p4:
3134 // Given the following function prototype:
3135 //
3136 // template <class T>
3137 // typename add_rvalue_reference<T>::type create();
3138 //
3139 // the predicate condition for a template specialization
3140 // is_convertible<From, To> shall be satisfied if and only if
3141 // the return expression in the following code would be
3142 // well-formed, including any implicit conversions to the return
3143 // type of the function:
3144 //
3145 // To test() {
3146 // return create<From>();
3147 // }
3148 //
3149 // Access checking is performed as if in a context unrelated to To and
3150 // From. Only the validity of the immediate context of the expression
3151 // of the return-statement (including conversions to the return type)
3152 // is considered.
3153 //
3154 // We model the initialization as a copy-initialization of a temporary
3155 // of the appropriate type, which for this expression is identical to the
3156 // return statement (since NRVO doesn't apply).
3157 if (LhsT->isObjectType() || LhsT->isFunctionType())
3158 LhsT = Self.Context.getRValueReferenceType(LhsT);
3159
3160 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorb608b982011-01-28 02:26:04 +00003161 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor9f361132011-01-27 20:28:01 +00003162 Expr::getValueKindForType(LhsT));
3163 Expr *FromPtr = &From;
3164 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
3165 SourceLocation()));
3166
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00003167 // Perform the initialization within a SFINAE trap at translation unit
3168 // scope.
3169 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3170 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Douglas Gregor9f361132011-01-27 20:28:01 +00003171 InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003172 if (Init.Failed())
Douglas Gregor9f361132011-01-27 20:28:01 +00003173 return false;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00003174
Douglas Gregor9f361132011-01-27 20:28:01 +00003175 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
3176 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
3177 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00003178 }
3179 llvm_unreachable("Unknown type trait or not implemented");
3180}
3181
3182ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
3183 SourceLocation KWLoc,
3184 TypeSourceInfo *LhsTSInfo,
3185 TypeSourceInfo *RhsTSInfo,
3186 SourceLocation RParen) {
3187 QualType LhsT = LhsTSInfo->getType();
3188 QualType RhsT = RhsTSInfo->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003189
John McCalld89d30f2011-01-28 22:02:36 +00003190 if (BTT == BTT_TypeCompatible) {
Francois Pichetf1872372010-12-08 22:35:30 +00003191 if (getLangOptions().CPlusPlus) {
3192 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
3193 << SourceRange(KWLoc, RParen);
3194 return ExprError();
3195 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00003196 }
3197
3198 bool Value = false;
3199 if (!LhsT->isDependentType() && !RhsT->isDependentType())
3200 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
3201
Francois Pichetf1872372010-12-08 22:35:30 +00003202 // Select trait result type.
3203 QualType ResultType;
3204 switch (BTT) {
Francois Pichetf1872372010-12-08 22:35:30 +00003205 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
John Wiegley20c0da72011-04-27 23:09:49 +00003206 case BTT_IsConvertible: ResultType = Context.BoolTy; break;
3207 case BTT_IsSame: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00003208 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
Douglas Gregor9f361132011-01-27 20:28:01 +00003209 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00003210 }
3211
Francois Pichet6ad6f282010-12-07 00:08:36 +00003212 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
3213 RhsTSInfo, Value, RParen,
Francois Pichetf1872372010-12-08 22:35:30 +00003214 ResultType));
Francois Pichet6ad6f282010-12-07 00:08:36 +00003215}
3216
John Wiegley21ff2e52011-04-28 00:16:57 +00003217ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3218 SourceLocation KWLoc,
3219 ParsedType Ty,
3220 Expr* DimExpr,
3221 SourceLocation RParen) {
3222 TypeSourceInfo *TSInfo;
3223 QualType T = GetTypeFromParser(Ty, &TSInfo);
3224 if (!TSInfo)
3225 TSInfo = Context.getTrivialTypeSourceInfo(T);
3226
3227 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
3228}
3229
3230static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
3231 QualType T, Expr *DimExpr,
3232 SourceLocation KeyLoc) {
Chandler Carruthd064c702011-05-01 08:41:10 +00003233 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley21ff2e52011-04-28 00:16:57 +00003234
3235 switch(ATT) {
3236 case ATT_ArrayRank:
3237 if (T->isArrayType()) {
3238 unsigned Dim = 0;
3239 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3240 ++Dim;
3241 T = AT->getElementType();
3242 }
3243 return Dim;
John Wiegley21ff2e52011-04-28 00:16:57 +00003244 }
John Wiegleycf566412011-04-28 02:06:46 +00003245 return 0;
3246
John Wiegley21ff2e52011-04-28 00:16:57 +00003247 case ATT_ArrayExtent: {
3248 llvm::APSInt Value;
3249 uint64_t Dim;
John Wiegleycf566412011-04-28 02:06:46 +00003250 if (DimExpr->isIntegerConstantExpr(Value, Self.Context, 0, false)) {
3251 if (Value < llvm::APSInt(Value.getBitWidth(), Value.isUnsigned())) {
3252 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
3253 DimExpr->getSourceRange();
3254 return false;
3255 }
John Wiegley21ff2e52011-04-28 00:16:57 +00003256 Dim = Value.getLimitedValue();
John Wiegleycf566412011-04-28 02:06:46 +00003257 } else {
3258 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
3259 DimExpr->getSourceRange();
3260 return false;
3261 }
John Wiegley21ff2e52011-04-28 00:16:57 +00003262
3263 if (T->isArrayType()) {
3264 unsigned D = 0;
3265 bool Matched = false;
3266 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3267 if (Dim == D) {
3268 Matched = true;
3269 break;
3270 }
3271 ++D;
3272 T = AT->getElementType();
3273 }
3274
John Wiegleycf566412011-04-28 02:06:46 +00003275 if (Matched && T->isArrayType()) {
3276 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
3277 return CAT->getSize().getLimitedValue();
3278 }
John Wiegley21ff2e52011-04-28 00:16:57 +00003279 }
John Wiegleycf566412011-04-28 02:06:46 +00003280 return 0;
John Wiegley21ff2e52011-04-28 00:16:57 +00003281 }
3282 }
3283 llvm_unreachable("Unknown type trait or not implemented");
3284}
3285
3286ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
3287 SourceLocation KWLoc,
3288 TypeSourceInfo *TSInfo,
3289 Expr* DimExpr,
3290 SourceLocation RParen) {
3291 QualType T = TSInfo->getType();
John Wiegley21ff2e52011-04-28 00:16:57 +00003292
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003293 // FIXME: This should likely be tracked as an APInt to remove any host
3294 // assumptions about the width of size_t on the target.
Chandler Carruthd064c702011-05-01 08:41:10 +00003295 uint64_t Value = 0;
3296 if (!T->isDependentType())
3297 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
3298
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003299 // While the specification for these traits from the Embarcadero C++
3300 // compiler's documentation says the return type is 'unsigned int', Clang
3301 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
3302 // compiler, there is no difference. On several other platforms this is an
3303 // important distinction.
John Wiegley21ff2e52011-04-28 00:16:57 +00003304 return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value,
Chandler Carruth06207f62011-05-01 07:49:26 +00003305 DimExpr, RParen,
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003306 Context.getSizeType()));
John Wiegley21ff2e52011-04-28 00:16:57 +00003307}
3308
John Wiegley55262202011-04-25 06:54:41 +00003309ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003310 SourceLocation KWLoc,
3311 Expr *Queried,
3312 SourceLocation RParen) {
John Wiegley55262202011-04-25 06:54:41 +00003313 // If error parsing the expression, ignore.
3314 if (!Queried)
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003315 return ExprError();
John Wiegley55262202011-04-25 06:54:41 +00003316
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003317 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegley55262202011-04-25 06:54:41 +00003318
3319 return move(Result);
3320}
3321
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003322static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
3323 switch (ET) {
3324 case ET_IsLValueExpr: return E->isLValue();
3325 case ET_IsRValueExpr: return E->isRValue();
3326 }
3327 llvm_unreachable("Expression trait not covered by switch");
3328}
3329
John Wiegley55262202011-04-25 06:54:41 +00003330ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003331 SourceLocation KWLoc,
3332 Expr *Queried,
3333 SourceLocation RParen) {
John Wiegley55262202011-04-25 06:54:41 +00003334 if (Queried->isTypeDependent()) {
3335 // Delay type-checking for type-dependent expressions.
3336 } else if (Queried->getType()->isPlaceholderType()) {
3337 ExprResult PE = CheckPlaceholderExpr(Queried);
3338 if (PE.isInvalid()) return ExprError();
3339 return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen);
3340 }
3341
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003342 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf7ef0002011-05-01 08:48:19 +00003343
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003344 return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value,
3345 RParen, Context.BoolTy));
John Wiegley55262202011-04-25 06:54:41 +00003346}
3347
Richard Trieudd225092011-09-15 21:56:47 +00003348QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCallf89e55a2010-11-18 06:31:45 +00003349 ExprValueKind &VK,
3350 SourceLocation Loc,
3351 bool isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003352 assert(!LHS.get()->getType()->isPlaceholderType() &&
3353 !RHS.get()->getType()->isPlaceholderType() &&
John McCallea4aba02011-06-30 17:15:34 +00003354 "placeholders should have been weeded out by now");
3355
3356 // The LHS undergoes lvalue conversions if this is ->*.
3357 if (isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003358 LHS = DefaultLvalueConversion(LHS.take());
3359 if (LHS.isInvalid()) return QualType();
John McCallea4aba02011-06-30 17:15:34 +00003360 }
3361
3362 // The RHS always undergoes lvalue conversions.
Richard Trieudd225092011-09-15 21:56:47 +00003363 RHS = DefaultLvalueConversion(RHS.take());
3364 if (RHS.isInvalid()) return QualType();
John McCallea4aba02011-06-30 17:15:34 +00003365
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003366 const char *OpSpelling = isIndirect ? "->*" : ".*";
3367 // C++ 5.5p2
3368 // The binary operator .* [p3: ->*] binds its second operand, which shall
3369 // be of type "pointer to member of T" (where T is a completely-defined
3370 // class type) [...]
Richard Trieudd225092011-09-15 21:56:47 +00003371 QualType RHSType = RHS.get()->getType();
3372 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00003373 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003374 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieudd225092011-09-15 21:56:47 +00003375 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003376 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00003377 }
Douglas Gregore7450f52009-03-24 19:52:54 +00003378
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003379 QualType Class(MemPtr->getClass(), 0);
3380
Douglas Gregor7d520ba2010-10-13 20:41:14 +00003381 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
3382 // member pointer points must be completely-defined. However, there is no
3383 // reason for this semantic distinction, and the rule is not enforced by
3384 // other compilers. Therefore, we do not check this property, as it is
3385 // likely to be considered a defect.
Sebastian Redl59fc2692010-04-10 10:14:54 +00003386
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003387 // C++ 5.5p2
3388 // [...] to its first operand, which shall be of class T or of a class of
3389 // which T is an unambiguous and accessible base class. [p3: a pointer to
3390 // such a class]
Richard Trieudd225092011-09-15 21:56:47 +00003391 QualType LHSType = LHS.get()->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003392 if (isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003393 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
3394 LHSType = Ptr->getPointeeType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003395 else {
3396 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieudd225092011-09-15 21:56:47 +00003397 << OpSpelling << 1 << LHSType
Douglas Gregor849b2432010-03-31 17:46:05 +00003398 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003399 return QualType();
3400 }
3401 }
3402
Richard Trieudd225092011-09-15 21:56:47 +00003403 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00003404 // If we want to check the hierarchy, we need a complete type.
Richard Trieudd225092011-09-15 21:56:47 +00003405 if (RequireCompleteType(Loc, LHSType, PDiag(diag::err_bad_memptr_lhs)
Sebastian Redl17e1d352010-04-23 17:18:26 +00003406 << OpSpelling << (int)isIndirect)) {
3407 return QualType();
3408 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003409 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00003410 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00003411 // FIXME: Would it be useful to print full ambiguity paths, or is that
3412 // overkill?
Richard Trieudd225092011-09-15 21:56:47 +00003413 if (!IsDerivedFrom(LHSType, Class, Paths) ||
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003414 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
3415 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieudd225092011-09-15 21:56:47 +00003416 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003417 return QualType();
3418 }
Eli Friedman3005efe2010-01-16 00:00:48 +00003419 // Cast LHS to type of use.
3420 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00003421 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Sebastian Redl906082e2010-07-20 04:20:21 +00003422
John McCallf871d0c2010-08-07 06:22:56 +00003423 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003424 BuildBasePathArray(Paths, BasePath);
Richard Trieudd225092011-09-15 21:56:47 +00003425 LHS = ImpCastExprToType(LHS.take(), UseType, CK_DerivedToBase, VK,
3426 &BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003427 }
3428
Richard Trieudd225092011-09-15 21:56:47 +00003429 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00003430 // Diagnose use of pointer-to-member type which when used as
3431 // the functional cast in a pointer-to-member expression.
3432 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
3433 return QualType();
3434 }
John McCallf89e55a2010-11-18 06:31:45 +00003435
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003436 // C++ 5.5p2
3437 // The result is an object or a function of the type specified by the
3438 // second operand.
3439 // The cv qualifiers are the union of those in the pointer and the left side,
3440 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003441 QualType Result = MemPtr->getPointeeType();
Richard Trieudd225092011-09-15 21:56:47 +00003442 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCallf89e55a2010-11-18 06:31:45 +00003443
Douglas Gregor6b4df912011-01-26 16:40:18 +00003444 // C++0x [expr.mptr.oper]p6:
3445 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003446 // ill-formed if the second operand is a pointer to member function with
3447 // ref-qualifier &. In a ->* expression or in a .* expression whose object
3448 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor6b4df912011-01-26 16:40:18 +00003449 // is a pointer to member function with ref-qualifier &&.
3450 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
3451 switch (Proto->getRefQualifier()) {
3452 case RQ_None:
3453 // Do nothing
3454 break;
3455
3456 case RQ_LValue:
Richard Trieudd225092011-09-15 21:56:47 +00003457 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
Douglas Gregor6b4df912011-01-26 16:40:18 +00003458 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieudd225092011-09-15 21:56:47 +00003459 << RHSType << 1 << LHS.get()->getSourceRange();
Douglas Gregor6b4df912011-01-26 16:40:18 +00003460 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003461
Douglas Gregor6b4df912011-01-26 16:40:18 +00003462 case RQ_RValue:
Richard Trieudd225092011-09-15 21:56:47 +00003463 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor6b4df912011-01-26 16:40:18 +00003464 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieudd225092011-09-15 21:56:47 +00003465 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor6b4df912011-01-26 16:40:18 +00003466 break;
3467 }
3468 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003469
John McCallf89e55a2010-11-18 06:31:45 +00003470 // C++ [expr.mptr.oper]p6:
3471 // The result of a .* expression whose second operand is a pointer
3472 // to a data member is of the same value category as its
3473 // first operand. The result of a .* expression whose second
3474 // operand is a pointer to a member function is a prvalue. The
3475 // result of an ->* expression is an lvalue if its second operand
3476 // is a pointer to data member and a prvalue otherwise.
John McCall864c0412011-04-26 20:42:42 +00003477 if (Result->isFunctionType()) {
John McCallf89e55a2010-11-18 06:31:45 +00003478 VK = VK_RValue;
John McCall864c0412011-04-26 20:42:42 +00003479 return Context.BoundMemberTy;
3480 } else if (isIndirect) {
John McCallf89e55a2010-11-18 06:31:45 +00003481 VK = VK_LValue;
John McCall864c0412011-04-26 20:42:42 +00003482 } else {
Richard Trieudd225092011-09-15 21:56:47 +00003483 VK = LHS.get()->getValueKind();
John McCall864c0412011-04-26 20:42:42 +00003484 }
John McCallf89e55a2010-11-18 06:31:45 +00003485
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003486 return Result;
3487}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003488
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003489/// \brief Try to convert a type to another according to C++0x 5.16p3.
3490///
3491/// This is part of the parameter validation for the ? operator. If either
3492/// value operand is a class type, the two operands are attempted to be
3493/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003494/// It returns true if the program is ill-formed and has already been diagnosed
3495/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003496static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
3497 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00003498 bool &HaveConversion,
3499 QualType &ToType) {
3500 HaveConversion = false;
3501 ToType = To->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003502
3503 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00003504 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003505 // C++0x 5.16p3
3506 // The process for determining whether an operand expression E1 of type T1
3507 // can be converted to match an operand expression E2 of type T2 is defined
3508 // as follows:
3509 // -- If E2 is an lvalue:
John McCall7eb0a9e2010-11-24 05:12:34 +00003510 bool ToIsLvalue = To->isLValue();
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00003511 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003512 // E1 can be converted to match E2 if E1 can be implicitly converted to
3513 // type "lvalue reference to T2", subject to the constraint that in the
3514 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003515 QualType T = Self.Context.getLValueReferenceType(ToType);
3516 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003517
Douglas Gregorb70cf442010-03-26 20:14:36 +00003518 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3519 if (InitSeq.isDirectReferenceBinding()) {
3520 ToType = T;
3521 HaveConversion = true;
3522 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003523 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003524
Douglas Gregorb70cf442010-03-26 20:14:36 +00003525 if (InitSeq.isAmbiguous())
3526 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003527 }
John McCallb1bdc622010-02-25 01:37:24 +00003528
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003529 // -- If E2 is an rvalue, or if the conversion above cannot be done:
3530 // -- if E1 and E2 have class type, and the underlying class types are
3531 // the same or one is a base class of the other:
3532 QualType FTy = From->getType();
3533 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003534 const RecordType *FRec = FTy->getAs<RecordType>();
3535 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003536 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00003537 Self.IsDerivedFrom(FTy, TTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003538 if (FRec && TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00003539 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003540 // E1 can be converted to match E2 if the class of T2 is the
3541 // same type as, or a base class of, the class of T1, and
3542 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00003543 if (FRec == TRec || FDerivedFromT) {
3544 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003545 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3546 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003547 if (InitSeq) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003548 HaveConversion = true;
3549 return false;
3550 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003551
Douglas Gregorb70cf442010-03-26 20:14:36 +00003552 if (InitSeq.isAmbiguous())
3553 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003554 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003555 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003556
Douglas Gregorb70cf442010-03-26 20:14:36 +00003557 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003558 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003559
Douglas Gregorb70cf442010-03-26 20:14:36 +00003560 // -- Otherwise: E1 can be converted to match E2 if E1 can be
3561 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003562 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00003563 // an rvalue).
3564 //
3565 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
3566 // to the array-to-pointer or function-to-pointer conversions.
3567 if (!TTy->getAs<TagType>())
3568 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003569
Douglas Gregorb70cf442010-03-26 20:14:36 +00003570 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3571 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003572 HaveConversion = !InitSeq.Failed();
Douglas Gregorb70cf442010-03-26 20:14:36 +00003573 ToType = TTy;
3574 if (InitSeq.isAmbiguous())
3575 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3576
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003577 return false;
3578}
3579
3580/// \brief Try to find a common type for two according to C++0x 5.16p5.
3581///
3582/// This is part of the parameter validation for the ? operator. If either
3583/// value operand is a class type, overload resolution is used to find a
3584/// conversion to a common type.
John Wiegley429bb272011-04-08 18:41:53 +00003585static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth82214a82011-02-18 23:54:50 +00003586 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00003587 Expr *Args[2] = { LHS.get(), RHS.get() };
Chandler Carruth82214a82011-02-18 23:54:50 +00003588 OverloadCandidateSet CandidateSet(QuestionLoc);
3589 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
3590 CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003591
3592 OverloadCandidateSet::iterator Best;
Chandler Carruth82214a82011-02-18 23:54:50 +00003593 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley429bb272011-04-08 18:41:53 +00003594 case OR_Success: {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003595 // We found a match. Perform the conversions on the arguments and move on.
John Wiegley429bb272011-04-08 18:41:53 +00003596 ExprResult LHSRes =
3597 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
3598 Best->Conversions[0], Sema::AA_Converting);
3599 if (LHSRes.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003600 break;
John Wiegley429bb272011-04-08 18:41:53 +00003601 LHS = move(LHSRes);
3602
3603 ExprResult RHSRes =
3604 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
3605 Best->Conversions[1], Sema::AA_Converting);
3606 if (RHSRes.isInvalid())
3607 break;
3608 RHS = move(RHSRes);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003609 if (Best->Function)
3610 Self.MarkDeclarationReferenced(QuestionLoc, Best->Function);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003611 return false;
John Wiegley429bb272011-04-08 18:41:53 +00003612 }
3613
Douglas Gregor20093b42009-12-09 23:02:17 +00003614 case OR_No_Viable_Function:
Chandler Carruth82214a82011-02-18 23:54:50 +00003615
3616 // Emit a better diagnostic if one of the expressions is a null pointer
3617 // constant and the other is a pointer type. In this case, the user most
3618 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00003619 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00003620 return true;
3621
3622 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00003623 << LHS.get()->getType() << RHS.get()->getType()
3624 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003625 return true;
3626
Douglas Gregor20093b42009-12-09 23:02:17 +00003627 case OR_Ambiguous:
Chandler Carruth82214a82011-02-18 23:54:50 +00003628 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley429bb272011-04-08 18:41:53 +00003629 << LHS.get()->getType() << RHS.get()->getType()
3630 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00003631 // FIXME: Print the possible common types by printing the return types of
3632 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003633 break;
3634
Douglas Gregor20093b42009-12-09 23:02:17 +00003635 case OR_Deleted:
David Blaikieb219cfc2011-09-23 05:06:16 +00003636 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003637 }
3638 return true;
3639}
3640
Sebastian Redl76458502009-04-17 16:30:52 +00003641/// \brief Perform an "extended" implicit conversion as returned by
3642/// TryClassUnification.
John Wiegley429bb272011-04-08 18:41:53 +00003643static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003644 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley429bb272011-04-08 18:41:53 +00003645 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00003646 SourceLocation());
John Wiegley429bb272011-04-08 18:41:53 +00003647 Expr *Arg = E.take();
3648 InitializationSequence InitSeq(Self, Entity, Kind, &Arg, 1);
3649 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&Arg, 1));
Douglas Gregorb70cf442010-03-26 20:14:36 +00003650 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00003651 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003652
John Wiegley429bb272011-04-08 18:41:53 +00003653 E = Result;
Sebastian Redl76458502009-04-17 16:30:52 +00003654 return false;
3655}
3656
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003657/// \brief Check the operands of ?: under C++ semantics.
3658///
3659/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
3660/// extension. In this case, LHS == Cond. (But they're not aliases.)
John Wiegley429bb272011-04-08 18:41:53 +00003661QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCall56ca35d2011-02-17 10:25:35 +00003662 ExprValueKind &VK, ExprObjectKind &OK,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003663 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00003664 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
3665 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003666
3667 // C++0x 5.16p1
3668 // The first expression is contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00003669 if (!Cond.get()->isTypeDependent()) {
3670 ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
3671 if (CondRes.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003672 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003673 Cond = move(CondRes);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003674 }
3675
John McCallf89e55a2010-11-18 06:31:45 +00003676 // Assume r-value.
3677 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00003678 OK = OK_Ordinary;
John McCallf89e55a2010-11-18 06:31:45 +00003679
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003680 // Either of the arguments dependent?
John Wiegley429bb272011-04-08 18:41:53 +00003681 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003682 return Context.DependentTy;
3683
3684 // C++0x 5.16p2
3685 // If either the second or the third operand has type (cv) void, ...
John Wiegley429bb272011-04-08 18:41:53 +00003686 QualType LTy = LHS.get()->getType();
3687 QualType RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003688 bool LVoid = LTy->isVoidType();
3689 bool RVoid = RTy->isVoidType();
3690 if (LVoid || RVoid) {
3691 // ... then the [l2r] conversions are performed on the second and third
3692 // operands ...
John Wiegley429bb272011-04-08 18:41:53 +00003693 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3694 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3695 if (LHS.isInvalid() || RHS.isInvalid())
3696 return QualType();
3697 LTy = LHS.get()->getType();
3698 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003699
3700 // ... and one of the following shall hold:
3701 // -- The second or the third operand (but not both) is a throw-
3702 // expression; the result is of the type of the other and is an rvalue.
John Wiegley429bb272011-04-08 18:41:53 +00003703 bool LThrow = isa<CXXThrowExpr>(LHS.get());
3704 bool RThrow = isa<CXXThrowExpr>(RHS.get());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003705 if (LThrow && !RThrow)
3706 return RTy;
3707 if (RThrow && !LThrow)
3708 return LTy;
3709
3710 // -- Both the second and third operands have type void; the result is of
3711 // type void and is an rvalue.
3712 if (LVoid && RVoid)
3713 return Context.VoidTy;
3714
3715 // Neither holds, error.
3716 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
3717 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley429bb272011-04-08 18:41:53 +00003718 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003719 return QualType();
3720 }
3721
3722 // Neither is void.
3723
3724 // C++0x 5.16p3
3725 // Otherwise, if the second and third operand have different types, and
3726 // either has (cv) class type, and attempt is made to convert each of those
3727 // operands to the other.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003728 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003729 (LTy->isRecordType() || RTy->isRecordType())) {
3730 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
3731 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003732 QualType L2RType, R2LType;
3733 bool HaveL2R, HaveR2L;
John Wiegley429bb272011-04-08 18:41:53 +00003734 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003735 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003736 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003737 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003738
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003739 // If both can be converted, [...] the program is ill-formed.
3740 if (HaveL2R && HaveR2L) {
3741 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley429bb272011-04-08 18:41:53 +00003742 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003743 return QualType();
3744 }
3745
3746 // If exactly one conversion is possible, that conversion is applied to
3747 // the chosen operand and the converted operands are used in place of the
3748 // original operands for the remainder of this section.
3749 if (HaveL2R) {
John Wiegley429bb272011-04-08 18:41:53 +00003750 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003751 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003752 LTy = LHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003753 } else if (HaveR2L) {
John Wiegley429bb272011-04-08 18:41:53 +00003754 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003755 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003756 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003757 }
3758 }
3759
3760 // C++0x 5.16p4
John McCallf89e55a2010-11-18 06:31:45 +00003761 // If the second and third operands are glvalues of the same value
3762 // category and have the same type, the result is of that type and
3763 // value category and it is a bit-field if the second or the third
3764 // operand is a bit-field, or if both are bit-fields.
John McCall09431682010-11-18 19:01:18 +00003765 // We only extend this to bitfields, not to the crazy other kinds of
3766 // l-values.
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003767 bool Same = Context.hasSameType(LTy, RTy);
John McCallf89e55a2010-11-18 06:31:45 +00003768 if (Same &&
John Wiegley429bb272011-04-08 18:41:53 +00003769 LHS.get()->isGLValue() &&
3770 LHS.get()->getValueKind() == RHS.get()->getValueKind() &&
3771 LHS.get()->isOrdinaryOrBitFieldObject() &&
3772 RHS.get()->isOrdinaryOrBitFieldObject()) {
3773 VK = LHS.get()->getValueKind();
3774 if (LHS.get()->getObjectKind() == OK_BitField ||
3775 RHS.get()->getObjectKind() == OK_BitField)
John McCall09431682010-11-18 19:01:18 +00003776 OK = OK_BitField;
John McCallf89e55a2010-11-18 06:31:45 +00003777 return LTy;
Fariborz Jahanian3911a1a2010-09-25 01:08:05 +00003778 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003779
3780 // C++0x 5.16p5
3781 // Otherwise, the result is an rvalue. If the second and third operands
3782 // do not have the same type, and either has (cv) class type, ...
3783 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
3784 // ... overload resolution is used to determine the conversions (if any)
3785 // to be applied to the operands. If the overload resolution fails, the
3786 // program is ill-formed.
3787 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
3788 return QualType();
3789 }
3790
3791 // C++0x 5.16p6
3792 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
3793 // conversions are performed on the second and third operands.
John Wiegley429bb272011-04-08 18:41:53 +00003794 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3795 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3796 if (LHS.isInvalid() || RHS.isInvalid())
3797 return QualType();
3798 LTy = LHS.get()->getType();
3799 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003800
3801 // After those conversions, one of the following shall hold:
3802 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00003803 // is of that type. If the operands have class type, the result
3804 // is a prvalue temporary of the result type, which is
3805 // copy-initialized from either the second operand or the third
3806 // operand depending on the value of the first operand.
3807 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
3808 if (LTy->isRecordType()) {
3809 // The operands have class type. Make a temporary copy.
3810 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003811 ExprResult LHSCopy = PerformCopyInitialization(Entity,
3812 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00003813 LHS);
Douglas Gregorb65a4582010-05-19 23:40:50 +00003814 if (LHSCopy.isInvalid())
3815 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003816
3817 ExprResult RHSCopy = PerformCopyInitialization(Entity,
3818 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00003819 RHS);
Douglas Gregorb65a4582010-05-19 23:40:50 +00003820 if (RHSCopy.isInvalid())
3821 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003822
John Wiegley429bb272011-04-08 18:41:53 +00003823 LHS = LHSCopy;
3824 RHS = RHSCopy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00003825 }
3826
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003827 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00003828 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003829
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003830 // Extension: conditional operator involving vector types.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003831 if (LTy->isVectorType() || RTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00003832 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003833
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003834 // -- The second and third operands have arithmetic or enumeration type;
3835 // the usual arithmetic conversions are performed to bring them to a
3836 // common type, and the result is of that type.
3837 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
3838 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00003839 if (LHS.isInvalid() || RHS.isInvalid())
3840 return QualType();
3841 return LHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003842 }
3843
3844 // -- The second and third operands have pointer type, or one has pointer
3845 // type and the other is a null pointer constant; pointer conversions
3846 // and qualification conversions are performed to bring them to their
3847 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00003848 // -- The second and third operands have pointer to member type, or one has
3849 // pointer to member type and the other is a null pointer constant;
3850 // pointer to member conversions and qualification conversions are
3851 // performed to bring them to a common type, whose cv-qualification
3852 // shall match the cv-qualification of either the second or the third
3853 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003854 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003855 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003856 isSFINAEContext()? 0 : &NonStandardCompositeType);
3857 if (!Composite.isNull()) {
3858 if (NonStandardCompositeType)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003859 Diag(QuestionLoc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003860 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
3861 << LTy << RTy << Composite
John Wiegley429bb272011-04-08 18:41:53 +00003862 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003863
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003864 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003865 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003866
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003867 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00003868 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
3869 if (!Composite.isNull())
3870 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003871
Chandler Carruth7ef93242011-02-19 00:13:59 +00003872 // Check if we are using a null with a non-pointer type.
John Wiegley429bb272011-04-08 18:41:53 +00003873 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth7ef93242011-02-19 00:13:59 +00003874 return QualType();
3875
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003876 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00003877 << LHS.get()->getType() << RHS.get()->getType()
3878 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003879 return QualType();
3880}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003881
3882/// \brief Find a merged pointer type and convert the two expressions to it.
3883///
Douglas Gregor20b3e992009-08-24 17:42:35 +00003884/// This finds the composite pointer type (or member pointer type) for @p E1
3885/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
3886/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003887/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003888///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003889/// \param Loc The location of the operator requiring these two expressions to
3890/// be converted to the composite pointer type.
3891///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003892/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
3893/// a non-standard (but still sane) composite type to which both expressions
3894/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
3895/// will be set true.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003896QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003897 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003898 bool *NonStandardCompositeType) {
3899 if (NonStandardCompositeType)
3900 *NonStandardCompositeType = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003901
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003902 assert(getLangOptions().CPlusPlus && "This function assumes C++");
3903 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003904
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00003905 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
3906 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00003907 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003908
3909 // C++0x 5.9p2
3910 // Pointer conversions and qualification conversions are performed on
3911 // pointer operands to bring them to their composite pointer type. If
3912 // one operand is a null pointer constant, the composite pointer type is
3913 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00003914 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003915 if (T2->isMemberPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00003916 E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003917 else
John Wiegley429bb272011-04-08 18:41:53 +00003918 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003919 return T2;
3920 }
Douglas Gregorce940492009-09-25 04:25:58 +00003921 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003922 if (T1->isMemberPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00003923 E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003924 else
John Wiegley429bb272011-04-08 18:41:53 +00003925 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003926 return T1;
3927 }
Mike Stump1eb44332009-09-09 15:08:12 +00003928
Douglas Gregor20b3e992009-08-24 17:42:35 +00003929 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003930 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
3931 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003932 return QualType();
3933
3934 // Otherwise, of one of the operands has type "pointer to cv1 void," then
3935 // the other has type "pointer to cv2 T" and the composite pointer type is
3936 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
3937 // Otherwise, the composite pointer type is a pointer type similar to the
3938 // type of one of the operands, with a cv-qualification signature that is
3939 // the union of the cv-qualification signatures of the operand types.
3940 // In practice, the first part here is redundant; it's subsumed by the second.
3941 // What we do here is, we build the two possible composite types, and try the
3942 // conversions in both directions. If only one works, or if the two composite
3943 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00003944 // FIXME: extended qualifiers?
Chris Lattner5f9e2722011-07-23 10:55:15 +00003945 typedef SmallVector<unsigned, 4> QualifierVector;
Sebastian Redla439e6f2009-11-16 21:03:45 +00003946 QualifierVector QualifierUnion;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003947 typedef SmallVector<std::pair<const Type *, const Type *>, 4>
Sebastian Redla439e6f2009-11-16 21:03:45 +00003948 ContainingClassVector;
3949 ContainingClassVector MemberOfClass;
3950 QualType Composite1 = Context.getCanonicalType(T1),
3951 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003952 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00003953 do {
3954 const PointerType *Ptr1, *Ptr2;
3955 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3956 (Ptr2 = Composite2->getAs<PointerType>())) {
3957 Composite1 = Ptr1->getPointeeType();
3958 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003959
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003960 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003961 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003962 if (NonStandardCompositeType &&
3963 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3964 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003965
Douglas Gregor20b3e992009-08-24 17:42:35 +00003966 QualifierUnion.push_back(
3967 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3968 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3969 continue;
3970 }
Mike Stump1eb44332009-09-09 15:08:12 +00003971
Douglas Gregor20b3e992009-08-24 17:42:35 +00003972 const MemberPointerType *MemPtr1, *MemPtr2;
3973 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3974 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3975 Composite1 = MemPtr1->getPointeeType();
3976 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003977
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003978 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003979 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003980 if (NonStandardCompositeType &&
3981 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3982 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003983
Douglas Gregor20b3e992009-08-24 17:42:35 +00003984 QualifierUnion.push_back(
3985 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3986 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
3987 MemPtr2->getClass()));
3988 continue;
3989 }
Mike Stump1eb44332009-09-09 15:08:12 +00003990
Douglas Gregor20b3e992009-08-24 17:42:35 +00003991 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00003992
Douglas Gregor20b3e992009-08-24 17:42:35 +00003993 // Cannot unwrap any more types.
3994 break;
3995 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00003996
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003997 if (NeedConstBefore && NonStandardCompositeType) {
3998 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003999 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004000 // requirements of C++ [conv.qual]p4 bullet 3.
4001 for (unsigned I = 0; I != NeedConstBefore; ++I) {
4002 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
4003 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
4004 *NonStandardCompositeType = true;
4005 }
4006 }
4007 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004008
Douglas Gregor20b3e992009-08-24 17:42:35 +00004009 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00004010 ContainingClassVector::reverse_iterator MOC
4011 = MemberOfClass.rbegin();
4012 for (QualifierVector::reverse_iterator
4013 I = QualifierUnion.rbegin(),
4014 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00004015 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00004016 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00004017 if (MOC->first && MOC->second) {
4018 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00004019 Composite1 = Context.getMemberPointerType(
4020 Context.getQualifiedType(Composite1, Quals),
4021 MOC->first);
4022 Composite2 = Context.getMemberPointerType(
4023 Context.getQualifiedType(Composite2, Quals),
4024 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00004025 } else {
4026 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00004027 Composite1
4028 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
4029 Composite2
4030 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00004031 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004032 }
4033
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004034 // Try to convert to the first composite pointer type.
4035 InitializedEntity Entity1
4036 = InitializedEntity::InitializeTemporary(Composite1);
4037 InitializationKind Kind
4038 = InitializationKind::CreateCopy(Loc, SourceLocation());
4039 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
4040 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00004041
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004042 if (E1ToC1 && E2ToC1) {
4043 // Conversion to Composite1 is viable.
4044 if (!Context.hasSameType(Composite1, Composite2)) {
4045 // Composite2 is a different type from Composite1. Check whether
4046 // Composite2 is also viable.
4047 InitializedEntity Entity2
4048 = InitializedEntity::InitializeTemporary(Composite2);
4049 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4050 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4051 if (E1ToC2 && E2ToC2) {
4052 // Both Composite1 and Composite2 are viable and are different;
4053 // this is an ambiguity.
4054 return QualType();
4055 }
4056 }
4057
4058 // Convert E1 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00004059 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00004060 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004061 if (E1Result.isInvalid())
4062 return QualType();
4063 E1 = E1Result.takeAs<Expr>();
4064
4065 // Convert E2 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00004066 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00004067 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004068 if (E2Result.isInvalid())
4069 return QualType();
4070 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004071
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004072 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004073 }
4074
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004075 // Check whether Composite2 is viable.
4076 InitializedEntity Entity2
4077 = InitializedEntity::InitializeTemporary(Composite2);
4078 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4079 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4080 if (!E1ToC2 || !E2ToC2)
4081 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004082
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004083 // Convert E1 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00004084 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00004085 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004086 if (E1Result.isInvalid())
4087 return QualType();
4088 E1 = E1Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004089
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004090 // Convert E2 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00004091 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00004092 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004093 if (E2Result.isInvalid())
4094 return QualType();
4095 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004096
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004097 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004098}
Anders Carlsson165a0a02009-05-17 18:41:29 +00004099
John McCall60d7b3a2010-08-24 06:29:42 +00004100ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor19cc1c72010-11-01 21:10:29 +00004101 if (!E)
4102 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004103
John McCallf85e1932011-06-15 23:02:42 +00004104 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
4105
4106 // If the result is a glvalue, we shouldn't bind it.
4107 if (!E->isRValue())
Anders Carlsson089c2602009-08-15 23:41:35 +00004108 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004109
John McCallf85e1932011-06-15 23:02:42 +00004110 // In ARC, calls that return a retainable type can return retained,
4111 // in which case we have to insert a consuming cast.
4112 if (getLangOptions().ObjCAutoRefCount &&
4113 E->getType()->isObjCRetainableType()) {
4114
4115 bool ReturnsRetained;
4116
4117 // For actual calls, we compute this by examining the type of the
4118 // called value.
4119 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
4120 Expr *Callee = Call->getCallee()->IgnoreParens();
4121 QualType T = Callee->getType();
4122
4123 if (T == Context.BoundMemberTy) {
4124 // Handle pointer-to-members.
4125 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
4126 T = BinOp->getRHS()->getType();
4127 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
4128 T = Mem->getMemberDecl()->getType();
4129 }
4130
4131 if (const PointerType *Ptr = T->getAs<PointerType>())
4132 T = Ptr->getPointeeType();
4133 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
4134 T = Ptr->getPointeeType();
4135 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
4136 T = MemPtr->getPointeeType();
4137
4138 const FunctionType *FTy = T->getAs<FunctionType>();
4139 assert(FTy && "call to value not of function type?");
4140 ReturnsRetained = FTy->getExtInfo().getProducesResult();
4141
4142 // ActOnStmtExpr arranges things so that StmtExprs of retainable
4143 // type always produce a +1 object.
4144 } else if (isa<StmtExpr>(E)) {
4145 ReturnsRetained = true;
4146
4147 // For message sends and property references, we try to find an
4148 // actual method. FIXME: we should infer retention by selector in
4149 // cases where we don't have an actual method.
4150 } else {
John McCallfc4b1912011-08-03 07:02:44 +00004151 ObjCMethodDecl *D = 0;
John McCallf85e1932011-06-15 23:02:42 +00004152 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
4153 D = Send->getMethodDecl();
John McCallf85e1932011-06-15 23:02:42 +00004154 }
4155
4156 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCallfc4b1912011-08-03 07:02:44 +00004157
4158 // Don't do reclaims on performSelector calls; despite their
4159 // return type, the invoked method doesn't necessarily actually
4160 // return an object.
4161 if (!ReturnsRetained &&
4162 D && D->getMethodFamily() == OMF_performSelector)
4163 return Owned(E);
John McCallf85e1932011-06-15 23:02:42 +00004164 }
4165
John McCall567c5862011-11-14 19:53:16 +00004166 // Don't reclaim an object of Class type.
4167 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
4168 return Owned(E);
4169
John McCall7e5e5f42011-07-07 06:58:02 +00004170 ExprNeedsCleanups = true;
4171
John McCall33e56f32011-09-10 06:18:15 +00004172 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
4173 : CK_ARCReclaimReturnedObject);
John McCall7e5e5f42011-07-07 06:58:02 +00004174 return Owned(ImplicitCastExpr::Create(Context, E->getType(), ck, E, 0,
4175 VK_RValue));
John McCallf85e1932011-06-15 23:02:42 +00004176 }
4177
4178 if (!getLangOptions().CPlusPlus)
4179 return Owned(E);
Douglas Gregor51326552009-12-24 18:51:59 +00004180
Peter Collingbournebceb7552011-11-27 22:09:28 +00004181 QualType ET = Context.getBaseElementType(E->getType());
4182 const RecordType *RT = ET->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00004183 if (!RT)
4184 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004185
John McCall86ff3082010-02-04 22:26:26 +00004186 // That should be enough to guarantee that this type is complete.
4187 // If it has a trivial destructor, we can avoid the extra copy.
Jeffrey Yasskinb7ee2e52011-01-27 19:17:54 +00004188 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall507384f2010-08-12 02:40:37 +00004189 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall86ff3082010-02-04 22:26:26 +00004190 return Owned(E);
4191
John McCallf85e1932011-06-15 23:02:42 +00004192 CXXDestructorDecl *Destructor = LookupDestructor(RD);
4193
4194 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
4195 if (Destructor) {
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00004196 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00004197 CheckDestructorAccess(E->getExprLoc(), Destructor,
4198 PDiag(diag::err_access_dtor_temp)
4199 << E->getType());
John McCallf85e1932011-06-15 23:02:42 +00004200
John McCall80ee6e82011-11-10 05:35:25 +00004201 // We need a cleanup, but we don't need to remember the temporary.
John McCallf85e1932011-06-15 23:02:42 +00004202 ExprNeedsCleanups = true;
John McCallc91cc662010-04-07 00:41:46 +00004203 }
Anders Carlssondef11992009-05-30 20:36:53 +00004204 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
4205}
4206
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004207ExprResult
John McCall4765fa02010-12-06 08:20:24 +00004208Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregor90f93822009-12-22 22:17:25 +00004209 if (SubExpr.isInvalid())
4210 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004211
John McCall4765fa02010-12-06 08:20:24 +00004212 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregor90f93822009-12-22 22:17:25 +00004213}
4214
John McCall80ee6e82011-11-10 05:35:25 +00004215Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
4216 assert(SubExpr && "sub expression can't be null!");
4217
4218 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
4219 assert(ExprCleanupObjects.size() >= FirstCleanup);
4220 assert(ExprNeedsCleanups || ExprCleanupObjects.size() == FirstCleanup);
4221 if (!ExprNeedsCleanups)
4222 return SubExpr;
4223
4224 ArrayRef<ExprWithCleanups::CleanupObject> Cleanups
4225 = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
4226 ExprCleanupObjects.size() - FirstCleanup);
4227
4228 Expr *E = ExprWithCleanups::Create(Context, SubExpr, Cleanups);
4229 DiscardCleanupsInEvaluationContext();
4230
4231 return E;
4232}
4233
John McCall4765fa02010-12-06 08:20:24 +00004234Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004235 assert(SubStmt && "sub statement can't be null!");
4236
John McCallf85e1932011-06-15 23:02:42 +00004237 if (!ExprNeedsCleanups)
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004238 return SubStmt;
4239
4240 // FIXME: In order to attach the temporaries, wrap the statement into
4241 // a StmtExpr; currently this is only used for asm statements.
4242 // This is hacky, either create a new CXXStmtWithTemporaries statement or
4243 // a new AsmStmtWithTemporaries.
4244 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
4245 SourceLocation(),
4246 SourceLocation());
4247 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
4248 SourceLocation());
John McCall4765fa02010-12-06 08:20:24 +00004249 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004250}
4251
John McCall60d7b3a2010-08-24 06:29:42 +00004252ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004253Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallb3d87482010-08-24 05:47:05 +00004254 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00004255 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004256 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004257 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00004258 if (Result.isInvalid()) return ExprError();
4259 Base = Result.get();
Mike Stump1eb44332009-09-09 15:08:12 +00004260
John McCall3c3b7f92011-10-25 17:37:35 +00004261 Result = CheckPlaceholderExpr(Base);
4262 if (Result.isInvalid()) return ExprError();
4263 Base = Result.take();
4264
John McCall9ae2f072010-08-23 23:25:46 +00004265 QualType BaseType = Base->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00004266 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004267 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00004268 // If we have a pointer to a dependent type and are using the -> operator,
4269 // the object type is the type that the pointer points to. We might still
4270 // have enough information about that type to do something useful.
4271 if (OpKind == tok::arrow)
4272 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4273 BaseType = Ptr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004274
John McCallb3d87482010-08-24 05:47:05 +00004275 ObjectType = ParsedType::make(BaseType);
Douglas Gregord4dca082010-02-24 18:44:31 +00004276 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00004277 return Owned(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004278 }
Mike Stump1eb44332009-09-09 15:08:12 +00004279
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004280 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00004281 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004282 // returned, with the original second operand.
4283 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00004284 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00004285 llvm::SmallPtrSet<CanQualType,8> CTypes;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004286 SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00004287 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004288
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004289 while (BaseType->isRecordType()) {
John McCall9ae2f072010-08-23 23:25:46 +00004290 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
4291 if (Result.isInvalid())
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004292 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00004293 Base = Result.get();
4294 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonde699e52009-10-13 22:55:59 +00004295 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCall9ae2f072010-08-23 23:25:46 +00004296 BaseType = Base->getType();
John McCallc4e83212009-09-30 01:01:30 +00004297 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00004298 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00004299 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00004300 for (unsigned i = 0; i < Locations.size(); i++)
4301 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00004302 return ExprError();
4303 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004304 }
Mike Stump1eb44332009-09-09 15:08:12 +00004305
Douglas Gregor1d7049a2012-01-12 16:11:24 +00004306 if (BaseType->isPointerType() || BaseType->isObjCObjectPointerType())
Douglas Gregor31658df2009-11-20 19:58:21 +00004307 BaseType = BaseType->getPointeeType();
4308 }
Mike Stump1eb44332009-09-09 15:08:12 +00004309
Douglas Gregor1d7049a2012-01-12 16:11:24 +00004310 // Objective-C properties allow "." access on Objective-C pointer types,
4311 // so adjust the base type to the object type itself.
4312 if (BaseType->isObjCObjectPointerType())
4313 BaseType = BaseType->getPointeeType();
4314
4315 // C++ [basic.lookup.classref]p2:
4316 // [...] If the type of the object expression is of pointer to scalar
4317 // type, the unqualified-id is looked up in the context of the complete
4318 // postfix-expression.
4319 //
4320 // This also indicates that we could be parsing a pseudo-destructor-name.
4321 // Note that Objective-C class and object types can be pseudo-destructor
4322 // expressions or normal member (ivar or property) access expressions.
4323 if (BaseType->isObjCObjectOrInterfaceType()) {
4324 MayBePseudoDestructor = true;
4325 } else if (!BaseType->isRecordType()) {
John McCallb3d87482010-08-24 05:47:05 +00004326 ObjectType = ParsedType();
Douglas Gregord4dca082010-02-24 18:44:31 +00004327 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00004328 return Owned(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00004329 }
Mike Stump1eb44332009-09-09 15:08:12 +00004330
Douglas Gregor03c57052009-11-17 05:17:33 +00004331 // The object type must be complete (or dependent).
4332 if (!BaseType->isDependentType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004333 RequireCompleteType(OpLoc, BaseType,
Douglas Gregor03c57052009-11-17 05:17:33 +00004334 PDiag(diag::err_incomplete_member_access)))
4335 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004336
Douglas Gregorc68afe22009-09-03 21:38:09 +00004337 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004338 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00004339 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00004340 // type C (or of pointer to a class type C), the unqualified-id is looked
4341 // up in the scope of class C. [...]
John McCallb3d87482010-08-24 05:47:05 +00004342 ObjectType = ParsedType::make(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00004343 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004344}
4345
John McCall60d7b3a2010-08-24 06:29:42 +00004346ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCall9ae2f072010-08-23 23:25:46 +00004347 Expr *MemExpr) {
Douglas Gregor77549082010-02-24 21:29:12 +00004348 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCall9ae2f072010-08-23 23:25:46 +00004349 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
4350 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregor849b2432010-03-31 17:46:05 +00004351 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004352
Douglas Gregor77549082010-02-24 21:29:12 +00004353 return ActOnCallExpr(/*Scope*/ 0,
John McCall9ae2f072010-08-23 23:25:46 +00004354 MemExpr,
Douglas Gregor77549082010-02-24 21:29:12 +00004355 /*LPLoc*/ ExpectedLParenLoc,
John McCallf312b1e2010-08-26 23:41:50 +00004356 MultiExprArg(),
Douglas Gregor77549082010-02-24 21:29:12 +00004357 /*RPLoc*/ ExpectedLParenLoc);
4358}
Douglas Gregord4dca082010-02-24 18:44:31 +00004359
David Blaikie91ec7892011-12-16 16:03:09 +00004360static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *Base,
4361 tok::TokenKind& OpKind, SourceLocation OpLoc) {
4362 // C++ [expr.pseudo]p2:
4363 // The left-hand side of the dot operator shall be of scalar type. The
4364 // left-hand side of the arrow operator shall be of pointer to scalar type.
4365 // This scalar type is the object type.
4366 if (OpKind == tok::arrow) {
4367 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4368 ObjectType = Ptr->getPointeeType();
4369 } else if (!Base->isTypeDependent()) {
4370 // The user wrote "p->" when she probably meant "p."; fix it.
4371 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4372 << ObjectType << true
4373 << FixItHint::CreateReplacement(OpLoc, ".");
4374 if (S.isSFINAEContext())
4375 return true;
4376
4377 OpKind = tok::period;
4378 }
4379 }
4380
4381 return false;
4382}
4383
John McCall60d7b3a2010-08-24 06:29:42 +00004384ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00004385 SourceLocation OpLoc,
4386 tok::TokenKind OpKind,
4387 const CXXScopeSpec &SS,
4388 TypeSourceInfo *ScopeTypeInfo,
4389 SourceLocation CCLoc,
4390 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004391 PseudoDestructorTypeStorage Destructed,
John McCall2d9f5fa2011-02-25 05:21:17 +00004392 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004393 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004394
John McCall9ae2f072010-08-23 23:25:46 +00004395 QualType ObjectType = Base->getType();
David Blaikie91ec7892011-12-16 16:03:09 +00004396 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4397 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004398
Douglas Gregorb57fb492010-02-24 22:38:50 +00004399 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
Nico Weberdf1be862012-01-23 05:50:57 +00004400 if (getLangOptions().MicrosoftMode && ObjectType->isVoidType())
Nico Weber2d757ec2012-01-23 06:08:16 +00004401 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Nico Weberdf1be862012-01-23 05:50:57 +00004402 else
4403 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
4404 << ObjectType << Base->getSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00004405 return ExprError();
4406 }
4407
4408 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004409 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb57fb492010-02-24 22:38:50 +00004410 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004411 if (DestructedTypeInfo) {
4412 QualType DestructedType = DestructedTypeInfo->getType();
4413 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004414 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCallf85e1932011-06-15 23:02:42 +00004415 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
4416 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
4417 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
4418 << ObjectType << DestructedType << Base->getSourceRange()
4419 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004420
John McCallf85e1932011-06-15 23:02:42 +00004421 // Recover by setting the destructed type to the object type.
4422 DestructedType = ObjectType;
4423 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004424 DestructedTypeStart);
John McCallf85e1932011-06-15 23:02:42 +00004425 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4426 } else if (DestructedType.getObjCLifetime() !=
4427 ObjectType.getObjCLifetime()) {
4428
4429 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
4430 // Okay: just pretend that the user provided the correctly-qualified
4431 // type.
4432 } else {
4433 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
4434 << ObjectType << DestructedType << Base->getSourceRange()
4435 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
4436 }
4437
4438 // Recover by setting the destructed type to the object type.
4439 DestructedType = ObjectType;
4440 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
4441 DestructedTypeStart);
4442 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4443 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004444 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00004445 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004446
Douglas Gregorb57fb492010-02-24 22:38:50 +00004447 // C++ [expr.pseudo]p2:
4448 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
4449 // form
4450 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004451 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb57fb492010-02-24 22:38:50 +00004452 //
4453 // shall designate the same scalar type.
4454 if (ScopeTypeInfo) {
4455 QualType ScopeType = ScopeTypeInfo->getType();
4456 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00004457 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004458
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004459 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00004460 diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00004461 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004462 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004463
Douglas Gregorb57fb492010-02-24 22:38:50 +00004464 ScopeType = QualType();
4465 ScopeTypeInfo = 0;
4466 }
4467 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004468
John McCall9ae2f072010-08-23 23:25:46 +00004469 Expr *Result
4470 = new (Context) CXXPseudoDestructorExpr(Context, Base,
4471 OpKind == tok::arrow, OpLoc,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00004472 SS.getWithLocInContext(Context),
John McCall9ae2f072010-08-23 23:25:46 +00004473 ScopeTypeInfo,
4474 CCLoc,
4475 TildeLoc,
4476 Destructed);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004477
Douglas Gregorb57fb492010-02-24 22:38:50 +00004478 if (HasTrailingLParen)
John McCall9ae2f072010-08-23 23:25:46 +00004479 return Owned(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004480
John McCall9ae2f072010-08-23 23:25:46 +00004481 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor77549082010-02-24 21:29:12 +00004482}
4483
John McCall60d7b3a2010-08-24 06:29:42 +00004484ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00004485 SourceLocation OpLoc,
4486 tok::TokenKind OpKind,
4487 CXXScopeSpec &SS,
4488 UnqualifiedId &FirstTypeName,
4489 SourceLocation CCLoc,
4490 SourceLocation TildeLoc,
4491 UnqualifiedId &SecondTypeName,
4492 bool HasTrailingLParen) {
Douglas Gregor77549082010-02-24 21:29:12 +00004493 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4494 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4495 "Invalid first type name in pseudo-destructor");
4496 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4497 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4498 "Invalid second type name in pseudo-destructor");
4499
John McCall9ae2f072010-08-23 23:25:46 +00004500 QualType ObjectType = Base->getType();
David Blaikie91ec7892011-12-16 16:03:09 +00004501 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4502 return ExprError();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004503
4504 // Compute the object type that we should use for name lookup purposes. Only
4505 // record types and dependent types matter.
John McCallb3d87482010-08-24 05:47:05 +00004506 ParsedType ObjectTypePtrForLookup;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004507 if (!SS.isSet()) {
John McCall2d9f5fa2011-02-25 05:21:17 +00004508 if (ObjectType->isRecordType())
4509 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallb3d87482010-08-24 05:47:05 +00004510 else if (ObjectType->isDependentType())
4511 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004512 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004513
4514 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb57fb492010-02-24 22:38:50 +00004515 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00004516 QualType DestructedType;
4517 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004518 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00004519 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004520 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00004521 SecondTypeName.StartLocation,
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +00004522 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004523 if (!T &&
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004524 ((SS.isSet() && !computeDeclContext(SS, false)) ||
4525 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004526 // The name of the type being destroyed is a dependent name, and we
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004527 // couldn't find anything useful in scope. Just store the identifier and
4528 // it's location, and we'll perform (qualified) name lookup again at
4529 // template instantiation time.
4530 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
4531 SecondTypeName.StartLocation);
4532 } else if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004533 Diag(SecondTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00004534 diag::err_pseudo_dtor_destructor_non_type)
4535 << SecondTypeName.Identifier << ObjectType;
4536 if (isSFINAEContext())
4537 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004538
Douglas Gregor77549082010-02-24 21:29:12 +00004539 // Recover by assuming we had the right type all along.
4540 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004541 } else
Douglas Gregor77549082010-02-24 21:29:12 +00004542 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004543 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00004544 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00004545 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004546 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4547 TemplateId->getTemplateArgs(),
4548 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00004549 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4550 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004551 TemplateId->TemplateNameLoc,
4552 TemplateId->LAngleLoc,
4553 TemplateArgsPtr,
4554 TemplateId->RAngleLoc);
4555 if (T.isInvalid() || !T.get()) {
4556 // Recover by assuming we had the right type all along.
4557 DestructedType = ObjectType;
4558 } else
4559 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004560 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004561
4562 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb57fb492010-02-24 22:38:50 +00004563 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004564 if (!DestructedType.isNull()) {
4565 if (!DestructedTypeInfo)
4566 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004567 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004568 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4569 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004570
Douglas Gregorb57fb492010-02-24 22:38:50 +00004571 // Convert the name of the scope type (the type prior to '::') into a type.
4572 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00004573 QualType ScopeType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004574 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor77549082010-02-24 21:29:12 +00004575 FirstTypeName.Identifier) {
4576 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004577 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00004578 FirstTypeName.StartLocation,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00004579 S, &SS, true, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00004580 if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004581 Diag(FirstTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00004582 diag::err_pseudo_dtor_destructor_non_type)
4583 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004584
Douglas Gregorb57fb492010-02-24 22:38:50 +00004585 if (isSFINAEContext())
4586 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004587
Douglas Gregorb57fb492010-02-24 22:38:50 +00004588 // Just drop this type. It's unnecessary anyway.
4589 ScopeType = QualType();
4590 } else
4591 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004592 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00004593 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00004594 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004595 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4596 TemplateId->getTemplateArgs(),
4597 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00004598 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4599 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004600 TemplateId->TemplateNameLoc,
4601 TemplateId->LAngleLoc,
4602 TemplateArgsPtr,
4603 TemplateId->RAngleLoc);
4604 if (T.isInvalid() || !T.get()) {
4605 // Recover by dropping this type.
4606 ScopeType = QualType();
4607 } else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004608 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004609 }
4610 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004611
Douglas Gregorb4a418f2010-02-24 23:02:30 +00004612 if (!ScopeType.isNull() && !ScopeTypeInfo)
4613 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
4614 FirstTypeName.StartLocation);
4615
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004616
John McCall9ae2f072010-08-23 23:25:46 +00004617 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00004618 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004619 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00004620}
4621
David Blaikie91ec7892011-12-16 16:03:09 +00004622ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4623 SourceLocation OpLoc,
4624 tok::TokenKind OpKind,
4625 SourceLocation TildeLoc,
4626 const DeclSpec& DS,
4627 bool HasTrailingLParen) {
4628
4629 QualType ObjectType = Base->getType();
4630 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4631 return ExprError();
4632
4633 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
4634
4635 TypeLocBuilder TLB;
4636 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
4637 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
4638 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
4639 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
4640
4641 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
4642 0, SourceLocation(), TildeLoc,
4643 Destructed, HasTrailingLParen);
4644}
4645
John Wiegley429bb272011-04-08 18:41:53 +00004646ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004647 CXXMethodDecl *Method,
4648 bool HadMultipleCandidates) {
John Wiegley429bb272011-04-08 18:41:53 +00004649 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
4650 FoundDecl, Method);
4651 if (Exp.isInvalid())
Douglas Gregorf2ae5262011-01-20 00:18:04 +00004652 return true;
Eli Friedman772fffa2009-12-09 04:53:56 +00004653
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004654 MemberExpr *ME =
John Wiegley429bb272011-04-08 18:41:53 +00004655 new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
Abramo Bagnara960809e2011-11-16 22:46:05 +00004656 SourceLocation(), Context.BoundMemberTy,
John McCallf89e55a2010-11-18 06:31:45 +00004657 VK_RValue, OK_Ordinary);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004658 if (HadMultipleCandidates)
4659 ME->setHadMultipleCandidates(true);
4660
John McCallf89e55a2010-11-18 06:31:45 +00004661 QualType ResultType = Method->getResultType();
4662 ExprValueKind VK = Expr::getValueKindForType(ResultType);
4663 ResultType = ResultType.getNonLValueExprType(Context);
4664
John Wiegley429bb272011-04-08 18:41:53 +00004665 MarkDeclarationReferenced(Exp.get()->getLocStart(), Method);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004666 CXXMemberCallExpr *CE =
John McCallf89e55a2010-11-18 06:31:45 +00004667 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
John Wiegley429bb272011-04-08 18:41:53 +00004668 Exp.get()->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00004669 return CE;
4670}
4671
Sebastian Redl2e156222010-09-10 20:55:43 +00004672ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4673 SourceLocation RParen) {
Sebastian Redl2e156222010-09-10 20:55:43 +00004674 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
4675 Operand->CanThrow(Context),
4676 KeyLoc, RParen));
4677}
4678
4679ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
4680 Expr *Operand, SourceLocation RParen) {
4681 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl02bc21a2010-09-10 20:55:37 +00004682}
4683
John McCallf6a16482010-12-04 03:47:34 +00004684/// Perform the conversions required for an expression used in a
4685/// context that ignores the result.
John Wiegley429bb272011-04-08 18:41:53 +00004686ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall3c3b7f92011-10-25 17:37:35 +00004687 if (E->hasPlaceholderType()) {
4688 ExprResult result = CheckPlaceholderExpr(E);
4689 if (result.isInvalid()) return Owned(E);
4690 E = result.take();
4691 }
4692
John McCalla878cda2010-12-02 02:07:15 +00004693 // C99 6.3.2.1:
4694 // [Except in specific positions,] an lvalue that does not have
4695 // array type is converted to the value stored in the
4696 // designated object (and is no longer an lvalue).
John McCalle6d134b2011-06-27 21:24:11 +00004697 if (E->isRValue()) {
4698 // In C, function designators (i.e. expressions of function type)
4699 // are r-values, but we still want to do function-to-pointer decay
4700 // on them. This is both technically correct and convenient for
4701 // some clients.
4702 if (!getLangOptions().CPlusPlus && E->getType()->isFunctionType())
4703 return DefaultFunctionArrayConversion(E);
4704
4705 return Owned(E);
4706 }
John McCalla878cda2010-12-02 02:07:15 +00004707
John McCallf6a16482010-12-04 03:47:34 +00004708 // Otherwise, this rule does not apply in C++, at least not for the moment.
John Wiegley429bb272011-04-08 18:41:53 +00004709 if (getLangOptions().CPlusPlus) return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004710
4711 // GCC seems to also exclude expressions of incomplete enum type.
4712 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
4713 if (!T->getDecl()->isComplete()) {
4714 // FIXME: stupid workaround for a codegen bug!
John Wiegley429bb272011-04-08 18:41:53 +00004715 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
4716 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004717 }
4718 }
4719
John Wiegley429bb272011-04-08 18:41:53 +00004720 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
4721 if (Res.isInvalid())
4722 return Owned(E);
4723 E = Res.take();
4724
John McCall85515d62010-12-04 12:29:11 +00004725 if (!E->getType()->isVoidType())
4726 RequireCompleteType(E->getExprLoc(), E->getType(),
4727 diag::err_incomplete_type);
John Wiegley429bb272011-04-08 18:41:53 +00004728 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004729}
4730
John Wiegley429bb272011-04-08 18:41:53 +00004731ExprResult Sema::ActOnFinishFullExpr(Expr *FE) {
4732 ExprResult FullExpr = Owned(FE);
4733
4734 if (!FullExpr.get())
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00004735 return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00004736
John Wiegley429bb272011-04-08 18:41:53 +00004737 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregord0937222010-12-13 22:49:22 +00004738 return ExprError();
4739
Douglas Gregor5e3a8be2011-12-15 00:53:32 +00004740 // Top-level message sends default to 'id' when we're in a debugger.
4741 if (getLangOptions().DebuggerSupport &&
4742 FullExpr.get()->getType() == Context.UnknownAnyTy &&
4743 isa<ObjCMessageExpr>(FullExpr.get())) {
4744 FullExpr = forceUnknownAnyToType(FullExpr.take(), Context.getObjCIdType());
4745 if (FullExpr.isInvalid())
4746 return ExprError();
4747 }
4748
John McCallfb8721c2011-04-10 19:13:55 +00004749 FullExpr = CheckPlaceholderExpr(FullExpr.take());
4750 if (FullExpr.isInvalid())
4751 return ExprError();
Douglas Gregor353ee242011-03-07 02:05:23 +00004752
John Wiegley429bb272011-04-08 18:41:53 +00004753 FullExpr = IgnoredValueConversions(FullExpr.take());
4754 if (FullExpr.isInvalid())
4755 return ExprError();
4756
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004757 CheckImplicitConversions(FullExpr.get(), FullExpr.get()->getExprLoc());
John McCall4765fa02010-12-06 08:20:24 +00004758 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson165a0a02009-05-17 18:41:29 +00004759}
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004760
4761StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
4762 if (!FullStmt) return StmtError();
4763
John McCall4765fa02010-12-06 08:20:24 +00004764 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004765}
Francois Pichet1e862692011-05-06 20:48:22 +00004766
Douglas Gregorba0513d2011-10-25 01:33:02 +00004767Sema::IfExistsResult
4768Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
4769 CXXScopeSpec &SS,
4770 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet1e862692011-05-06 20:48:22 +00004771 DeclarationName TargetName = TargetNameInfo.getName();
4772 if (!TargetName)
Douglas Gregor3896fc52011-10-24 22:31:10 +00004773 return IER_DoesNotExist;
Douglas Gregorba0513d2011-10-25 01:33:02 +00004774
Douglas Gregor3896fc52011-10-24 22:31:10 +00004775 // If the name itself is dependent, then the result is dependent.
4776 if (TargetName.isDependentName())
4777 return IER_Dependent;
Douglas Gregorba0513d2011-10-25 01:33:02 +00004778
Francois Pichet1e862692011-05-06 20:48:22 +00004779 // Do the redeclaration lookup in the current scope.
4780 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
4781 Sema::NotForRedeclaration);
Douglas Gregor3896fc52011-10-24 22:31:10 +00004782 LookupParsedName(R, S, &SS);
Francois Pichet1e862692011-05-06 20:48:22 +00004783 R.suppressDiagnostics();
Douglas Gregor3896fc52011-10-24 22:31:10 +00004784
4785 switch (R.getResultKind()) {
4786 case LookupResult::Found:
4787 case LookupResult::FoundOverloaded:
4788 case LookupResult::FoundUnresolvedValue:
4789 case LookupResult::Ambiguous:
4790 return IER_Exists;
4791
4792 case LookupResult::NotFound:
4793 return IER_DoesNotExist;
4794
4795 case LookupResult::NotFoundInCurrentInstantiation:
4796 return IER_Dependent;
4797 }
David Blaikie7530c032012-01-17 06:56:22 +00004798
4799 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet1e862692011-05-06 20:48:22 +00004800}
Douglas Gregorba0513d2011-10-25 01:33:02 +00004801
Douglas Gregor65019ac2011-10-25 03:44:56 +00004802Sema::IfExistsResult
4803Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4804 bool IsIfExists, CXXScopeSpec &SS,
4805 UnqualifiedId &Name) {
Douglas Gregorba0513d2011-10-25 01:33:02 +00004806 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Douglas Gregor65019ac2011-10-25 03:44:56 +00004807
4808 // Check for unexpanded parameter packs.
4809 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
4810 collectUnexpandedParameterPacks(SS, Unexpanded);
4811 collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
4812 if (!Unexpanded.empty()) {
4813 DiagnoseUnexpandedParameterPacks(KeywordLoc,
4814 IsIfExists? UPPC_IfExists
4815 : UPPC_IfNotExists,
4816 Unexpanded);
4817 return IER_Error;
4818 }
4819
Douglas Gregorba0513d2011-10-25 01:33:02 +00004820 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
4821}
4822
Eli Friedmandc3b7232012-01-04 02:40:39 +00004823//===----------------------------------------------------------------------===//
4824// Lambdas.
4825//===----------------------------------------------------------------------===//
4826
Eli Friedmanec9ea722012-01-05 03:35:19 +00004827void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
4828 Declarator &ParamInfo,
4829 Scope *CurScope) {
4830 DeclContext *DC = CurContext;
Eli Friedman906a7e12012-01-06 03:05:34 +00004831 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
Eli Friedmanec9ea722012-01-05 03:35:19 +00004832 DC = DC->getParent();
Eli Friedmandc3b7232012-01-04 02:40:39 +00004833
Eli Friedmanec9ea722012-01-05 03:35:19 +00004834 // Start constructing the lambda class.
4835 CXXRecordDecl *Class = CXXRecordDecl::Create(Context, TTK_Class, DC,
4836 Intro.Range.getBegin(),
4837 /*IdLoc=*/SourceLocation(),
4838 /*Id=*/0);
4839 Class->startDefinition();
Eli Friedman72899c32012-01-07 04:59:52 +00004840 Class->setLambda(true);
Eli Friedmanec9ea722012-01-05 03:35:19 +00004841 CurContext->addDecl(Class);
Eli Friedmandc3b7232012-01-04 02:40:39 +00004842
Eli Friedmane81d7e92012-01-07 01:08:17 +00004843 QualType ThisCaptureType;
Eli Friedmanb69b42c2012-01-11 02:36:31 +00004844 llvm::DenseMap<VarDecl*, unsigned> CaptureMap;
4845 unsigned CXXThisCaptureIndex = 0;
Eli Friedman72899c32012-01-07 04:59:52 +00004846 llvm::SmallVector<LambdaScopeInfo::Capture, 4> Captures;
Eli Friedmane81d7e92012-01-07 01:08:17 +00004847 for (llvm::SmallVector<LambdaCapture, 4>::const_iterator
4848 C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E; ++C) {
4849 if (C->Kind == LCK_This) {
4850 if (!ThisCaptureType.isNull()) {
4851 Diag(C->Loc, diag::err_capture_more_than_once) << "'this'";
4852 continue;
4853 }
4854
4855 if (Intro.Default == LCD_ByCopy) {
4856 Diag(C->Loc, diag::err_this_capture_with_copy_default);
4857 continue;
4858 }
4859
4860 ThisCaptureType = getCurrentThisType();
Eli Friedmane81d7e92012-01-07 01:08:17 +00004861 if (ThisCaptureType.isNull()) {
4862 Diag(C->Loc, diag::err_invalid_this_use);
4863 continue;
4864 }
Eli Friedman72899c32012-01-07 04:59:52 +00004865 CheckCXXThisCapture(C->Loc);
4866
Eli Friedmanb69b42c2012-01-11 02:36:31 +00004867 // FIXME: Need getCurCapture().
4868 bool isNested = getCurBlock() || getCurLambda();
4869 CapturingScopeInfo::Capture Cap(CapturingScopeInfo::Capture::ThisCapture,
4870 isNested);
4871 Captures.push_back(Cap);
4872 CXXThisCaptureIndex = Captures.size();
Eli Friedmane81d7e92012-01-07 01:08:17 +00004873 continue;
4874 }
4875
4876 assert(C->Id && "missing identifier for capture");
4877
4878 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
4879 Diag(C->Loc, diag::err_reference_capture_with_reference_default);
4880 continue;
4881 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
4882 Diag(C->Loc, diag::err_copy_capture_with_copy_default);
4883 continue;
4884 }
4885
Eli Friedmane81d7e92012-01-07 01:08:17 +00004886 DeclarationNameInfo Name(C->Id, C->Loc);
4887 LookupResult R(*this, Name, LookupOrdinaryName);
4888 CXXScopeSpec ScopeSpec;
4889 LookupParsedName(R, CurScope, &ScopeSpec);
4890 if (R.isAmbiguous())
4891 continue;
Kaelyn Uhrain4798f8d2012-01-18 05:58:54 +00004892 if (R.empty()) {
4893 DeclFilterCCC<VarDecl> Validator;
4894 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
Eli Friedmane81d7e92012-01-07 01:08:17 +00004895 continue;
Kaelyn Uhrain4798f8d2012-01-18 05:58:54 +00004896 }
Eli Friedmane81d7e92012-01-07 01:08:17 +00004897
4898 VarDecl *Var = R.getAsSingle<VarDecl>();
4899 if (!Var) {
4900 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
4901 continue;
4902 }
4903
Eli Friedmanb69b42c2012-01-11 02:36:31 +00004904 if (CaptureMap.count(Var)) {
4905 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
4906 continue;
4907 }
4908
Eli Friedmane81d7e92012-01-07 01:08:17 +00004909 if (!Var->hasLocalStorage()) {
4910 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
4911 continue;
4912 }
4913
Eli Friedmanb69b42c2012-01-11 02:36:31 +00004914 // FIXME: This is completely wrong for nested captures and variables
4915 // with a non-trivial constructor.
4916 // FIXME: We should refuse to capture __block variables.
4917 Captures.push_back(LambdaScopeInfo::Capture(Var, C->Kind == LCK_ByRef,
4918 /*isNested*/false, 0));
4919 CaptureMap[Var] = Captures.size();
Eli Friedmane81d7e92012-01-07 01:08:17 +00004920 }
4921
Eli Friedmanec9ea722012-01-05 03:35:19 +00004922 // Build the call operator; we don't really have all the relevant information
4923 // at this point, but we need something to attach child declarations to.
Eli Friedman906a7e12012-01-06 03:05:34 +00004924 QualType MethodTy;
Eli Friedmanf88c4002012-01-04 04:41:38 +00004925 TypeSourceInfo *MethodTyInfo;
Eli Friedman906a7e12012-01-06 03:05:34 +00004926 if (ParamInfo.getNumTypeObjects() == 0) {
4927 FunctionProtoType::ExtProtoInfo EPI;
4928 EPI.TypeQuals |= DeclSpec::TQ_const;
4929 MethodTy = Context.getFunctionType(Context.DependentTy,
4930 /*Args=*/0, /*NumArgs=*/0, EPI);
4931 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
4932 } else {
4933 assert(ParamInfo.isFunctionDeclarator() &&
4934 "lambda-declarator is a function");
4935 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
4936 if (!FTI.hasMutableQualifier())
4937 FTI.TypeQuals |= DeclSpec::TQ_const;
4938 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
4939 // FIXME: Can these asserts actually fail?
4940 assert(MethodTyInfo && "no type from lambda-declarator");
4941 MethodTy = MethodTyInfo->getType();
4942 assert(!MethodTy.isNull() && "no type from lambda declarator");
4943 }
Eli Friedmanf88c4002012-01-04 04:41:38 +00004944
Eli Friedmanec9ea722012-01-05 03:35:19 +00004945 DeclarationName MethodName
4946 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
4947 CXXMethodDecl *Method
4948 = CXXMethodDecl::Create(Context,
4949 Class,
4950 ParamInfo.getSourceRange().getEnd(),
4951 DeclarationNameInfo(MethodName,
4952 /*NameLoc=*/SourceLocation()),
Eli Friedman906a7e12012-01-06 03:05:34 +00004953 MethodTy,
Eli Friedmanec9ea722012-01-05 03:35:19 +00004954 MethodTyInfo,
4955 /*isStatic=*/false,
4956 SC_None,
4957 /*isInline=*/true,
4958 /*isConstExpr=*/false,
4959 ParamInfo.getSourceRange().getEnd());
4960 Method->setAccess(AS_public);
4961 Class->addDecl(Method);
4962 Method->setLexicalDeclContext(DC); // FIXME: Is this really correct?
4963
Eli Friedmanec9ea722012-01-05 03:35:19 +00004964 ProcessDeclAttributes(CurScope, Method, ParamInfo);
4965
Eli Friedmanec9ea722012-01-05 03:35:19 +00004966 // Enter a new evaluation context to insulate the block from any
4967 // cleanups from the enclosing full-expression.
4968 PushExpressionEvaluationContext(PotentiallyEvaluated);
4969
4970 PushDeclContext(CurScope, Method);
Eli Friedman906a7e12012-01-06 03:05:34 +00004971
Eli Friedman906a7e12012-01-06 03:05:34 +00004972 // Set the parameters on the decl, if specified.
4973 if (isa<FunctionProtoTypeLoc>(MethodTyInfo->getTypeLoc())) {
4974 FunctionProtoTypeLoc Proto =
4975 cast<FunctionProtoTypeLoc>(MethodTyInfo->getTypeLoc());
4976 Method->setParams(Proto.getParams());
4977 CheckParmsForFunctionDef(Method->param_begin(),
4978 Method->param_end(),
4979 /*CheckParameterNames=*/false);
4980
4981 // Introduce our parameters into the function scope
4982 for (unsigned p = 0, NumParams = Method->getNumParams(); p < NumParams; ++p) {
4983 ParmVarDecl *Param = Method->getParamDecl(p);
4984 Param->setOwningFunction(Method);
4985
4986 // If this has an identifier, add it to the scope stack.
4987 if (Param->getIdentifier()) {
4988 CheckShadow(CurScope, Param);
4989
4990 PushOnScopeChains(Param, CurScope);
4991 }
4992 }
4993 }
4994
Eli Friedman72899c32012-01-07 04:59:52 +00004995 // Introduce the lambda scope.
4996 PushLambdaScope(Class);
4997
4998 LambdaScopeInfo *LSI = getCurLambda();
Eli Friedmanb69b42c2012-01-11 02:36:31 +00004999 LSI->CXXThisCaptureIndex = CXXThisCaptureIndex;
5000 std::swap(LSI->CaptureMap, CaptureMap);
Eli Friedman72899c32012-01-07 04:59:52 +00005001 std::swap(LSI->Captures, Captures);
Eli Friedmanb69b42c2012-01-11 02:36:31 +00005002 LSI->NumExplicitCaptures = Captures.size();
5003 if (Intro.Default == LCD_ByCopy)
5004 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
5005 else if (Intro.Default == LCD_ByRef)
5006 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
Eli Friedman72899c32012-01-07 04:59:52 +00005007
Eli Friedman906a7e12012-01-06 03:05:34 +00005008 const FunctionType *Fn = MethodTy->getAs<FunctionType>();
5009 QualType RetTy = Fn->getResultType();
5010 if (RetTy != Context.DependentTy) {
5011 LSI->ReturnType = RetTy;
Eli Friedmanb69b42c2012-01-11 02:36:31 +00005012 } else {
Eli Friedman906a7e12012-01-06 03:05:34 +00005013 LSI->HasImplicitReturnType = true;
5014 }
5015
5016 // FIXME: Check return type is complete, !isObjCObjectType
5017
Eli Friedmandc3b7232012-01-04 02:40:39 +00005018}
5019
5020void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope) {
5021 // Leave the expression-evaluation context.
5022 DiscardCleanupsInEvaluationContext();
5023 PopExpressionEvaluationContext();
5024
5025 // Leave the context of the lambda.
Eli Friedmanec9ea722012-01-05 03:35:19 +00005026 PopDeclContext();
5027 PopFunctionScopeInfo();
Eli Friedmandc3b7232012-01-04 02:40:39 +00005028}
5029
5030ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc,
5031 Stmt *Body, Scope *CurScope) {
5032 // FIXME: Implement
5033 Diag(StartLoc, diag::err_lambda_unsupported);
5034 ActOnLambdaError(StartLoc, CurScope);
5035 return ExprError();
5036}