blob: ae0c2c58c1902c90e82b1cd22f941bc29ccb949a [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 Friedmanceccab92012-01-26 00:26:18 +0000998 ExprResult ConvertedSize = ConvertToIntegralOrEnumerationType(
Richard Smithebaf0e62011-10-18 20:49:44 +0000999 StartLoc, ArraySize,
1000 PDiag(diag::err_array_size_not_integral),
1001 PDiag(diag::err_array_size_incomplete_type)
1002 << ArraySize->getSourceRange(),
1003 PDiag(diag::err_array_size_explicit_conversion),
1004 PDiag(diag::note_array_size_conversion),
1005 PDiag(diag::err_array_size_ambiguous_conversion),
1006 PDiag(diag::note_array_size_conversion),
1007 PDiag(getLangOptions().CPlusPlus0x ?
1008 diag::warn_cxx98_compat_array_size_conversion :
1009 diag::ext_array_size_conversion));
Douglas Gregor6bc574d2010-06-30 00:20:43 +00001010 if (ConvertedSize.isInvalid())
1011 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001012
John McCall9ae2f072010-08-23 23:25:46 +00001013 ArraySize = ConvertedSize.take();
John McCall806054d2012-01-11 00:14:46 +00001014 QualType SizeType = ArraySize->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001015 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor6bc574d2010-06-30 00:20:43 +00001016 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001017
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001018 // Let's see if this is a constant < 0. If so, we reject it out of hand.
1019 // We don't care about special rules, so we tell the machinery it's not
1020 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +00001021 if (!ArraySize->isValueDependent()) {
1022 llvm::APSInt Value;
1023 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
1024 if (Value < llvm::APSInt(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001025 llvm::APInt::getNullValue(Value.getBitWidth()),
Anders Carlssonac18b2e2009-09-23 00:37:25 +00001026 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +00001027 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +00001028 diag::err_typecheck_negative_array_size)
Sebastian Redlf53597f2009-03-15 17:47:39 +00001029 << ArraySize->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001030
Douglas Gregor2767ce22010-08-18 00:39:00 +00001031 if (!AllocType->isDependentType()) {
1032 unsigned ActiveSizeBits
1033 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1034 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001035 Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +00001036 diag::err_array_too_large)
1037 << Value.toString(10)
1038 << ArraySize->getSourceRange();
1039 return ExprError();
1040 }
1041 }
Douglas Gregor4bd40312010-07-13 15:54:32 +00001042 } else if (TypeIdParens.isValid()) {
1043 // Can't have dynamic array size when the type-id is in parentheses.
1044 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1045 << ArraySize->getSourceRange()
1046 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1047 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001048
Douglas Gregor4bd40312010-07-13 15:54:32 +00001049 TypeIdParens = SourceRange();
Sebastian Redl28507842009-02-26 14:39:58 +00001050 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001051 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001052
John McCallf85e1932011-06-15 23:02:42 +00001053 // ARC: warn about ABI issues.
1054 if (getLangOptions().ObjCAutoRefCount) {
1055 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1056 if (BaseAllocType.hasStrongOrWeakObjCLifetime())
1057 Diag(StartLoc, diag::warn_err_new_delete_object_array)
1058 << 0 << BaseAllocType;
1059 }
1060
John McCall7d166272011-05-15 07:14:44 +00001061 // Note that we do *not* convert the argument in any way. It can
1062 // be signed, larger than size_t, whatever.
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001063 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001064
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001065 FunctionDecl *OperatorNew = 0;
1066 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +00001067 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
1068 unsigned NumPlaceArgs = PlacementArgs.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001069
Sebastian Redl28507842009-02-26 14:39:58 +00001070 if (!AllocType->isDependentType() &&
1071 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
1072 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +00001073 SourceRange(PlacementLParen, PlacementRParen),
1074 UseGlobal, AllocType, ArraySize, PlaceArgs,
1075 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +00001076 return ExprError();
John McCall6ec278d2011-01-27 09:37:56 +00001077
1078 // If this is an array allocation, compute whether the usual array
1079 // deallocation function for the type has a size_t parameter.
1080 bool UsualArrayDeleteWantsSize = false;
1081 if (ArraySize && !AllocType->isDependentType())
1082 UsualArrayDeleteWantsSize
1083 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1084
Chris Lattner5f9e2722011-07-23 10:55:15 +00001085 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001086 if (OperatorNew) {
1087 // Add default arguments, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001088 const FunctionProtoType *Proto =
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001089 OperatorNew->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001090 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00001091 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001092
Anders Carlsson28e94832010-05-03 02:07:56 +00001093 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001094 Proto, 1, PlaceArgs, NumPlaceArgs,
Anders Carlsson28e94832010-05-03 02:07:56 +00001095 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001096 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001097
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001098 NumPlaceArgs = AllPlaceArgs.size();
1099 if (NumPlaceArgs > 0)
1100 PlaceArgs = &AllPlaceArgs[0];
1101 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001102
Nick Lewyckyfca84b22012-01-24 21:15:41 +00001103 // Warn if the type is over-aligned and is being allocated by global operator
1104 // new.
1105 if (OperatorNew &&
1106 (OperatorNew->isImplicit() ||
1107 getSourceManager().isInSystemHeader(OperatorNew->getLocStart()))) {
1108 if (unsigned Align = Context.getPreferredTypeAlign(AllocType.getTypePtr())){
1109 unsigned SuitableAlign = Context.getTargetInfo().getSuitableAlign();
1110 if (Align > SuitableAlign)
1111 Diag(StartLoc, diag::warn_overaligned_type)
1112 << AllocType
1113 << unsigned(Align / Context.getCharWidth())
1114 << unsigned(SuitableAlign / Context.getCharWidth());
1115 }
1116 }
1117
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001118 bool Init = ConstructorLParen.isValid();
1119 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001120 CXXConstructorDecl *Constructor = 0;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001121 bool HadMultipleCandidates = false;
Sebastian Redlf53597f2009-03-15 17:47:39 +00001122 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
1123 unsigned NumConsArgs = ConstructorArgs.size();
John McCallca0408f2010-08-23 06:44:23 +00001124 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmana8ce9ec2009-11-08 22:15:39 +00001125
Anders Carlsson48c95012010-05-03 15:45:23 +00001126 // Array 'new' can't have any initializers.
Anders Carlsson55cbd6e2010-05-16 16:24:20 +00001127 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlsson48c95012010-05-03 15:45:23 +00001128 SourceRange InitRange(ConsArgs[0]->getLocStart(),
1129 ConsArgs[NumConsArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001130
Anders Carlsson48c95012010-05-03 15:45:23 +00001131 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1132 return ExprError();
1133 }
1134
Douglas Gregor99a2e602009-12-16 01:38:02 +00001135 if (!AllocType->isDependentType() &&
1136 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
1137 // C++0x [expr.new]p15:
1138 // A new-expression that creates an object of type T initializes that
1139 // object as follows:
1140 InitializationKind Kind
1141 // - If the new-initializer is omitted, the object is default-
1142 // initialized (8.5); if no initialization is performed,
1143 // the object has indeterminate value
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001144 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001145 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor99a2e602009-12-16 01:38:02 +00001146 // initialization rules of 8.5 for direct-initialization.
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001147 : InitializationKind::CreateDirect(TypeRange.getBegin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001148 ConstructorLParen,
Douglas Gregor99a2e602009-12-16 01:38:02 +00001149 ConstructorRParen);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001150
Douglas Gregor99a2e602009-12-16 01:38:02 +00001151 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00001152 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001153 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001154 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor99a2e602009-12-16 01:38:02 +00001155 move(ConstructorArgs));
1156 if (FullInit.isInvalid())
1157 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001158
1159 // FullInit is our initializer; walk through it to determine if it's a
Douglas Gregor99a2e602009-12-16 01:38:02 +00001160 // constructor call, which CXXNewExpr handles directly.
1161 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
1162 if (CXXBindTemporaryExpr *Binder
1163 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
1164 FullInitExpr = Binder->getSubExpr();
1165 if (CXXConstructExpr *Construct
1166 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
1167 Constructor = Construct->getConstructor();
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001168 HadMultipleCandidates = Construct->hadMultipleCandidates();
Douglas Gregor99a2e602009-12-16 01:38:02 +00001169 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
1170 AEnd = Construct->arg_end();
1171 A != AEnd; ++A)
John McCall3fa5cae2010-10-26 07:05:15 +00001172 ConvertedConstructorArgs.push_back(*A);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001173 } else {
1174 // Take the converted initializer.
1175 ConvertedConstructorArgs.push_back(FullInit.release());
1176 }
1177 } else {
1178 // No initialization required.
1179 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001180
Douglas Gregor99a2e602009-12-16 01:38:02 +00001181 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +00001182 NumConsArgs = ConvertedConstructorArgs.size();
1183 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001184 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001185
Douglas Gregor6d908702010-02-26 05:06:18 +00001186 // Mark the new and delete operators as referenced.
1187 if (OperatorNew)
1188 MarkDeclarationReferenced(StartLoc, OperatorNew);
1189 if (OperatorDelete)
1190 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1191
John McCall84ff0fc2011-07-13 20:12:57 +00001192 // C++0x [expr.new]p17:
1193 // If the new expression creates an array of objects of class type,
1194 // access and ambiguity control are done for the destructor.
1195 if (ArraySize && Constructor) {
1196 if (CXXDestructorDecl *dtor = LookupDestructor(Constructor->getParent())) {
1197 MarkDeclarationReferenced(StartLoc, dtor);
1198 CheckDestructorAccess(StartLoc, dtor,
1199 PDiag(diag::err_access_dtor)
1200 << Context.getBaseElementType(AllocType));
1201 }
1202 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001203
Sebastian Redlf53597f2009-03-15 17:47:39 +00001204 PlacementArgs.release();
1205 ConstructorArgs.release();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001206
Ted Kremenekad7fe862010-02-11 22:51:03 +00001207 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregor4bd40312010-07-13 15:54:32 +00001208 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001209 ArraySize, Constructor, Init,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001210 ConsArgs, NumConsArgs,
1211 HadMultipleCandidates,
1212 OperatorDelete,
John McCall6ec278d2011-01-27 09:37:56 +00001213 UsualArrayDeleteWantsSize,
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001214 ResultType, AllocTypeInfo,
1215 StartLoc,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001216 Init ? ConstructorRParen :
Chandler Carruth428edaf2010-10-25 08:47:36 +00001217 TypeRange.getEnd(),
1218 ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001219}
1220
1221/// CheckAllocatedType - Checks that a type is suitable as the allocated type
1222/// in a new-expression.
1223/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +00001224bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00001225 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001226 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1227 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +00001228 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001229 return Diag(Loc, diag::err_bad_new_type)
1230 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001231 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001232 return Diag(Loc, diag::err_bad_new_type)
1233 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001234 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +00001235 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001236 PDiag(diag::err_new_incomplete_type)
1237 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001238 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +00001239 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +00001240 diag::err_allocation_of_abstract_type))
1241 return true;
Douglas Gregora0750762010-10-06 16:00:31 +00001242 else if (AllocType->isVariablyModifiedType())
1243 return Diag(Loc, diag::err_variably_modified_new_type)
1244 << AllocType;
Douglas Gregor5666d362011-04-15 19:46:20 +00001245 else if (unsigned AddressSpace = AllocType.getAddressSpace())
1246 return Diag(Loc, diag::err_address_space_qualified_new)
1247 << AllocType.getUnqualifiedType() << AddressSpace;
John McCallf85e1932011-06-15 23:02:42 +00001248 else if (getLangOptions().ObjCAutoRefCount) {
1249 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
1250 QualType BaseAllocType = Context.getBaseElementType(AT);
1251 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1252 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001253 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001254 << BaseAllocType;
1255 }
1256 }
Douglas Gregor5666d362011-04-15 19:46:20 +00001257
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001258 return false;
1259}
1260
Douglas Gregor6d908702010-02-26 05:06:18 +00001261/// \brief Determine whether the given function is a non-placement
1262/// deallocation function.
1263static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1264 if (FD->isInvalidDecl())
1265 return false;
1266
1267 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1268 return Method->isUsualDeallocationFunction();
1269
1270 return ((FD->getOverloadedOperator() == OO_Delete ||
1271 FD->getOverloadedOperator() == OO_Array_Delete) &&
1272 FD->getNumParams() == 1);
1273}
1274
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001275/// FindAllocationFunctions - Finds the overloads of operator new and delete
1276/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001277bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1278 bool UseGlobal, QualType AllocType,
1279 bool IsArray, Expr **PlaceArgs,
1280 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001281 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +00001282 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001283 // --- Choosing an allocation function ---
1284 // C++ 5.3.4p8 - 14 & 18
1285 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1286 // in the scope of the allocated class.
1287 // 2) If an array size is given, look for operator new[], else look for
1288 // operator new.
1289 // 3) The first argument is always size_t. Append the arguments from the
1290 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001291
Chris Lattner5f9e2722011-07-23 10:55:15 +00001292 SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001293 // We don't care about the actual value of this argument.
1294 // FIXME: Should the Sema create the expression and embed it in the syntax
1295 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00001296 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001297 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssond67c4c32009-08-16 20:29:29 +00001298 Context.getSizeType(),
1299 SourceLocation());
1300 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001301 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1302
Douglas Gregor6d908702010-02-26 05:06:18 +00001303 // C++ [expr.new]p8:
1304 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001305 // function's name is operator new and the deallocation function's
Douglas Gregor6d908702010-02-26 05:06:18 +00001306 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001307 // type, the allocation function's name is operator new[] and the
1308 // deallocation function's name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001309 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1310 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +00001311 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1312 IsArray ? OO_Array_Delete : OO_Delete);
1313
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001314 QualType AllocElemType = Context.getBaseElementType(AllocType);
1315
1316 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +00001317 CXXRecordDecl *Record
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001318 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +00001319 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001320 AllocArgs.size(), Record, /*AllowMissing=*/true,
1321 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001322 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001323 }
1324 if (!OperatorNew) {
1325 // Didn't find a member overload. Look for a global one.
1326 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +00001327 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +00001328 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001329 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1330 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001331 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001332 }
1333
John McCall9c82afc2010-04-20 02:18:25 +00001334 // We don't need an operator delete if we're running under
1335 // -fno-exceptions.
1336 if (!getLangOptions().Exceptions) {
1337 OperatorDelete = 0;
1338 return false;
1339 }
1340
Anders Carlssond9583892009-05-31 20:26:12 +00001341 // FindAllocationOverload can change the passed in arguments, so we need to
1342 // copy them back.
1343 if (NumPlaceArgs > 0)
1344 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001345
Douglas Gregor6d908702010-02-26 05:06:18 +00001346 // C++ [expr.new]p19:
1347 //
1348 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001349 // deallocation function's name is looked up in the global
Douglas Gregor6d908702010-02-26 05:06:18 +00001350 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001351 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6d908702010-02-26 05:06:18 +00001352 // the scope of T. If this lookup fails to find the name, or if
1353 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001354 // deallocation function's name is looked up in the global scope.
Douglas Gregor6d908702010-02-26 05:06:18 +00001355 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001356 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001357 CXXRecordDecl *RD
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001358 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6d908702010-02-26 05:06:18 +00001359 LookupQualifiedName(FoundDelete, RD);
1360 }
John McCall90c8c572010-03-18 08:19:33 +00001361 if (FoundDelete.isAmbiguous())
1362 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +00001363
1364 if (FoundDelete.empty()) {
1365 DeclareGlobalNewDelete();
1366 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1367 }
1368
1369 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +00001370
Chris Lattner5f9e2722011-07-23 10:55:15 +00001371 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCall9aa472c2010-03-19 07:35:19 +00001372
John McCalledeb6c92010-09-14 21:34:24 +00001373 // Whether we're looking for a placement operator delete is dictated
1374 // by whether we selected a placement operator new, not by whether
1375 // we had explicit placement arguments. This matters for things like
1376 // struct A { void *operator new(size_t, int = 0); ... };
1377 // A *a = new A()
1378 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1379
1380 if (isPlacementNew) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001381 // C++ [expr.new]p20:
1382 // A declaration of a placement deallocation function matches the
1383 // declaration of a placement allocation function if it has the
1384 // same number of parameters and, after parameter transformations
1385 // (8.3.5), all parameter types except the first are
1386 // identical. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001387 //
Douglas Gregor6d908702010-02-26 05:06:18 +00001388 // To perform this comparison, we compute the function type that
1389 // the deallocation function should have, and use that type both
1390 // for template argument deduction and for comparison purposes.
John McCalle23cf432010-12-14 08:05:40 +00001391 //
1392 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6d908702010-02-26 05:06:18 +00001393 QualType ExpectedFunctionType;
1394 {
1395 const FunctionProtoType *Proto
1396 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00001397
Chris Lattner5f9e2722011-07-23 10:55:15 +00001398 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001399 ArgTypes.push_back(Context.VoidPtrTy);
Douglas Gregor6d908702010-02-26 05:06:18 +00001400 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1401 ArgTypes.push_back(Proto->getArgType(I));
1402
John McCalle23cf432010-12-14 08:05:40 +00001403 FunctionProtoType::ExtProtoInfo EPI;
1404 EPI.Variadic = Proto->isVariadic();
1405
Douglas Gregor6d908702010-02-26 05:06:18 +00001406 ExpectedFunctionType
1407 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
John McCalle23cf432010-12-14 08:05:40 +00001408 ArgTypes.size(), EPI);
Douglas Gregor6d908702010-02-26 05:06:18 +00001409 }
1410
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001411 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001412 DEnd = FoundDelete.end();
1413 D != DEnd; ++D) {
1414 FunctionDecl *Fn = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001415 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6d908702010-02-26 05:06:18 +00001416 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1417 // Perform template argument deduction to try to match the
1418 // expected function type.
1419 TemplateDeductionInfo Info(Context, StartLoc);
1420 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1421 continue;
1422 } else
1423 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1424
1425 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001426 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001427 }
1428 } else {
1429 // C++ [expr.new]p20:
1430 // [...] Any non-placement deallocation function matches a
1431 // non-placement allocation function. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001432 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001433 DEnd = FoundDelete.end();
1434 D != DEnd; ++D) {
1435 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1436 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001437 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001438 }
1439 }
1440
1441 // C++ [expr.new]p20:
1442 // [...] If the lookup finds a single matching deallocation
1443 // function, that function will be called; otherwise, no
1444 // deallocation function will be called.
1445 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001446 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001447
1448 // C++0x [expr.new]p20:
1449 // If the lookup finds the two-parameter form of a usual
1450 // deallocation function (3.7.4.2) and that function, considered
1451 // as a placement deallocation function, would have been
1452 // selected as a match for the allocation function, the program
1453 // is ill-formed.
1454 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1455 isNonPlacementDeallocationFunction(OperatorDelete)) {
1456 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001457 << SourceRange(PlaceArgs[0]->getLocStart(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001458 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1459 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1460 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001461 } else {
1462 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001463 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001464 }
1465 }
1466
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001467 return false;
1468}
1469
Sebastian Redl7f662392008-12-04 22:20:51 +00001470/// FindAllocationOverload - Find an fitting overload for the allocation
1471/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001472bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1473 DeclarationName Name, Expr** Args,
1474 unsigned NumArgs, DeclContext *Ctx,
Sean Hunt2be7e902011-05-12 22:46:29 +00001475 bool AllowMissing, FunctionDecl *&Operator,
1476 bool Diagnose) {
John McCalla24dc2e2009-11-17 02:14:36 +00001477 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1478 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001479 if (R.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001480 if (AllowMissing || !Diagnose)
Sebastian Redl7f662392008-12-04 22:20:51 +00001481 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001482 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001483 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001484 }
1485
John McCall90c8c572010-03-18 08:19:33 +00001486 if (R.isAmbiguous())
1487 return true;
1488
1489 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001490
John McCall5769d612010-02-08 23:07:23 +00001491 OverloadCandidateSet Candidates(StartLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001492 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001493 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001494 // Even member operator new/delete are implicitly treated as
1495 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001496 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001497
John McCall9aa472c2010-03-19 07:35:19 +00001498 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1499 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001500 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1501 Candidates,
1502 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001503 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001504 }
1505
John McCall9aa472c2010-03-19 07:35:19 +00001506 FunctionDecl *Fn = cast<FunctionDecl>(D);
1507 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001508 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001509 }
1510
1511 // Do the resolution.
1512 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00001513 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001514 case OR_Success: {
1515 // Got one!
1516 FunctionDecl *FnDecl = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00001517 MarkDeclarationReferenced(StartLoc, FnDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001518 // The first argument is size_t, and the first parameter must be size_t,
1519 // too. This is checked on declaration and can be assumed. (It can't be
1520 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001521 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001522 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1523 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001524 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1525 FnDecl->getParamDecl(i));
1526
1527 if (!Diagnose && !CanPerformCopyInitialization(Entity, Owned(Args[i])))
1528 return true;
1529
John McCall60d7b3a2010-08-24 06:29:42 +00001530 ExprResult Result
Sean Hunt2be7e902011-05-12 22:46:29 +00001531 = PerformCopyInitialization(Entity, SourceLocation(), Owned(Args[i]));
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001532 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001533 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001534
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001535 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001536 }
1537 Operator = FnDecl;
Sean Hunt2be7e902011-05-12 22:46:29 +00001538 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl,
1539 Diagnose);
Sebastian Redl7f662392008-12-04 22:20:51 +00001540 return false;
1541 }
1542
1543 case OR_No_Viable_Function:
Chandler Carruth361d3802011-06-08 10:26:03 +00001544 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001545 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1546 << Name << Range;
Chandler Carruth361d3802011-06-08 10:26:03 +00001547 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1548 }
Sebastian Redl7f662392008-12-04 22:20:51 +00001549 return true;
1550
1551 case OR_Ambiguous:
Chandler Carruth361d3802011-06-08 10:26:03 +00001552 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001553 Diag(StartLoc, diag::err_ovl_ambiguous_call)
1554 << Name << Range;
Chandler Carruth361d3802011-06-08 10:26:03 +00001555 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
1556 }
Sebastian Redl7f662392008-12-04 22:20:51 +00001557 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001558
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001559 case OR_Deleted: {
Chandler Carruth361d3802011-06-08 10:26:03 +00001560 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001561 Diag(StartLoc, diag::err_ovl_deleted_call)
1562 << Best->Function->isDeleted()
1563 << Name
1564 << getDeletedOrUnavailableSuffix(Best->Function)
1565 << Range;
Chandler Carruth361d3802011-06-08 10:26:03 +00001566 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1567 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001568 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001569 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001570 }
David Blaikieb219cfc2011-09-23 05:06:16 +00001571 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Sebastian Redl7f662392008-12-04 22:20:51 +00001572}
1573
1574
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001575/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1576/// delete. These are:
1577/// @code
Sebastian Redl8999fe12011-03-14 18:08:30 +00001578/// // C++03:
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001579/// void* operator new(std::size_t) throw(std::bad_alloc);
1580/// void* operator new[](std::size_t) throw(std::bad_alloc);
1581/// void operator delete(void *) throw();
1582/// void operator delete[](void *) throw();
Sebastian Redl8999fe12011-03-14 18:08:30 +00001583/// // C++0x:
1584/// void* operator new(std::size_t);
1585/// void* operator new[](std::size_t);
1586/// void operator delete(void *);
1587/// void operator delete[](void *);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001588/// @endcode
Sebastian Redl8999fe12011-03-14 18:08:30 +00001589/// C++0x operator delete is implicitly noexcept.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001590/// Note that the placement and nothrow forms of new are *not* implicitly
1591/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001592void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001593 if (GlobalNewDeleteDeclared)
1594 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001595
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001596 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001597 // [...] The following allocation and deallocation functions (18.4) are
1598 // implicitly declared in global scope in each translation unit of a
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001599 // program
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001600 //
Sebastian Redl8999fe12011-03-14 18:08:30 +00001601 // C++03:
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001602 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001603 // void* operator new[](std::size_t) throw(std::bad_alloc);
1604 // void operator delete(void*) throw();
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001605 // void operator delete[](void*) throw();
Sebastian Redl8999fe12011-03-14 18:08:30 +00001606 // C++0x:
1607 // void* operator new(std::size_t);
1608 // void* operator new[](std::size_t);
1609 // void operator delete(void*);
1610 // void operator delete[](void*);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001611 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001612 // These implicit declarations introduce only the function names operator
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001613 // new, operator new[], operator delete, operator delete[].
1614 //
1615 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1616 // "std" or "bad_alloc" as necessary to form the exception specification.
1617 // However, we do not make these implicit declarations visible to name
1618 // lookup.
Sebastian Redl8999fe12011-03-14 18:08:30 +00001619 // Note that the C++0x versions of operator delete are deallocation functions,
1620 // and thus are implicitly noexcept.
1621 if (!StdBadAlloc && !getLangOptions().CPlusPlus0x) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001622 // The "std::bad_alloc" class has not yet been declared, so build it
1623 // implicitly.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001624 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1625 getOrCreateStdNamespace(),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001626 SourceLocation(), SourceLocation(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001627 &PP.getIdentifierTable().get("bad_alloc"),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001628 0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001629 getStdBadAlloc()->setImplicit(true);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001630 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001631
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001632 GlobalNewDeleteDeclared = true;
1633
1634 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1635 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001636 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001637
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001638 DeclareGlobalAllocationFunction(
1639 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001640 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001641 DeclareGlobalAllocationFunction(
1642 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001643 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001644 DeclareGlobalAllocationFunction(
1645 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1646 Context.VoidTy, VoidPtr);
1647 DeclareGlobalAllocationFunction(
1648 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1649 Context.VoidTy, VoidPtr);
1650}
1651
1652/// DeclareGlobalAllocationFunction - Declares a single implicit global
1653/// allocation function if it doesn't already exist.
1654void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001655 QualType Return, QualType Argument,
1656 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001657 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1658
1659 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001660 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001661 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001662 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001663 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001664 // Only look at non-template functions, as it is the predefined,
1665 // non-templated allocation function we are trying to declare here.
1666 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1667 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001668 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001669 Func->getParamDecl(0)->getType().getUnqualifiedType());
1670 // FIXME: Do we need to check for default arguments here?
Douglas Gregor7b868622010-08-18 15:06:25 +00001671 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1672 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00001673 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001674 return;
Douglas Gregor7b868622010-08-18 15:06:25 +00001675 }
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001676 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001677 }
1678 }
1679
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001680 QualType BadAllocType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001681 bool HasBadAllocExceptionSpec
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001682 = (Name.getCXXOverloadedOperator() == OO_New ||
1683 Name.getCXXOverloadedOperator() == OO_Array_New);
Sebastian Redl8999fe12011-03-14 18:08:30 +00001684 if (HasBadAllocExceptionSpec && !getLangOptions().CPlusPlus0x) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001685 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001686 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001687 }
John McCalle23cf432010-12-14 08:05:40 +00001688
1689 FunctionProtoType::ExtProtoInfo EPI;
John McCalle23cf432010-12-14 08:05:40 +00001690 if (HasBadAllocExceptionSpec) {
Sebastian Redl8999fe12011-03-14 18:08:30 +00001691 if (!getLangOptions().CPlusPlus0x) {
1692 EPI.ExceptionSpecType = EST_Dynamic;
1693 EPI.NumExceptions = 1;
1694 EPI.Exceptions = &BadAllocType;
1695 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00001696 } else {
Sebastian Redl8999fe12011-03-14 18:08:30 +00001697 EPI.ExceptionSpecType = getLangOptions().CPlusPlus0x ?
1698 EST_BasicNoexcept : EST_DynamicNone;
John McCalle23cf432010-12-14 08:05:40 +00001699 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001700
John McCalle23cf432010-12-14 08:05:40 +00001701 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001702 FunctionDecl *Alloc =
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001703 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
1704 SourceLocation(), Name,
John McCalld931b082010-08-26 03:08:43 +00001705 FnType, /*TInfo=*/0, SC_None,
1706 SC_None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001707 Alloc->setImplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001708
Nuno Lopesfc284482009-12-16 16:59:22 +00001709 if (AddMallocAttr)
Sean Huntcf807c42010-08-18 23:23:40 +00001710 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001711
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001712 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001713 SourceLocation(), 0,
1714 Argument, /*TInfo=*/0,
1715 SC_None, SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00001716 Alloc->setParams(Param);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001717
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001718 // FIXME: Also add this declaration to the IdentifierResolver, but
1719 // make sure it is at the end of the chain to coincide with the
1720 // global scope.
John McCall5f1e0942010-08-24 08:50:51 +00001721 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001722}
1723
Anders Carlsson78f74552009-11-15 18:45:20 +00001724bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1725 DeclarationName Name,
Sean Hunt2be7e902011-05-12 22:46:29 +00001726 FunctionDecl* &Operator, bool Diagnose) {
John McCalla24dc2e2009-11-17 02:14:36 +00001727 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001728 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001729 LookupQualifiedName(Found, RD);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001730
John McCalla24dc2e2009-11-17 02:14:36 +00001731 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001732 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001733
Chandler Carruth23893242010-06-28 00:30:51 +00001734 Found.suppressDiagnostics();
1735
Chris Lattner5f9e2722011-07-23 10:55:15 +00001736 SmallVector<DeclAccessPair,4> Matches;
Anders Carlsson78f74552009-11-15 18:45:20 +00001737 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1738 F != FEnd; ++F) {
Chandler Carruth09556fd2010-08-08 07:04:00 +00001739 NamedDecl *ND = (*F)->getUnderlyingDecl();
1740
1741 // Ignore template operator delete members from the check for a usual
1742 // deallocation function.
1743 if (isa<FunctionTemplateDecl>(ND))
1744 continue;
1745
1746 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall046a7462010-08-04 00:31:26 +00001747 Matches.push_back(F.getPair());
1748 }
1749
1750 // There's exactly one suitable operator; pick it.
1751 if (Matches.size() == 1) {
1752 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
Sean Hunt2be7e902011-05-12 22:46:29 +00001753
1754 if (Operator->isDeleted()) {
1755 if (Diagnose) {
1756 Diag(StartLoc, diag::err_deleted_function_use);
1757 Diag(Operator->getLocation(), diag::note_unavailable_here) << true;
1758 }
1759 return true;
1760 }
1761
John McCall046a7462010-08-04 00:31:26 +00001762 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Sean Hunt2be7e902011-05-12 22:46:29 +00001763 Matches[0], Diagnose);
John McCall046a7462010-08-04 00:31:26 +00001764 return false;
1765
1766 // We found multiple suitable operators; complain about the ambiguity.
1767 } else if (!Matches.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001768 if (Diagnose) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00001769 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1770 << Name << RD;
John McCall046a7462010-08-04 00:31:26 +00001771
Chris Lattner5f9e2722011-07-23 10:55:15 +00001772 for (SmallVectorImpl<DeclAccessPair>::iterator
Sean Huntcb45a0f2011-05-12 22:46:25 +00001773 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1774 Diag((*F)->getUnderlyingDecl()->getLocation(),
1775 diag::note_member_declared_here) << Name;
1776 }
John McCall046a7462010-08-04 00:31:26 +00001777 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001778 }
1779
1780 // We did find operator delete/operator delete[] declarations, but
1781 // none of them were suitable.
1782 if (!Found.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001783 if (Diagnose) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00001784 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1785 << Name << RD;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001786
Sean Huntcb45a0f2011-05-12 22:46:25 +00001787 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1788 F != FEnd; ++F)
1789 Diag((*F)->getUnderlyingDecl()->getLocation(),
1790 diag::note_member_declared_here) << Name;
1791 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001792 return true;
1793 }
1794
1795 // Look for a global declaration.
1796 DeclareGlobalNewDelete();
1797 DeclContext *TUDecl = Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001798
Anders Carlsson78f74552009-11-15 18:45:20 +00001799 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1800 Expr* DeallocArgs[1];
1801 DeallocArgs[0] = &Null;
1802 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
Sean Hunt2be7e902011-05-12 22:46:29 +00001803 DeallocArgs, 1, TUDecl, !Diagnose,
1804 Operator, Diagnose))
Anders Carlsson78f74552009-11-15 18:45:20 +00001805 return true;
1806
1807 assert(Operator && "Did not find a deallocation function!");
1808 return false;
1809}
1810
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001811/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1812/// @code ::delete ptr; @endcode
1813/// or
1814/// @code delete [] ptr; @endcode
John McCall60d7b3a2010-08-24 06:29:42 +00001815ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001816Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley429bb272011-04-08 18:41:53 +00001817 bool ArrayForm, Expr *ExE) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001818 // C++ [expr.delete]p1:
1819 // The operand shall have a pointer type, or a class type having a single
1820 // conversion function to a pointer type. The result has type void.
1821 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001822 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1823
John Wiegley429bb272011-04-08 18:41:53 +00001824 ExprResult Ex = Owned(ExE);
Anders Carlssond67c4c32009-08-16 20:29:29 +00001825 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001826 bool ArrayFormAsWritten = ArrayForm;
John McCall6ec278d2011-01-27 09:37:56 +00001827 bool UsualArrayDeleteWantsSize = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001828
John Wiegley429bb272011-04-08 18:41:53 +00001829 if (!Ex.get()->isTypeDependent()) {
1830 QualType Type = Ex.get()->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001831
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001832 if (const RecordType *Record = Type->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001833 if (RequireCompleteType(StartLoc, Type,
Douglas Gregor254a9422010-07-29 14:44:35 +00001834 PDiag(diag::err_delete_incomplete_class_type)))
1835 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001836
Chris Lattner5f9e2722011-07-23 10:55:15 +00001837 SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
John McCall32daa422010-03-31 01:36:47 +00001838
Fariborz Jahanian53462782009-09-11 21:44:33 +00001839 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001840 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001841 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001842 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001843 NamedDecl *D = I.getDecl();
1844 if (isa<UsingShadowDecl>(D))
1845 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1846
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001847 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001848 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001849 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001850
John McCall32daa422010-03-31 01:36:47 +00001851 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001852
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001853 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1854 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedman13578692010-08-05 02:49:48 +00001855 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001856 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001857 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001858 if (ObjectPtrConversions.size() == 1) {
1859 // We have a single conversion to a pointer-to-object type. Perform
1860 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001861 // TODO: don't redo the conversion calculation.
John Wiegley429bb272011-04-08 18:41:53 +00001862 ExprResult Res =
1863 PerformImplicitConversion(Ex.get(),
John McCall32daa422010-03-31 01:36:47 +00001864 ObjectPtrConversions.front()->getConversionType(),
John Wiegley429bb272011-04-08 18:41:53 +00001865 AA_Converting);
1866 if (Res.isUsable()) {
1867 Ex = move(Res);
1868 Type = Ex.get()->getType();
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001869 }
1870 }
1871 else if (ObjectPtrConversions.size() > 1) {
1872 Diag(StartLoc, diag::err_ambiguous_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001873 << Type << Ex.get()->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001874 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1875 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001876 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001877 }
Sebastian Redl28507842009-02-26 14:39:58 +00001878 }
1879
Sebastian Redlf53597f2009-03-15 17:47:39 +00001880 if (!Type->isPointerType())
1881 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001882 << Type << Ex.get()->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001883
Ted Kremenek6217b802009-07-29 21:53:49 +00001884 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmane52c9142011-07-26 22:25:31 +00001885 QualType PointeeElem = Context.getBaseElementType(Pointee);
1886
1887 if (unsigned AddressSpace = Pointee.getAddressSpace())
1888 return Diag(Ex.get()->getLocStart(),
1889 diag::err_address_space_qualified_delete)
1890 << Pointee.getUnqualifiedType() << AddressSpace;
1891
1892 CXXRecordDecl *PointeeRD = 0;
Douglas Gregor94a61572010-05-24 17:01:56 +00001893 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001894 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregor94a61572010-05-24 17:01:56 +00001895 // effectively bans deletion of "void*". However, most compilers support
1896 // this, so we treat it as a warning unless we're in a SFINAE context.
1897 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001898 << Type << Ex.get()->getSourceRange();
Eli Friedmane52c9142011-07-26 22:25:31 +00001899 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00001900 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001901 << Type << Ex.get()->getSourceRange());
Eli Friedmane52c9142011-07-26 22:25:31 +00001902 } else if (!Pointee->isDependentType()) {
1903 if (!RequireCompleteType(StartLoc, Pointee,
1904 PDiag(diag::warn_delete_incomplete)
1905 << Ex.get()->getSourceRange())) {
1906 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
1907 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
1908 }
1909 }
1910
Abramo Bagnara30bb4202011-11-16 15:42:13 +00001911 // Perform lvalue-to-rvalue cast, if needed.
1912 Ex = DefaultLvalueConversion(Ex.take());
1913
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001914 // C++ [expr.delete]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001915 // [Note: a pointer to a const type can be the operand of a
1916 // delete-expression; it is not necessary to cast away the constness
1917 // (5.2.11) of the pointer expression before it is used as the operand
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001918 // of the delete-expression. ]
John McCallf85e1932011-06-15 23:02:42 +00001919 if (!Context.hasSameType(Ex.get()->getType(), Context.VoidPtrTy))
Abramo Bagnara30bb4202011-11-16 15:42:13 +00001920 Ex = Owned(ImplicitCastExpr::Create(Context, Context.VoidPtrTy,
1921 CK_BitCast, Ex.take(), 0, VK_RValue));
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001922
1923 if (Pointee->isArrayType() && !ArrayForm) {
1924 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley429bb272011-04-08 18:41:53 +00001925 << Type << Ex.get()->getSourceRange()
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001926 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1927 ArrayForm = true;
1928 }
1929
Anders Carlssond67c4c32009-08-16 20:29:29 +00001930 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1931 ArrayForm ? OO_Array_Delete : OO_Delete);
1932
Eli Friedmane52c9142011-07-26 22:25:31 +00001933 if (PointeeRD) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001934 if (!UseGlobal &&
Eli Friedmane52c9142011-07-26 22:25:31 +00001935 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
1936 OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001937 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001938
John McCall6ec278d2011-01-27 09:37:56 +00001939 // If we're allocating an array of records, check whether the
1940 // usual operator delete[] has a size_t parameter.
1941 if (ArrayForm) {
1942 // If the user specifically asked to use the global allocator,
1943 // we'll need to do the lookup into the class.
1944 if (UseGlobal)
1945 UsualArrayDeleteWantsSize =
1946 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
1947
1948 // Otherwise, the usual operator delete[] should be the
1949 // function we just found.
1950 else if (isa<CXXMethodDecl>(OperatorDelete))
1951 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
1952 }
1953
Eli Friedmane52c9142011-07-26 22:25:31 +00001954 if (!PointeeRD->hasTrivialDestructor())
1955 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001956 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001957 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor9b623632010-10-12 23:32:35 +00001958 DiagnoseUseOfDecl(Dtor, StartLoc);
1959 }
Argyrios Kyrtzidis6f0074a2011-05-24 19:53:26 +00001960
1961 // C++ [expr.delete]p3:
1962 // In the first alternative (delete object), if the static type of the
1963 // object to be deleted is different from its dynamic type, the static
1964 // type shall be a base class of the dynamic type of the object to be
1965 // deleted and the static type shall have a virtual destructor or the
1966 // behavior is undefined.
1967 //
1968 // Note: a final class cannot be derived from, no issue there
Eli Friedmanef8c79c2011-07-26 23:27:24 +00001969 if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) {
Eli Friedmane52c9142011-07-26 22:25:31 +00001970 CXXDestructorDecl *dtor = PointeeRD->getDestructor();
Eli Friedmanef8c79c2011-07-26 23:27:24 +00001971 if (dtor && !dtor->isVirtual()) {
1972 if (PointeeRD->isAbstract()) {
1973 // If the class is abstract, we warn by default, because we're
1974 // sure the code has undefined behavior.
1975 Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor)
1976 << PointeeElem;
1977 } else if (!ArrayForm) {
1978 // Otherwise, if this is not an array delete, it's a bit suspect,
1979 // but not necessarily wrong.
1980 Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
1981 }
1982 }
Argyrios Kyrtzidis6f0074a2011-05-24 19:53:26 +00001983 }
John McCallf85e1932011-06-15 23:02:42 +00001984
1985 } else if (getLangOptions().ObjCAutoRefCount &&
1986 PointeeElem->isObjCLifetimeType() &&
1987 (PointeeElem.getObjCLifetime() == Qualifiers::OCL_Strong ||
1988 PointeeElem.getObjCLifetime() == Qualifiers::OCL_Weak) &&
1989 ArrayForm) {
1990 Diag(StartLoc, diag::warn_err_new_delete_object_array)
1991 << 1 << PointeeElem;
Anders Carlssond67c4c32009-08-16 20:29:29 +00001992 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001993
Anders Carlssond67c4c32009-08-16 20:29:29 +00001994 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001995 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001996 DeclareGlobalNewDelete();
1997 DeclContext *TUDecl = Context.getTranslationUnitDecl();
John Wiegley429bb272011-04-08 18:41:53 +00001998 Expr *Arg = Ex.get();
Mike Stump1eb44332009-09-09 15:08:12 +00001999 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
John Wiegley429bb272011-04-08 18:41:53 +00002000 &Arg, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00002001 OperatorDelete))
2002 return ExprError();
2003 }
Mike Stump1eb44332009-09-09 15:08:12 +00002004
John McCall9c82afc2010-04-20 02:18:25 +00002005 MarkDeclarationReferenced(StartLoc, OperatorDelete);
John McCall6ec278d2011-01-27 09:37:56 +00002006
Douglas Gregord880f522011-02-01 15:50:11 +00002007 // Check access and ambiguity of operator delete and destructor.
Eli Friedmane52c9142011-07-26 22:25:31 +00002008 if (PointeeRD) {
2009 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
John Wiegley429bb272011-04-08 18:41:53 +00002010 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregord880f522011-02-01 15:50:11 +00002011 PDiag(diag::err_access_dtor) << PointeeElem);
2012 }
2013 }
2014
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002015 }
2016
Sebastian Redlf53597f2009-03-15 17:47:39 +00002017 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
John McCall6ec278d2011-01-27 09:37:56 +00002018 ArrayFormAsWritten,
2019 UsualArrayDeleteWantsSize,
John Wiegley429bb272011-04-08 18:41:53 +00002020 OperatorDelete, Ex.take(), StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002021}
2022
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002023/// \brief Check the use of the given variable as a C++ condition in an if,
2024/// while, do-while, or switch statement.
John McCall60d7b3a2010-08-24 06:29:42 +00002025ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCallf89e55a2010-11-18 06:31:45 +00002026 SourceLocation StmtLoc,
2027 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002028 QualType T = ConditionVar->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002029
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002030 // C++ [stmt.select]p2:
2031 // The declarator shall not specify a function or an array.
2032 if (T->isFunctionType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002033 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002034 diag::err_invalid_use_of_function_type)
2035 << ConditionVar->getSourceRange());
2036 else if (T->isArrayType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002037 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002038 diag::err_invalid_use_of_array_type)
2039 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00002040
John Wiegley429bb272011-04-08 18:41:53 +00002041 ExprResult Condition =
2042 Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
Douglas Gregor40d96a62011-02-28 21:54:11 +00002043 ConditionVar,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002044 ConditionVar->getLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00002045 ConditionVar->getType().getNonReferenceType(),
John Wiegley429bb272011-04-08 18:41:53 +00002046 VK_LValue));
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002047
2048 MarkDeclarationReferenced(ConditionVar->getLocation(), ConditionVar);
2049
John Wiegley429bb272011-04-08 18:41:53 +00002050 if (ConvertToBoolean) {
2051 Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
2052 if (Condition.isInvalid())
2053 return ExprError();
2054 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002055
John Wiegley429bb272011-04-08 18:41:53 +00002056 return move(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002057}
2058
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002059/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
John Wiegley429bb272011-04-08 18:41:53 +00002060ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002061 // C++ 6.4p4:
2062 // The value of a condition that is an initialized declaration in a statement
2063 // other than a switch statement is the value of the declared variable
2064 // implicitly converted to type bool. If that conversion is ill-formed, the
2065 // program is ill-formed.
2066 // The value of a condition that is an expression is the value of the
2067 // expression, implicitly converted to bool.
2068 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002069 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002070}
Douglas Gregor77a52232008-09-12 00:47:35 +00002071
2072/// Helper function to determine whether this is the (deprecated) C++
2073/// conversion from a string literal to a pointer to non-const char or
2074/// non-const wchar_t (for narrow and wide string literals,
2075/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00002076bool
Douglas Gregor77a52232008-09-12 00:47:35 +00002077Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
2078 // Look inside the implicit cast, if it exists.
2079 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
2080 From = Cast->getSubExpr();
2081
2082 // A string literal (2.13.4) that is not a wide string literal can
2083 // be converted to an rvalue of type "pointer to char"; a wide
2084 // string literal can be converted to an rvalue of type "pointer
2085 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00002086 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00002087 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00002088 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00002089 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00002090 // This conversion is considered only when there is an
2091 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregor5cee1192011-07-27 05:40:30 +00002092 if (!ToPtrType->getPointeeType().hasQualifiers()) {
2093 switch (StrLit->getKind()) {
2094 case StringLiteral::UTF8:
2095 case StringLiteral::UTF16:
2096 case StringLiteral::UTF32:
2097 // We don't allow UTF literals to be implicitly converted
2098 break;
2099 case StringLiteral::Ascii:
2100 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
2101 ToPointeeType->getKind() == BuiltinType::Char_S);
2102 case StringLiteral::Wide:
2103 return ToPointeeType->isWideCharType();
2104 }
2105 }
Douglas Gregor77a52232008-09-12 00:47:35 +00002106 }
2107
2108 return false;
2109}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002110
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002111static ExprResult BuildCXXCastArgument(Sema &S,
John McCall2de56d12010-08-25 11:45:40 +00002112 SourceLocation CastLoc,
2113 QualType Ty,
2114 CastKind Kind,
2115 CXXMethodDecl *Method,
John McCallca82a822011-09-21 08:36:56 +00002116 DeclAccessPair FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002117 bool HadMultipleCandidates,
John McCall2de56d12010-08-25 11:45:40 +00002118 Expr *From) {
Douglas Gregorba70ab62010-04-16 22:17:36 +00002119 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002120 default: llvm_unreachable("Unhandled cast kind!");
John McCall2de56d12010-08-25 11:45:40 +00002121 case CK_ConstructorConversion: {
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002122 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
John McCallca0408f2010-08-23 06:44:23 +00002123 ASTOwningVector<Expr*> ConstructorArgs(S);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002124
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002125 if (S.CompleteConstructorCall(Constructor,
John McCallf312b1e2010-08-26 23:41:50 +00002126 MultiExprArg(&From, 1),
Douglas Gregorba70ab62010-04-16 22:17:36 +00002127 CastLoc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00002128 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002129
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002130 S.CheckConstructorAccess(CastLoc, Constructor, Constructor->getAccess(),
2131 S.PDiag(diag::err_access_ctor));
2132
2133 ExprResult Result
2134 = S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2135 move_arg(ConstructorArgs),
2136 HadMultipleCandidates, /*ZeroInit*/ false,
2137 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregorba70ab62010-04-16 22:17:36 +00002138 if (Result.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00002139 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002140
Douglas Gregorba70ab62010-04-16 22:17:36 +00002141 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
2142 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002143
John McCall2de56d12010-08-25 11:45:40 +00002144 case CK_UserDefinedConversion: {
Douglas Gregorba70ab62010-04-16 22:17:36 +00002145 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002146
Douglas Gregorba70ab62010-04-16 22:17:36 +00002147 // Create an implicit call expr that calls it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002148 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method,
2149 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00002150 if (Result.isInvalid())
2151 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00002152 // Record usage of conversion in an implicit cast.
2153 Result = S.Owned(ImplicitCastExpr::Create(S.Context,
2154 Result.get()->getType(),
2155 CK_UserDefinedConversion,
2156 Result.get(), 0,
2157 Result.get()->getValueKind()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002158
John McCallca82a822011-09-21 08:36:56 +00002159 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ 0, FoundDecl);
2160
Douglas Gregorf2ae5262011-01-20 00:18:04 +00002161 return S.MaybeBindToTemporary(Result.get());
Douglas Gregorba70ab62010-04-16 22:17:36 +00002162 }
2163 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002164}
Douglas Gregorba70ab62010-04-16 22:17:36 +00002165
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002166/// PerformImplicitConversion - Perform an implicit conversion of the
2167/// expression From to the type ToType using the pre-computed implicit
John Wiegley429bb272011-04-08 18:41:53 +00002168/// conversion sequence ICS. Returns the converted
Douglas Gregor68647482009-12-16 03:45:30 +00002169/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002170/// used in the error message.
John Wiegley429bb272011-04-08 18:41:53 +00002171ExprResult
2172Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002173 const ImplicitConversionSequence &ICS,
John McCallf85e1932011-06-15 23:02:42 +00002174 AssignmentAction Action,
2175 CheckedConversionKind CCK) {
John McCall1d318332010-01-12 00:44:57 +00002176 switch (ICS.getKind()) {
John Wiegley429bb272011-04-08 18:41:53 +00002177 case ImplicitConversionSequence::StandardConversion: {
Richard Smithc8d7f582011-11-29 22:48:16 +00002178 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
2179 Action, CCK);
John Wiegley429bb272011-04-08 18:41:53 +00002180 if (Res.isInvalid())
2181 return ExprError();
2182 From = Res.take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002183 break;
John Wiegley429bb272011-04-08 18:41:53 +00002184 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002185
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002186 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002187
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00002188 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCalldaa8e4e2010-11-15 09:13:47 +00002189 CastKind CastKind;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002190 QualType BeforeToType;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00002191 assert(FD && "FIXME: aggregate initialization from init list");
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002192 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCall2de56d12010-08-25 11:45:40 +00002193 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002194
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002195 // If the user-defined conversion is specified by a conversion function,
2196 // the initial standard conversion sequence converts the source type to
2197 // the implicit object parameter of the conversion function.
2198 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCall9ec94452010-12-04 09:57:16 +00002199 } else {
2200 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCall2de56d12010-08-25 11:45:40 +00002201 CastKind = CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002202 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00002203 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002204 // If the user-defined conversion is specified by a constructor, the
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002205 // initial standard conversion sequence converts the source type to the
2206 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00002207 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
2208 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002209 }
Douglas Gregora3998bd2010-12-02 21:47:04 +00002210 // Watch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00002211 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley429bb272011-04-08 18:41:53 +00002212 ExprResult Res =
Richard Smithc8d7f582011-11-29 22:48:16 +00002213 PerformImplicitConversion(From, BeforeToType,
2214 ICS.UserDefined.Before, AA_Converting,
2215 CCK);
John Wiegley429bb272011-04-08 18:41:53 +00002216 if (Res.isInvalid())
2217 return ExprError();
2218 From = Res.take();
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002219 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002220
2221 ExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00002222 = BuildCXXCastArgument(*this,
2223 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00002224 ToType.getNonReferenceType(),
Douglas Gregor83eecbe2011-01-20 01:32:05 +00002225 CastKind, cast<CXXMethodDecl>(FD),
2226 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002227 ICS.UserDefined.HadMultipleCandidates,
John McCall9ae2f072010-08-23 23:25:46 +00002228 From);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002229
2230 if (CastArg.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00002231 return ExprError();
Eli Friedmand8889622009-11-27 04:41:50 +00002232
John Wiegley429bb272011-04-08 18:41:53 +00002233 From = CastArg.take();
Eli Friedmand8889622009-11-27 04:41:50 +00002234
Richard Smithc8d7f582011-11-29 22:48:16 +00002235 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
2236 AA_Converting, CCK);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00002237 }
John McCall1d318332010-01-12 00:44:57 +00002238
2239 case ImplicitConversionSequence::AmbiguousConversion:
John McCall120d63c2010-08-24 20:38:10 +00002240 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall1d318332010-01-12 00:44:57 +00002241 PDiag(diag::err_typecheck_ambiguous_condition)
2242 << From->getSourceRange());
John Wiegley429bb272011-04-08 18:41:53 +00002243 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002244
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002245 case ImplicitConversionSequence::EllipsisConversion:
David Blaikieb219cfc2011-09-23 05:06:16 +00002246 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002247
2248 case ImplicitConversionSequence::BadConversion:
John Wiegley429bb272011-04-08 18:41:53 +00002249 return ExprError();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002250 }
2251
2252 // Everything went well.
John Wiegley429bb272011-04-08 18:41:53 +00002253 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002254}
2255
Richard Smithc8d7f582011-11-29 22:48:16 +00002256/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002257/// expression From to the type ToType by following the standard
John Wiegley429bb272011-04-08 18:41:53 +00002258/// conversion sequence SCS. Returns the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00002259/// expression. Flavor is the context in which we're performing this
2260/// conversion, for use in error messages.
John Wiegley429bb272011-04-08 18:41:53 +00002261ExprResult
Richard Smithc8d7f582011-11-29 22:48:16 +00002262Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00002263 const StandardConversionSequence& SCS,
John McCallf85e1932011-06-15 23:02:42 +00002264 AssignmentAction Action,
2265 CheckedConversionKind CCK) {
2266 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
2267
Mike Stump390b4cc2009-05-16 07:39:55 +00002268 // Overall FIXME: we are recomputing too many types here and doing far too
2269 // much extra work. What this means is that we need to keep track of more
2270 // information that is computed when we try the implicit conversion initially,
2271 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002272 QualType FromType = From->getType();
John McCallf85e1932011-06-15 23:02:42 +00002273
Douglas Gregor225c41e2008-11-03 19:09:14 +00002274 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00002275 // FIXME: When can ToType be a reference type?
2276 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002277 if (SCS.Second == ICK_Derived_To_Base) {
John McCallca0408f2010-08-23 06:44:23 +00002278 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002279 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCallca0408f2010-08-23 06:44:23 +00002280 MultiExprArg(*this, &From, 1),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002281 /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002282 ConstructorArgs))
John Wiegley429bb272011-04-08 18:41:53 +00002283 return ExprError();
2284 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2285 ToType, SCS.CopyConstructor,
2286 move_arg(ConstructorArgs),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002287 /*HadMultipleCandidates*/ false,
John Wiegley429bb272011-04-08 18:41:53 +00002288 /*ZeroInit*/ false,
2289 CXXConstructExpr::CK_Complete,
2290 SourceRange());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002291 }
John Wiegley429bb272011-04-08 18:41:53 +00002292 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2293 ToType, SCS.CopyConstructor,
2294 MultiExprArg(*this, &From, 1),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002295 /*HadMultipleCandidates*/ false,
John Wiegley429bb272011-04-08 18:41:53 +00002296 /*ZeroInit*/ false,
2297 CXXConstructExpr::CK_Complete,
2298 SourceRange());
Douglas Gregor225c41e2008-11-03 19:09:14 +00002299 }
2300
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002301 // Resolve overloaded function references.
2302 if (Context.hasSameType(FromType, Context.OverloadTy)) {
2303 DeclAccessPair Found;
2304 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2305 true, Found);
2306 if (!Fn)
John Wiegley429bb272011-04-08 18:41:53 +00002307 return ExprError();
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002308
2309 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
John Wiegley429bb272011-04-08 18:41:53 +00002310 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002311
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002312 From = FixOverloadedFunctionReference(From, Found, Fn);
2313 FromType = From->getType();
2314 }
2315
Richard Smithc8d7f582011-11-29 22:48:16 +00002316 // Perform the first implicit conversion.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002317 switch (SCS.First) {
2318 case ICK_Identity:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002319 // Nothing to do.
2320 break;
2321
Eli Friedmand814eaf2012-01-24 22:51:26 +00002322 case ICK_Lvalue_To_Rvalue: {
John McCall3c3b7f92011-10-25 17:37:35 +00002323 assert(From->getObjectKind() != OK_ObjCProperty);
John McCallf6a16482010-12-04 03:47:34 +00002324 FromType = FromType.getUnqualifiedType();
Eli Friedmand814eaf2012-01-24 22:51:26 +00002325 ExprResult FromRes = DefaultLvalueConversion(From);
2326 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
2327 From = FromRes.take();
John McCallf6a16482010-12-04 03:47:34 +00002328 break;
Eli Friedmand814eaf2012-01-24 22:51:26 +00002329 }
John McCallf6a16482010-12-04 03:47:34 +00002330
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002331 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002332 FromType = Context.getArrayDecayedType(FromType);
Richard Smithc8d7f582011-11-29 22:48:16 +00002333 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
2334 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002335 break;
2336
2337 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002338 FromType = Context.getPointerType(FromType);
Richard Smithc8d7f582011-11-29 22:48:16 +00002339 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
2340 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002341 break;
2342
2343 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002344 llvm_unreachable("Improper first standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002345 }
2346
Richard Smithc8d7f582011-11-29 22:48:16 +00002347 // Perform the second implicit conversion
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002348 switch (SCS.Second) {
2349 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002350 // If both sides are functions (or pointers/references to them), there could
2351 // be incompatible exception declarations.
2352 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002353 return ExprError();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002354 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002355 break;
2356
Douglas Gregor43c79c22009-12-09 00:47:37 +00002357 case ICK_NoReturn_Adjustment:
2358 // If both sides are functions (or pointers/references to them), there could
2359 // be incompatible exception declarations.
2360 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002361 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002362
Richard Smithc8d7f582011-11-29 22:48:16 +00002363 From = ImpCastExprToType(From, ToType, CK_NoOp,
2364 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor43c79c22009-12-09 00:47:37 +00002365 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002366
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002367 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002368 case ICK_Integral_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002369 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
2370 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002371 break;
2372
2373 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002374 case ICK_Floating_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002375 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
2376 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002377 break;
2378
2379 case ICK_Complex_Promotion:
John McCalldaa8e4e2010-11-15 09:13:47 +00002380 case ICK_Complex_Conversion: {
2381 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2382 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2383 CastKind CK;
2384 if (FromEl->isRealFloatingType()) {
2385 if (ToEl->isRealFloatingType())
2386 CK = CK_FloatingComplexCast;
2387 else
2388 CK = CK_FloatingComplexToIntegralComplex;
2389 } else if (ToEl->isRealFloatingType()) {
2390 CK = CK_IntegralComplexToFloatingComplex;
2391 } else {
2392 CK = CK_IntegralComplexCast;
2393 }
Richard Smithc8d7f582011-11-29 22:48:16 +00002394 From = ImpCastExprToType(From, ToType, CK,
2395 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002396 break;
John McCalldaa8e4e2010-11-15 09:13:47 +00002397 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00002398
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002399 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00002400 if (ToType->isRealFloatingType())
Richard Smithc8d7f582011-11-29 22:48:16 +00002401 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
2402 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002403 else
Richard Smithc8d7f582011-11-29 22:48:16 +00002404 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
2405 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002406 break;
2407
Douglas Gregorf9201e02009-02-11 23:02:49 +00002408 case ICK_Compatible_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002409 From = ImpCastExprToType(From, ToType, CK_NoOp,
2410 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002411 break;
2412
John McCallf85e1932011-06-15 23:02:42 +00002413 case ICK_Writeback_Conversion:
Anders Carlsson61faec12009-09-12 04:46:44 +00002414 case ICK_Pointer_Conversion: {
Douglas Gregora3998bd2010-12-02 21:47:04 +00002415 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor45920e82008-12-19 17:40:08 +00002416 // Diagnose incompatible Objective-C conversions
Douglas Gregor8cf0d222011-06-11 04:42:12 +00002417 if (Action == AA_Initializing || Action == AA_Assigning)
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002418 Diag(From->getSourceRange().getBegin(),
2419 diag::ext_typecheck_convert_incompatible_pointer)
2420 << ToType << From->getType() << Action
Anna Zaks67221552011-07-28 19:51:27 +00002421 << From->getSourceRange() << 0;
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002422 else
2423 Diag(From->getSourceRange().getBegin(),
2424 diag::ext_typecheck_convert_incompatible_pointer)
2425 << From->getType() << ToType << Action
Anna Zaks67221552011-07-28 19:51:27 +00002426 << From->getSourceRange() << 0;
John McCallf85e1932011-06-15 23:02:42 +00002427
Douglas Gregor926df6c2011-06-11 01:09:30 +00002428 if (From->getType()->isObjCObjectPointerType() &&
2429 ToType->isObjCObjectPointerType())
2430 EmitRelatedResultTypeNote(From);
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002431 }
2432 else if (getLangOptions().ObjCAutoRefCount &&
2433 !CheckObjCARCUnavailableWeakConversion(ToType,
2434 From->getType())) {
John McCall7f3a6d32011-09-09 06:12:06 +00002435 if (Action == AA_Initializing)
2436 Diag(From->getSourceRange().getBegin(),
2437 diag::err_arc_weak_unavailable_assign);
2438 else
2439 Diag(From->getSourceRange().getBegin(),
2440 diag::err_arc_convesion_of_weak_unavailable)
2441 << (Action == AA_Casting) << From->getType() << ToType
2442 << From->getSourceRange();
2443 }
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002444
John McCalldaa8e4e2010-11-15 09:13:47 +00002445 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002446 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002447 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002448 return ExprError();
John McCalldc05b112011-09-10 01:16:55 +00002449
2450 // Make sure we extend blocks if necessary.
2451 // FIXME: doing this here is really ugly.
2452 if (Kind == CK_BlockPointerToObjCPointerCast) {
2453 ExprResult E = From;
2454 (void) PrepareCastToObjCObjectPointer(E);
2455 From = E.take();
2456 }
2457
Richard Smithc8d7f582011-11-29 22:48:16 +00002458 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2459 .take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002460 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00002461 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002462
Anders Carlsson61faec12009-09-12 04:46:44 +00002463 case ICK_Pointer_Member: {
John McCalldaa8e4e2010-11-15 09:13:47 +00002464 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002465 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002466 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002467 return ExprError();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002468 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002469 return ExprError();
Richard Smithc8d7f582011-11-29 22:48:16 +00002470 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2471 .take();
Anders Carlsson61faec12009-09-12 04:46:44 +00002472 break;
2473 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002474
Abramo Bagnara737d5442011-04-07 09:26:19 +00002475 case ICK_Boolean_Conversion:
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00002476 // Perform half-to-boolean conversion via float.
2477 if (From->getType()->isHalfType()) {
2478 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).take();
2479 FromType = Context.FloatTy;
2480 }
2481
Richard Smithc8d7f582011-11-29 22:48:16 +00002482 From = ImpCastExprToType(From, Context.BoolTy,
2483 ScalarTypeToBooleanCastKind(FromType),
2484 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002485 break;
2486
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002487 case ICK_Derived_To_Base: {
John McCallf871d0c2010-08-07 06:22:56 +00002488 CXXCastPath BasePath;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002489 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002490 ToType.getNonReferenceType(),
2491 From->getLocStart(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002492 From->getSourceRange(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002493 &BasePath,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002494 CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002495 return ExprError();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002496
Richard Smithc8d7f582011-11-29 22:48:16 +00002497 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
2498 CK_DerivedToBase, From->getValueKind(),
2499 &BasePath, CCK).take();
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002500 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002501 }
2502
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002503 case ICK_Vector_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002504 From = ImpCastExprToType(From, ToType, CK_BitCast,
2505 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002506 break;
2507
2508 case ICK_Vector_Splat:
Richard Smithc8d7f582011-11-29 22:48:16 +00002509 From = ImpCastExprToType(From, ToType, CK_VectorSplat,
2510 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002511 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002512
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002513 case ICK_Complex_Real:
John McCalldaa8e4e2010-11-15 09:13:47 +00002514 // Case 1. x -> _Complex y
2515 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2516 QualType ElType = ToComplex->getElementType();
2517 bool isFloatingComplex = ElType->isRealFloatingType();
2518
2519 // x -> y
2520 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2521 // do nothing
2522 } else if (From->getType()->isRealFloatingType()) {
Richard Smithc8d7f582011-11-29 22:48:16 +00002523 From = ImpCastExprToType(From, ElType,
2524 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002525 } else {
2526 assert(From->getType()->isIntegerType());
Richard Smithc8d7f582011-11-29 22:48:16 +00002527 From = ImpCastExprToType(From, ElType,
2528 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002529 }
2530 // y -> _Complex y
Richard Smithc8d7f582011-11-29 22:48:16 +00002531 From = ImpCastExprToType(From, ToType,
2532 isFloatingComplex ? CK_FloatingRealToComplex
2533 : CK_IntegralRealToComplex).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002534
2535 // Case 2. _Complex x -> y
2536 } else {
2537 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2538 assert(FromComplex);
2539
2540 QualType ElType = FromComplex->getElementType();
2541 bool isFloatingComplex = ElType->isRealFloatingType();
2542
2543 // _Complex x -> x
Richard Smithc8d7f582011-11-29 22:48:16 +00002544 From = ImpCastExprToType(From, ElType,
2545 isFloatingComplex ? CK_FloatingComplexToReal
2546 : CK_IntegralComplexToReal,
2547 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002548
2549 // x -> y
2550 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2551 // do nothing
2552 } else if (ToType->isRealFloatingType()) {
Richard Smithc8d7f582011-11-29 22:48:16 +00002553 From = ImpCastExprToType(From, ToType,
2554 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
2555 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002556 } else {
2557 assert(ToType->isIntegerType());
Richard Smithc8d7f582011-11-29 22:48:16 +00002558 From = ImpCastExprToType(From, ToType,
2559 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
2560 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002561 }
2562 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002563 break;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002564
2565 case ICK_Block_Pointer_Conversion: {
Richard Smithc8d7f582011-11-29 22:48:16 +00002566 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
2567 VK_RValue, /*BasePath=*/0, CCK).take();
John McCallf85e1932011-06-15 23:02:42 +00002568 break;
2569 }
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002570
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002571 case ICK_TransparentUnionConversion: {
John Wiegley429bb272011-04-08 18:41:53 +00002572 ExprResult FromRes = Owned(From);
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002573 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00002574 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
2575 if (FromRes.isInvalid())
2576 return ExprError();
2577 From = FromRes.take();
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002578 assert ((ConvTy == Sema::Compatible) &&
2579 "Improper transparent union conversion");
2580 (void)ConvTy;
2581 break;
2582 }
2583
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002584 case ICK_Lvalue_To_Rvalue:
2585 case ICK_Array_To_Pointer:
2586 case ICK_Function_To_Pointer:
2587 case ICK_Qualification:
2588 case ICK_Num_Conversion_Kinds:
David Blaikieb219cfc2011-09-23 05:06:16 +00002589 llvm_unreachable("Improper second standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002590 }
2591
2592 switch (SCS.Third) {
2593 case ICK_Identity:
2594 // Nothing to do.
2595 break;
2596
Sebastian Redl906082e2010-07-20 04:20:21 +00002597 case ICK_Qualification: {
2598 // The qualification keeps the category of the inner expression, unless the
2599 // target type isn't a reference.
John McCall5baba9d2010-08-25 10:28:54 +00002600 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00002601 From->getValueKind() : VK_RValue;
Richard Smithc8d7f582011-11-29 22:48:16 +00002602 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
2603 CK_NoOp, VK, /*BasePath=*/0, CCK).take();
Douglas Gregora9bff302010-02-28 18:30:25 +00002604
Douglas Gregor069a6da2011-03-14 16:13:32 +00002605 if (SCS.DeprecatedStringLiteralToCharPtr &&
2606 !getLangOptions().WritableStrings)
Douglas Gregora9bff302010-02-28 18:30:25 +00002607 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2608 << ToType.getNonReferenceType();
2609
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002610 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002611 }
2612
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002613 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002614 llvm_unreachable("Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002615 }
2616
John Wiegley429bb272011-04-08 18:41:53 +00002617 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002618}
2619
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002620ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002621 SourceLocation KWLoc,
2622 ParsedType Ty,
2623 SourceLocation RParen) {
2624 TypeSourceInfo *TSInfo;
2625 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002626
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002627 if (!TSInfo)
2628 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002629 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002630}
2631
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002632/// \brief Check the completeness of a type in a unary type trait.
2633///
2634/// If the particular type trait requires a complete type, tries to complete
2635/// it. If completing the type fails, a diagnostic is emitted and false
2636/// returned. If completing the type succeeds or no completion was required,
2637/// returns true.
2638static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S,
2639 UnaryTypeTrait UTT,
2640 SourceLocation Loc,
2641 QualType ArgTy) {
2642 // C++0x [meta.unary.prop]p3:
2643 // For all of the class templates X declared in this Clause, instantiating
2644 // that template with a template argument that is a class template
2645 // specialization may result in the implicit instantiation of the template
2646 // argument if and only if the semantics of X require that the argument
2647 // must be a complete type.
2648 // We apply this rule to all the type trait expressions used to implement
2649 // these class templates. We also try to follow any GCC documented behavior
2650 // in these expressions to ensure portability of standard libraries.
2651 switch (UTT) {
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002652 // is_complete_type somewhat obviously cannot require a complete type.
2653 case UTT_IsCompleteType:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002654 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002655
2656 // These traits are modeled on the type predicates in C++0x
2657 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
2658 // requiring a complete type, as whether or not they return true cannot be
2659 // impacted by the completeness of the type.
2660 case UTT_IsVoid:
2661 case UTT_IsIntegral:
2662 case UTT_IsFloatingPoint:
2663 case UTT_IsArray:
2664 case UTT_IsPointer:
2665 case UTT_IsLvalueReference:
2666 case UTT_IsRvalueReference:
2667 case UTT_IsMemberFunctionPointer:
2668 case UTT_IsMemberObjectPointer:
2669 case UTT_IsEnum:
2670 case UTT_IsUnion:
2671 case UTT_IsClass:
2672 case UTT_IsFunction:
2673 case UTT_IsReference:
2674 case UTT_IsArithmetic:
2675 case UTT_IsFundamental:
2676 case UTT_IsObject:
2677 case UTT_IsScalar:
2678 case UTT_IsCompound:
2679 case UTT_IsMemberPointer:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002680 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002681
2682 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
2683 // which requires some of its traits to have the complete type. However,
2684 // the completeness of the type cannot impact these traits' semantics, and
2685 // so they don't require it. This matches the comments on these traits in
2686 // Table 49.
2687 case UTT_IsConst:
2688 case UTT_IsVolatile:
2689 case UTT_IsSigned:
2690 case UTT_IsUnsigned:
2691 return true;
2692
2693 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002694 // applied to a complete type.
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002695 case UTT_IsTrivial:
Sean Huntfeb375d2011-05-13 00:31:07 +00002696 case UTT_IsTriviallyCopyable:
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002697 case UTT_IsStandardLayout:
2698 case UTT_IsPOD:
2699 case UTT_IsLiteral:
2700 case UTT_IsEmpty:
2701 case UTT_IsPolymorphic:
2702 case UTT_IsAbstract:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002703 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002704
Douglas Gregor5e9392b2011-12-03 18:14:24 +00002705 // These traits require a complete type.
2706 case UTT_IsFinal:
2707
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002708 // These trait expressions are designed to help implement predicates in
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002709 // [meta.unary.prop] despite not being named the same. They are specified
2710 // by both GCC and the Embarcadero C++ compiler, and require the complete
2711 // type due to the overarching C++0x type predicates being implemented
2712 // requiring the complete type.
2713 case UTT_HasNothrowAssign:
2714 case UTT_HasNothrowConstructor:
2715 case UTT_HasNothrowCopy:
2716 case UTT_HasTrivialAssign:
Sean Hunt023df372011-05-09 18:22:59 +00002717 case UTT_HasTrivialDefaultConstructor:
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002718 case UTT_HasTrivialCopy:
2719 case UTT_HasTrivialDestructor:
2720 case UTT_HasVirtualDestructor:
2721 // Arrays of unknown bound are expressly allowed.
2722 QualType ElTy = ArgTy;
2723 if (ArgTy->isIncompleteArrayType())
2724 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
2725
2726 // The void type is expressly allowed.
2727 if (ElTy->isVoidType())
2728 return true;
2729
2730 return !S.RequireCompleteType(
2731 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleycf566412011-04-28 02:06:46 +00002732 }
Chandler Carruth73e0a912011-05-01 07:23:17 +00002733 llvm_unreachable("Type trait not handled by switch");
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002734}
2735
2736static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT,
2737 SourceLocation KeyLoc, QualType T) {
Chandler Carruthd064c702011-05-01 08:41:10 +00002738 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleycf566412011-04-28 02:06:46 +00002739
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002740 ASTContext &C = Self.Context;
2741 switch(UTT) {
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002742 // Type trait expressions corresponding to the primary type category
2743 // predicates in C++0x [meta.unary.cat].
2744 case UTT_IsVoid:
2745 return T->isVoidType();
2746 case UTT_IsIntegral:
2747 return T->isIntegralType(C);
2748 case UTT_IsFloatingPoint:
2749 return T->isFloatingType();
2750 case UTT_IsArray:
2751 return T->isArrayType();
2752 case UTT_IsPointer:
2753 return T->isPointerType();
2754 case UTT_IsLvalueReference:
2755 return T->isLValueReferenceType();
2756 case UTT_IsRvalueReference:
2757 return T->isRValueReferenceType();
2758 case UTT_IsMemberFunctionPointer:
2759 return T->isMemberFunctionPointerType();
2760 case UTT_IsMemberObjectPointer:
2761 return T->isMemberDataPointerType();
2762 case UTT_IsEnum:
2763 return T->isEnumeralType();
Chandler Carruth28eeb382011-05-01 06:11:03 +00002764 case UTT_IsUnion:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002765 return T->isUnionType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002766 case UTT_IsClass:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002767 return T->isClassType() || T->isStructureType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002768 case UTT_IsFunction:
2769 return T->isFunctionType();
2770
2771 // Type trait expressions which correspond to the convenient composition
2772 // predicates in C++0x [meta.unary.comp].
2773 case UTT_IsReference:
2774 return T->isReferenceType();
2775 case UTT_IsArithmetic:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002776 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002777 case UTT_IsFundamental:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002778 return T->isFundamentalType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002779 case UTT_IsObject:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002780 return T->isObjectType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002781 case UTT_IsScalar:
John McCallf85e1932011-06-15 23:02:42 +00002782 // Note: semantic analysis depends on Objective-C lifetime types to be
2783 // considered scalar types. However, such types do not actually behave
2784 // like scalar types at run time (since they may require retain/release
2785 // operations), so we report them as non-scalar.
2786 if (T->isObjCLifetimeType()) {
2787 switch (T.getObjCLifetime()) {
2788 case Qualifiers::OCL_None:
2789 case Qualifiers::OCL_ExplicitNone:
2790 return true;
2791
2792 case Qualifiers::OCL_Strong:
2793 case Qualifiers::OCL_Weak:
2794 case Qualifiers::OCL_Autoreleasing:
2795 return false;
2796 }
2797 }
2798
Chandler Carruthcec0ced2011-05-01 09:29:55 +00002799 return T->isScalarType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002800 case UTT_IsCompound:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002801 return T->isCompoundType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002802 case UTT_IsMemberPointer:
2803 return T->isMemberPointerType();
2804
2805 // Type trait expressions which correspond to the type property predicates
2806 // in C++0x [meta.unary.prop].
2807 case UTT_IsConst:
2808 return T.isConstQualified();
2809 case UTT_IsVolatile:
2810 return T.isVolatileQualified();
2811 case UTT_IsTrivial:
John McCallf85e1932011-06-15 23:02:42 +00002812 return T.isTrivialType(Self.Context);
Sean Huntfeb375d2011-05-13 00:31:07 +00002813 case UTT_IsTriviallyCopyable:
John McCallf85e1932011-06-15 23:02:42 +00002814 return T.isTriviallyCopyableType(Self.Context);
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002815 case UTT_IsStandardLayout:
2816 return T->isStandardLayoutType();
2817 case UTT_IsPOD:
John McCallf85e1932011-06-15 23:02:42 +00002818 return T.isPODType(Self.Context);
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002819 case UTT_IsLiteral:
2820 return T->isLiteralType();
2821 case UTT_IsEmpty:
2822 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2823 return !RD->isUnion() && RD->isEmpty();
2824 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002825 case UTT_IsPolymorphic:
Chandler Carruth28eeb382011-05-01 06:11:03 +00002826 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2827 return RD->isPolymorphic();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002828 return false;
2829 case UTT_IsAbstract:
Chandler Carruth28eeb382011-05-01 06:11:03 +00002830 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2831 return RD->isAbstract();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002832 return false;
Douglas Gregor5e9392b2011-12-03 18:14:24 +00002833 case UTT_IsFinal:
2834 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2835 return RD->hasAttr<FinalAttr>();
2836 return false;
John Wiegley20c0da72011-04-27 23:09:49 +00002837 case UTT_IsSigned:
2838 return T->isSignedIntegerType();
John Wiegley20c0da72011-04-27 23:09:49 +00002839 case UTT_IsUnsigned:
2840 return T->isUnsignedIntegerType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002841
2842 // Type trait expressions which query classes regarding their construction,
2843 // destruction, and copying. Rather than being based directly on the
2844 // related type predicates in the standard, they are specified by both
2845 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
2846 // specifications.
2847 //
2848 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
2849 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Sean Hunt023df372011-05-09 18:22:59 +00002850 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002851 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2852 // If __is_pod (type) is true then the trait is true, else if type is
2853 // a cv class or union type (or array thereof) with a trivial default
2854 // constructor ([class.ctor]) then the trait is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00002855 if (T.isPODType(Self.Context))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002856 return true;
2857 if (const RecordType *RT =
2858 C.getBaseElementType(T)->getAs<RecordType>())
Sean Hunt023df372011-05-09 18:22:59 +00002859 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDefaultConstructor();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002860 return false;
2861 case UTT_HasTrivialCopy:
2862 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2863 // If __is_pod (type) is true or type is a reference type then
2864 // the trait is true, else if type is a cv class or union type
2865 // with a trivial copy constructor ([class.copy]) then the trait
2866 // is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00002867 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002868 return true;
2869 if (const RecordType *RT = T->getAs<RecordType>())
2870 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2871 return false;
2872 case UTT_HasTrivialAssign:
2873 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2874 // If type is const qualified or is a reference type then the
2875 // trait is false. Otherwise if __is_pod (type) is true then the
2876 // trait is true, else if type is a cv class or union type with
2877 // a trivial copy assignment ([class.copy]) then the trait is
2878 // true, else it is false.
2879 // Note: the const and reference restrictions are interesting,
2880 // given that const and reference members don't prevent a class
2881 // from having a trivial copy assignment operator (but do cause
2882 // errors if the copy assignment operator is actually used, q.v.
2883 // [class.copy]p12).
2884
2885 if (C.getBaseElementType(T).isConstQualified())
2886 return false;
John McCallf85e1932011-06-15 23:02:42 +00002887 if (T.isPODType(Self.Context))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002888 return true;
2889 if (const RecordType *RT = T->getAs<RecordType>())
2890 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2891 return false;
2892 case UTT_HasTrivialDestructor:
2893 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2894 // If __is_pod (type) is true or type is a reference type
2895 // then the trait is true, else if type is a cv class or union
2896 // type (or array thereof) with a trivial destructor
2897 // ([class.dtor]) then the trait is true, else it is
2898 // false.
John McCallf85e1932011-06-15 23:02:42 +00002899 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002900 return true;
John McCallf85e1932011-06-15 23:02:42 +00002901
2902 // Objective-C++ ARC: autorelease types don't require destruction.
2903 if (T->isObjCLifetimeType() &&
2904 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
2905 return true;
2906
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002907 if (const RecordType *RT =
2908 C.getBaseElementType(T)->getAs<RecordType>())
2909 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2910 return false;
2911 // TODO: Propagate nothrowness for implicitly declared special members.
2912 case UTT_HasNothrowAssign:
2913 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2914 // If type is const qualified or is a reference type then the
2915 // trait is false. Otherwise if __has_trivial_assign (type)
2916 // is true then the trait is true, else if type is a cv class
2917 // or union type with copy assignment operators that are known
2918 // not to throw an exception then the trait is true, else it is
2919 // false.
2920 if (C.getBaseElementType(T).isConstQualified())
2921 return false;
2922 if (T->isReferenceType())
2923 return false;
John McCallf85e1932011-06-15 23:02:42 +00002924 if (T.isPODType(Self.Context) || T->isObjCLifetimeType())
2925 return true;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002926 if (const RecordType *RT = T->getAs<RecordType>()) {
2927 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2928 if (RD->hasTrivialCopyAssignment())
2929 return true;
2930
2931 bool FoundAssign = false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002932 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redlf8aca862010-09-14 23:40:14 +00002933 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2934 Sema::LookupOrdinaryName);
2935 if (Self.LookupQualifiedName(Res, RD)) {
Douglas Gregord41679d2011-10-12 15:40:49 +00002936 Res.suppressDiagnostics();
Sebastian Redlf8aca862010-09-14 23:40:14 +00002937 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2938 Op != OpEnd; ++Op) {
Douglas Gregord41679d2011-10-12 15:40:49 +00002939 if (isa<FunctionTemplateDecl>(*Op))
2940 continue;
2941
Sebastian Redlf8aca862010-09-14 23:40:14 +00002942 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2943 if (Operator->isCopyAssignmentOperator()) {
2944 FoundAssign = true;
2945 const FunctionProtoType *CPT
2946 = Operator->getType()->getAs<FunctionProtoType>();
Richard Smith7a614d82011-06-11 17:19:42 +00002947 if (CPT->getExceptionSpecType() == EST_Delayed)
2948 return false;
2949 if (!CPT->isNothrow(Self.Context))
2950 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002951 }
2952 }
2953 }
Douglas Gregord41679d2011-10-12 15:40:49 +00002954
Richard Smith7a614d82011-06-11 17:19:42 +00002955 return FoundAssign;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002956 }
2957 return false;
2958 case UTT_HasNothrowCopy:
2959 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2960 // If __has_trivial_copy (type) is true then the trait is true, else
2961 // if type is a cv class or union type with copy constructors that are
2962 // known not to throw an exception then the trait is true, else it is
2963 // false.
John McCallf85e1932011-06-15 23:02:42 +00002964 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002965 return true;
2966 if (const RecordType *RT = T->getAs<RecordType>()) {
2967 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2968 if (RD->hasTrivialCopyConstructor())
2969 return true;
2970
2971 bool FoundConstructor = false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002972 unsigned FoundTQs;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002973 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl5f4e8992010-09-13 21:10:20 +00002974 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002975 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002976 // A template constructor is never a copy constructor.
2977 // FIXME: However, it may actually be selected at the actual overload
2978 // resolution point.
2979 if (isa<FunctionTemplateDecl>(*Con))
2980 continue;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002981 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2982 if (Constructor->isCopyConstructor(FoundTQs)) {
2983 FoundConstructor = true;
2984 const FunctionProtoType *CPT
2985 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smith7a614d82011-06-11 17:19:42 +00002986 if (CPT->getExceptionSpecType() == EST_Delayed)
2987 return false;
Sebastian Redl60618fa2011-03-12 11:50:43 +00002988 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redl751025d2010-09-13 22:02:47 +00002989 // For now, we'll be conservative and assume that they can throw.
Richard Smith7a614d82011-06-11 17:19:42 +00002990 if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1)
2991 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002992 }
2993 }
2994
Richard Smith7a614d82011-06-11 17:19:42 +00002995 return FoundConstructor;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002996 }
2997 return false;
2998 case UTT_HasNothrowConstructor:
2999 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3000 // If __has_trivial_constructor (type) is true then the trait is
3001 // true, else if type is a cv class or union type (or array
3002 // thereof) with a default constructor that is known not to
3003 // throw an exception then the trait is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00003004 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003005 return true;
3006 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
3007 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Hunt023df372011-05-09 18:22:59 +00003008 if (RD->hasTrivialDefaultConstructor())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003009 return true;
3010
Sebastian Redl751025d2010-09-13 22:02:47 +00003011 DeclContext::lookup_const_iterator Con, ConEnd;
3012 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
3013 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00003014 // FIXME: In C++0x, a constructor template can be a default constructor.
3015 if (isa<FunctionTemplateDecl>(*Con))
3016 continue;
Sebastian Redl751025d2010-09-13 22:02:47 +00003017 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3018 if (Constructor->isDefaultConstructor()) {
3019 const FunctionProtoType *CPT
3020 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smith7a614d82011-06-11 17:19:42 +00003021 if (CPT->getExceptionSpecType() == EST_Delayed)
3022 return false;
Sebastian Redl751025d2010-09-13 22:02:47 +00003023 // TODO: check whether evaluating default arguments can throw.
3024 // For now, we'll be conservative and assume that they can throw.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00003025 return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
Sebastian Redl751025d2010-09-13 22:02:47 +00003026 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003027 }
3028 }
3029 return false;
3030 case UTT_HasVirtualDestructor:
3031 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3032 // If type is a class type with a virtual destructor ([class.dtor])
3033 // then the trait is true, else it is false.
3034 if (const RecordType *Record = T->getAs<RecordType>()) {
3035 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redlf8aca862010-09-14 23:40:14 +00003036 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003037 return Destructor->isVirtual();
3038 }
3039 return false;
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003040
3041 // These type trait expressions are modeled on the specifications for the
3042 // Embarcadero C++0x type trait functions:
3043 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
3044 case UTT_IsCompleteType:
3045 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
3046 // Returns True if and only if T is a complete type at the point of the
3047 // function call.
3048 return !T->isIncompleteType();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003049 }
Chandler Carruth83f563c2011-05-01 07:44:17 +00003050 llvm_unreachable("Type trait not covered by switch");
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003051}
3052
3053ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00003054 SourceLocation KWLoc,
3055 TypeSourceInfo *TSInfo,
3056 SourceLocation RParen) {
3057 QualType T = TSInfo->getType();
Chandler Carrutheb65a102011-04-30 10:07:32 +00003058 if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T))
3059 return ExprError();
Sebastian Redl64b45f72009-01-05 20:52:13 +00003060
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003061 bool Value = false;
3062 if (!T->isDependentType())
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00003063 Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003064
3065 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson3292d5c2009-07-07 19:06:02 +00003066 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00003067}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003068
Francois Pichet6ad6f282010-12-07 00:08:36 +00003069ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
3070 SourceLocation KWLoc,
3071 ParsedType LhsTy,
3072 ParsedType RhsTy,
3073 SourceLocation RParen) {
3074 TypeSourceInfo *LhsTSInfo;
3075 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
3076 if (!LhsTSInfo)
3077 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
3078
3079 TypeSourceInfo *RhsTSInfo;
3080 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
3081 if (!RhsTSInfo)
3082 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
3083
3084 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
3085}
3086
3087static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
3088 QualType LhsT, QualType RhsT,
3089 SourceLocation KeyLoc) {
Chandler Carruthd064c702011-05-01 08:41:10 +00003090 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
3091 "Cannot evaluate traits of dependent types");
Francois Pichet6ad6f282010-12-07 00:08:36 +00003092
3093 switch(BTT) {
John McCalld89d30f2011-01-28 22:02:36 +00003094 case BTT_IsBaseOf: {
Francois Pichet6ad6f282010-12-07 00:08:36 +00003095 // C++0x [meta.rel]p2
John McCalld89d30f2011-01-28 22:02:36 +00003096 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet6ad6f282010-12-07 00:08:36 +00003097 // Base and Derived are not unions and name the same class type without
3098 // regard to cv-qualifiers.
Francois Pichet6ad6f282010-12-07 00:08:36 +00003099
John McCalld89d30f2011-01-28 22:02:36 +00003100 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
3101 if (!lhsRecord) return false;
3102
3103 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
3104 if (!rhsRecord) return false;
3105
3106 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
3107 == (lhsRecord == rhsRecord));
3108
3109 if (lhsRecord == rhsRecord)
3110 return !lhsRecord->getDecl()->isUnion();
3111
3112 // C++0x [meta.rel]p2:
3113 // If Base and Derived are class types and are different types
3114 // (ignoring possible cv-qualifiers) then Derived shall be a
3115 // complete type.
3116 if (Self.RequireCompleteType(KeyLoc, RhsT,
3117 diag::err_incomplete_type_used_in_type_trait_expr))
3118 return false;
3119
3120 return cast<CXXRecordDecl>(rhsRecord->getDecl())
3121 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
3122 }
John Wiegley20c0da72011-04-27 23:09:49 +00003123 case BTT_IsSame:
3124 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichetf1872372010-12-08 22:35:30 +00003125 case BTT_TypeCompatible:
3126 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
3127 RhsT.getUnqualifiedType());
John Wiegley20c0da72011-04-27 23:09:49 +00003128 case BTT_IsConvertible:
Douglas Gregor9f361132011-01-27 20:28:01 +00003129 case BTT_IsConvertibleTo: {
3130 // C++0x [meta.rel]p4:
3131 // Given the following function prototype:
3132 //
3133 // template <class T>
3134 // typename add_rvalue_reference<T>::type create();
3135 //
3136 // the predicate condition for a template specialization
3137 // is_convertible<From, To> shall be satisfied if and only if
3138 // the return expression in the following code would be
3139 // well-formed, including any implicit conversions to the return
3140 // type of the function:
3141 //
3142 // To test() {
3143 // return create<From>();
3144 // }
3145 //
3146 // Access checking is performed as if in a context unrelated to To and
3147 // From. Only the validity of the immediate context of the expression
3148 // of the return-statement (including conversions to the return type)
3149 // is considered.
3150 //
3151 // We model the initialization as a copy-initialization of a temporary
3152 // of the appropriate type, which for this expression is identical to the
3153 // return statement (since NRVO doesn't apply).
3154 if (LhsT->isObjectType() || LhsT->isFunctionType())
3155 LhsT = Self.Context.getRValueReferenceType(LhsT);
3156
3157 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorb608b982011-01-28 02:26:04 +00003158 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor9f361132011-01-27 20:28:01 +00003159 Expr::getValueKindForType(LhsT));
3160 Expr *FromPtr = &From;
3161 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
3162 SourceLocation()));
3163
Eli Friedman3add9f02012-01-25 01:05:57 +00003164 // Perform the initialization in an unevaluated context within a SFINAE
3165 // trap at translation unit scope.
3166 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00003167 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3168 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Douglas Gregor9f361132011-01-27 20:28:01 +00003169 InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003170 if (Init.Failed())
Douglas Gregor9f361132011-01-27 20:28:01 +00003171 return false;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00003172
Douglas Gregor9f361132011-01-27 20:28:01 +00003173 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
3174 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
3175 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00003176 }
3177 llvm_unreachable("Unknown type trait or not implemented");
3178}
3179
3180ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
3181 SourceLocation KWLoc,
3182 TypeSourceInfo *LhsTSInfo,
3183 TypeSourceInfo *RhsTSInfo,
3184 SourceLocation RParen) {
3185 QualType LhsT = LhsTSInfo->getType();
3186 QualType RhsT = RhsTSInfo->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003187
John McCalld89d30f2011-01-28 22:02:36 +00003188 if (BTT == BTT_TypeCompatible) {
Francois Pichetf1872372010-12-08 22:35:30 +00003189 if (getLangOptions().CPlusPlus) {
3190 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
3191 << SourceRange(KWLoc, RParen);
3192 return ExprError();
3193 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00003194 }
3195
3196 bool Value = false;
3197 if (!LhsT->isDependentType() && !RhsT->isDependentType())
3198 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
3199
Francois Pichetf1872372010-12-08 22:35:30 +00003200 // Select trait result type.
3201 QualType ResultType;
3202 switch (BTT) {
Francois Pichetf1872372010-12-08 22:35:30 +00003203 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
John Wiegley20c0da72011-04-27 23:09:49 +00003204 case BTT_IsConvertible: ResultType = Context.BoolTy; break;
3205 case BTT_IsSame: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00003206 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
Douglas Gregor9f361132011-01-27 20:28:01 +00003207 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00003208 }
3209
Francois Pichet6ad6f282010-12-07 00:08:36 +00003210 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
3211 RhsTSInfo, Value, RParen,
Francois Pichetf1872372010-12-08 22:35:30 +00003212 ResultType));
Francois Pichet6ad6f282010-12-07 00:08:36 +00003213}
3214
John Wiegley21ff2e52011-04-28 00:16:57 +00003215ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3216 SourceLocation KWLoc,
3217 ParsedType Ty,
3218 Expr* DimExpr,
3219 SourceLocation RParen) {
3220 TypeSourceInfo *TSInfo;
3221 QualType T = GetTypeFromParser(Ty, &TSInfo);
3222 if (!TSInfo)
3223 TSInfo = Context.getTrivialTypeSourceInfo(T);
3224
3225 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
3226}
3227
3228static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
3229 QualType T, Expr *DimExpr,
3230 SourceLocation KeyLoc) {
Chandler Carruthd064c702011-05-01 08:41:10 +00003231 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley21ff2e52011-04-28 00:16:57 +00003232
3233 switch(ATT) {
3234 case ATT_ArrayRank:
3235 if (T->isArrayType()) {
3236 unsigned Dim = 0;
3237 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3238 ++Dim;
3239 T = AT->getElementType();
3240 }
3241 return Dim;
John Wiegley21ff2e52011-04-28 00:16:57 +00003242 }
John Wiegleycf566412011-04-28 02:06:46 +00003243 return 0;
3244
John Wiegley21ff2e52011-04-28 00:16:57 +00003245 case ATT_ArrayExtent: {
3246 llvm::APSInt Value;
3247 uint64_t Dim;
John Wiegleycf566412011-04-28 02:06:46 +00003248 if (DimExpr->isIntegerConstantExpr(Value, Self.Context, 0, false)) {
3249 if (Value < llvm::APSInt(Value.getBitWidth(), Value.isUnsigned())) {
3250 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
3251 DimExpr->getSourceRange();
3252 return false;
3253 }
John Wiegley21ff2e52011-04-28 00:16:57 +00003254 Dim = Value.getLimitedValue();
John Wiegleycf566412011-04-28 02:06:46 +00003255 } else {
3256 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
3257 DimExpr->getSourceRange();
3258 return false;
3259 }
John Wiegley21ff2e52011-04-28 00:16:57 +00003260
3261 if (T->isArrayType()) {
3262 unsigned D = 0;
3263 bool Matched = false;
3264 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3265 if (Dim == D) {
3266 Matched = true;
3267 break;
3268 }
3269 ++D;
3270 T = AT->getElementType();
3271 }
3272
John Wiegleycf566412011-04-28 02:06:46 +00003273 if (Matched && T->isArrayType()) {
3274 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
3275 return CAT->getSize().getLimitedValue();
3276 }
John Wiegley21ff2e52011-04-28 00:16:57 +00003277 }
John Wiegleycf566412011-04-28 02:06:46 +00003278 return 0;
John Wiegley21ff2e52011-04-28 00:16:57 +00003279 }
3280 }
3281 llvm_unreachable("Unknown type trait or not implemented");
3282}
3283
3284ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
3285 SourceLocation KWLoc,
3286 TypeSourceInfo *TSInfo,
3287 Expr* DimExpr,
3288 SourceLocation RParen) {
3289 QualType T = TSInfo->getType();
John Wiegley21ff2e52011-04-28 00:16:57 +00003290
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003291 // FIXME: This should likely be tracked as an APInt to remove any host
3292 // assumptions about the width of size_t on the target.
Chandler Carruthd064c702011-05-01 08:41:10 +00003293 uint64_t Value = 0;
3294 if (!T->isDependentType())
3295 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
3296
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003297 // While the specification for these traits from the Embarcadero C++
3298 // compiler's documentation says the return type is 'unsigned int', Clang
3299 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
3300 // compiler, there is no difference. On several other platforms this is an
3301 // important distinction.
John Wiegley21ff2e52011-04-28 00:16:57 +00003302 return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value,
Chandler Carruth06207f62011-05-01 07:49:26 +00003303 DimExpr, RParen,
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003304 Context.getSizeType()));
John Wiegley21ff2e52011-04-28 00:16:57 +00003305}
3306
John Wiegley55262202011-04-25 06:54:41 +00003307ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003308 SourceLocation KWLoc,
3309 Expr *Queried,
3310 SourceLocation RParen) {
John Wiegley55262202011-04-25 06:54:41 +00003311 // If error parsing the expression, ignore.
3312 if (!Queried)
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003313 return ExprError();
John Wiegley55262202011-04-25 06:54:41 +00003314
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003315 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegley55262202011-04-25 06:54:41 +00003316
3317 return move(Result);
3318}
3319
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003320static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
3321 switch (ET) {
3322 case ET_IsLValueExpr: return E->isLValue();
3323 case ET_IsRValueExpr: return E->isRValue();
3324 }
3325 llvm_unreachable("Expression trait not covered by switch");
3326}
3327
John Wiegley55262202011-04-25 06:54:41 +00003328ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003329 SourceLocation KWLoc,
3330 Expr *Queried,
3331 SourceLocation RParen) {
John Wiegley55262202011-04-25 06:54:41 +00003332 if (Queried->isTypeDependent()) {
3333 // Delay type-checking for type-dependent expressions.
3334 } else if (Queried->getType()->isPlaceholderType()) {
3335 ExprResult PE = CheckPlaceholderExpr(Queried);
3336 if (PE.isInvalid()) return ExprError();
3337 return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen);
3338 }
3339
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003340 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf7ef0002011-05-01 08:48:19 +00003341
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003342 return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value,
3343 RParen, Context.BoolTy));
John Wiegley55262202011-04-25 06:54:41 +00003344}
3345
Richard Trieudd225092011-09-15 21:56:47 +00003346QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCallf89e55a2010-11-18 06:31:45 +00003347 ExprValueKind &VK,
3348 SourceLocation Loc,
3349 bool isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003350 assert(!LHS.get()->getType()->isPlaceholderType() &&
3351 !RHS.get()->getType()->isPlaceholderType() &&
John McCallea4aba02011-06-30 17:15:34 +00003352 "placeholders should have been weeded out by now");
3353
3354 // The LHS undergoes lvalue conversions if this is ->*.
3355 if (isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003356 LHS = DefaultLvalueConversion(LHS.take());
3357 if (LHS.isInvalid()) return QualType();
John McCallea4aba02011-06-30 17:15:34 +00003358 }
3359
3360 // The RHS always undergoes lvalue conversions.
Richard Trieudd225092011-09-15 21:56:47 +00003361 RHS = DefaultLvalueConversion(RHS.take());
3362 if (RHS.isInvalid()) return QualType();
John McCallea4aba02011-06-30 17:15:34 +00003363
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003364 const char *OpSpelling = isIndirect ? "->*" : ".*";
3365 // C++ 5.5p2
3366 // The binary operator .* [p3: ->*] binds its second operand, which shall
3367 // be of type "pointer to member of T" (where T is a completely-defined
3368 // class type) [...]
Richard Trieudd225092011-09-15 21:56:47 +00003369 QualType RHSType = RHS.get()->getType();
3370 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00003371 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003372 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieudd225092011-09-15 21:56:47 +00003373 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003374 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00003375 }
Douglas Gregore7450f52009-03-24 19:52:54 +00003376
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003377 QualType Class(MemPtr->getClass(), 0);
3378
Douglas Gregor7d520ba2010-10-13 20:41:14 +00003379 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
3380 // member pointer points must be completely-defined. However, there is no
3381 // reason for this semantic distinction, and the rule is not enforced by
3382 // other compilers. Therefore, we do not check this property, as it is
3383 // likely to be considered a defect.
Sebastian Redl59fc2692010-04-10 10:14:54 +00003384
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003385 // C++ 5.5p2
3386 // [...] to its first operand, which shall be of class T or of a class of
3387 // which T is an unambiguous and accessible base class. [p3: a pointer to
3388 // such a class]
Richard Trieudd225092011-09-15 21:56:47 +00003389 QualType LHSType = LHS.get()->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003390 if (isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003391 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
3392 LHSType = Ptr->getPointeeType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003393 else {
3394 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieudd225092011-09-15 21:56:47 +00003395 << OpSpelling << 1 << LHSType
Douglas Gregor849b2432010-03-31 17:46:05 +00003396 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003397 return QualType();
3398 }
3399 }
3400
Richard Trieudd225092011-09-15 21:56:47 +00003401 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00003402 // If we want to check the hierarchy, we need a complete type.
Richard Trieudd225092011-09-15 21:56:47 +00003403 if (RequireCompleteType(Loc, LHSType, PDiag(diag::err_bad_memptr_lhs)
Sebastian Redl17e1d352010-04-23 17:18:26 +00003404 << OpSpelling << (int)isIndirect)) {
3405 return QualType();
3406 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003407 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00003408 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00003409 // FIXME: Would it be useful to print full ambiguity paths, or is that
3410 // overkill?
Richard Trieudd225092011-09-15 21:56:47 +00003411 if (!IsDerivedFrom(LHSType, Class, Paths) ||
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003412 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
3413 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieudd225092011-09-15 21:56:47 +00003414 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003415 return QualType();
3416 }
Eli Friedman3005efe2010-01-16 00:00:48 +00003417 // Cast LHS to type of use.
3418 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00003419 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Sebastian Redl906082e2010-07-20 04:20:21 +00003420
John McCallf871d0c2010-08-07 06:22:56 +00003421 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003422 BuildBasePathArray(Paths, BasePath);
Richard Trieudd225092011-09-15 21:56:47 +00003423 LHS = ImpCastExprToType(LHS.take(), UseType, CK_DerivedToBase, VK,
3424 &BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003425 }
3426
Richard Trieudd225092011-09-15 21:56:47 +00003427 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00003428 // Diagnose use of pointer-to-member type which when used as
3429 // the functional cast in a pointer-to-member expression.
3430 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
3431 return QualType();
3432 }
John McCallf89e55a2010-11-18 06:31:45 +00003433
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003434 // C++ 5.5p2
3435 // The result is an object or a function of the type specified by the
3436 // second operand.
3437 // The cv qualifiers are the union of those in the pointer and the left side,
3438 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003439 QualType Result = MemPtr->getPointeeType();
Richard Trieudd225092011-09-15 21:56:47 +00003440 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCallf89e55a2010-11-18 06:31:45 +00003441
Douglas Gregor6b4df912011-01-26 16:40:18 +00003442 // C++0x [expr.mptr.oper]p6:
3443 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003444 // ill-formed if the second operand is a pointer to member function with
3445 // ref-qualifier &. In a ->* expression or in a .* expression whose object
3446 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor6b4df912011-01-26 16:40:18 +00003447 // is a pointer to member function with ref-qualifier &&.
3448 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
3449 switch (Proto->getRefQualifier()) {
3450 case RQ_None:
3451 // Do nothing
3452 break;
3453
3454 case RQ_LValue:
Richard Trieudd225092011-09-15 21:56:47 +00003455 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
Douglas Gregor6b4df912011-01-26 16:40:18 +00003456 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieudd225092011-09-15 21:56:47 +00003457 << RHSType << 1 << LHS.get()->getSourceRange();
Douglas Gregor6b4df912011-01-26 16:40:18 +00003458 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003459
Douglas Gregor6b4df912011-01-26 16:40:18 +00003460 case RQ_RValue:
Richard Trieudd225092011-09-15 21:56:47 +00003461 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor6b4df912011-01-26 16:40:18 +00003462 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieudd225092011-09-15 21:56:47 +00003463 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor6b4df912011-01-26 16:40:18 +00003464 break;
3465 }
3466 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003467
John McCallf89e55a2010-11-18 06:31:45 +00003468 // C++ [expr.mptr.oper]p6:
3469 // The result of a .* expression whose second operand is a pointer
3470 // to a data member is of the same value category as its
3471 // first operand. The result of a .* expression whose second
3472 // operand is a pointer to a member function is a prvalue. The
3473 // result of an ->* expression is an lvalue if its second operand
3474 // is a pointer to data member and a prvalue otherwise.
John McCall864c0412011-04-26 20:42:42 +00003475 if (Result->isFunctionType()) {
John McCallf89e55a2010-11-18 06:31:45 +00003476 VK = VK_RValue;
John McCall864c0412011-04-26 20:42:42 +00003477 return Context.BoundMemberTy;
3478 } else if (isIndirect) {
John McCallf89e55a2010-11-18 06:31:45 +00003479 VK = VK_LValue;
John McCall864c0412011-04-26 20:42:42 +00003480 } else {
Richard Trieudd225092011-09-15 21:56:47 +00003481 VK = LHS.get()->getValueKind();
John McCall864c0412011-04-26 20:42:42 +00003482 }
John McCallf89e55a2010-11-18 06:31:45 +00003483
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003484 return Result;
3485}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003486
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003487/// \brief Try to convert a type to another according to C++0x 5.16p3.
3488///
3489/// This is part of the parameter validation for the ? operator. If either
3490/// value operand is a class type, the two operands are attempted to be
3491/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003492/// It returns true if the program is ill-formed and has already been diagnosed
3493/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003494static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
3495 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00003496 bool &HaveConversion,
3497 QualType &ToType) {
3498 HaveConversion = false;
3499 ToType = To->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003500
3501 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00003502 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003503 // C++0x 5.16p3
3504 // The process for determining whether an operand expression E1 of type T1
3505 // can be converted to match an operand expression E2 of type T2 is defined
3506 // as follows:
3507 // -- If E2 is an lvalue:
John McCall7eb0a9e2010-11-24 05:12:34 +00003508 bool ToIsLvalue = To->isLValue();
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00003509 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003510 // E1 can be converted to match E2 if E1 can be implicitly converted to
3511 // type "lvalue reference to T2", subject to the constraint that in the
3512 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003513 QualType T = Self.Context.getLValueReferenceType(ToType);
3514 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003515
Douglas Gregorb70cf442010-03-26 20:14:36 +00003516 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3517 if (InitSeq.isDirectReferenceBinding()) {
3518 ToType = T;
3519 HaveConversion = true;
3520 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003521 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003522
Douglas Gregorb70cf442010-03-26 20:14:36 +00003523 if (InitSeq.isAmbiguous())
3524 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003525 }
John McCallb1bdc622010-02-25 01:37:24 +00003526
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003527 // -- If E2 is an rvalue, or if the conversion above cannot be done:
3528 // -- if E1 and E2 have class type, and the underlying class types are
3529 // the same or one is a base class of the other:
3530 QualType FTy = From->getType();
3531 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003532 const RecordType *FRec = FTy->getAs<RecordType>();
3533 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003534 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00003535 Self.IsDerivedFrom(FTy, TTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003536 if (FRec && TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00003537 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003538 // E1 can be converted to match E2 if the class of T2 is the
3539 // same type as, or a base class of, the class of T1, and
3540 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00003541 if (FRec == TRec || FDerivedFromT) {
3542 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003543 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3544 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003545 if (InitSeq) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003546 HaveConversion = true;
3547 return false;
3548 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003549
Douglas Gregorb70cf442010-03-26 20:14:36 +00003550 if (InitSeq.isAmbiguous())
3551 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003552 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003553 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003554
Douglas Gregorb70cf442010-03-26 20:14:36 +00003555 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003556 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003557
Douglas Gregorb70cf442010-03-26 20:14:36 +00003558 // -- Otherwise: E1 can be converted to match E2 if E1 can be
3559 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003560 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00003561 // an rvalue).
3562 //
3563 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
3564 // to the array-to-pointer or function-to-pointer conversions.
3565 if (!TTy->getAs<TagType>())
3566 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003567
Douglas Gregorb70cf442010-03-26 20:14:36 +00003568 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3569 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003570 HaveConversion = !InitSeq.Failed();
Douglas Gregorb70cf442010-03-26 20:14:36 +00003571 ToType = TTy;
3572 if (InitSeq.isAmbiguous())
3573 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3574
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003575 return false;
3576}
3577
3578/// \brief Try to find a common type for two according to C++0x 5.16p5.
3579///
3580/// This is part of the parameter validation for the ? operator. If either
3581/// value operand is a class type, overload resolution is used to find a
3582/// conversion to a common type.
John Wiegley429bb272011-04-08 18:41:53 +00003583static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth82214a82011-02-18 23:54:50 +00003584 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00003585 Expr *Args[2] = { LHS.get(), RHS.get() };
Chandler Carruth82214a82011-02-18 23:54:50 +00003586 OverloadCandidateSet CandidateSet(QuestionLoc);
3587 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
3588 CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003589
3590 OverloadCandidateSet::iterator Best;
Chandler Carruth82214a82011-02-18 23:54:50 +00003591 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley429bb272011-04-08 18:41:53 +00003592 case OR_Success: {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003593 // We found a match. Perform the conversions on the arguments and move on.
John Wiegley429bb272011-04-08 18:41:53 +00003594 ExprResult LHSRes =
3595 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
3596 Best->Conversions[0], Sema::AA_Converting);
3597 if (LHSRes.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003598 break;
John Wiegley429bb272011-04-08 18:41:53 +00003599 LHS = move(LHSRes);
3600
3601 ExprResult RHSRes =
3602 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
3603 Best->Conversions[1], Sema::AA_Converting);
3604 if (RHSRes.isInvalid())
3605 break;
3606 RHS = move(RHSRes);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003607 if (Best->Function)
3608 Self.MarkDeclarationReferenced(QuestionLoc, Best->Function);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003609 return false;
John Wiegley429bb272011-04-08 18:41:53 +00003610 }
3611
Douglas Gregor20093b42009-12-09 23:02:17 +00003612 case OR_No_Viable_Function:
Chandler Carruth82214a82011-02-18 23:54:50 +00003613
3614 // Emit a better diagnostic if one of the expressions is a null pointer
3615 // constant and the other is a pointer type. In this case, the user most
3616 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00003617 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00003618 return true;
3619
3620 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00003621 << LHS.get()->getType() << RHS.get()->getType()
3622 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003623 return true;
3624
Douglas Gregor20093b42009-12-09 23:02:17 +00003625 case OR_Ambiguous:
Chandler Carruth82214a82011-02-18 23:54:50 +00003626 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley429bb272011-04-08 18:41:53 +00003627 << LHS.get()->getType() << RHS.get()->getType()
3628 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00003629 // FIXME: Print the possible common types by printing the return types of
3630 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003631 break;
3632
Douglas Gregor20093b42009-12-09 23:02:17 +00003633 case OR_Deleted:
David Blaikieb219cfc2011-09-23 05:06:16 +00003634 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003635 }
3636 return true;
3637}
3638
Sebastian Redl76458502009-04-17 16:30:52 +00003639/// \brief Perform an "extended" implicit conversion as returned by
3640/// TryClassUnification.
John Wiegley429bb272011-04-08 18:41:53 +00003641static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003642 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley429bb272011-04-08 18:41:53 +00003643 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00003644 SourceLocation());
John Wiegley429bb272011-04-08 18:41:53 +00003645 Expr *Arg = E.take();
3646 InitializationSequence InitSeq(Self, Entity, Kind, &Arg, 1);
3647 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&Arg, 1));
Douglas Gregorb70cf442010-03-26 20:14:36 +00003648 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00003649 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003650
John Wiegley429bb272011-04-08 18:41:53 +00003651 E = Result;
Sebastian Redl76458502009-04-17 16:30:52 +00003652 return false;
3653}
3654
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003655/// \brief Check the operands of ?: under C++ semantics.
3656///
3657/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
3658/// extension. In this case, LHS == Cond. (But they're not aliases.)
John Wiegley429bb272011-04-08 18:41:53 +00003659QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCall56ca35d2011-02-17 10:25:35 +00003660 ExprValueKind &VK, ExprObjectKind &OK,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003661 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00003662 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
3663 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003664
3665 // C++0x 5.16p1
3666 // The first expression is contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00003667 if (!Cond.get()->isTypeDependent()) {
3668 ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
3669 if (CondRes.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003670 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003671 Cond = move(CondRes);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003672 }
3673
John McCallf89e55a2010-11-18 06:31:45 +00003674 // Assume r-value.
3675 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00003676 OK = OK_Ordinary;
John McCallf89e55a2010-11-18 06:31:45 +00003677
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003678 // Either of the arguments dependent?
John Wiegley429bb272011-04-08 18:41:53 +00003679 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003680 return Context.DependentTy;
3681
3682 // C++0x 5.16p2
3683 // If either the second or the third operand has type (cv) void, ...
John Wiegley429bb272011-04-08 18:41:53 +00003684 QualType LTy = LHS.get()->getType();
3685 QualType RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003686 bool LVoid = LTy->isVoidType();
3687 bool RVoid = RTy->isVoidType();
3688 if (LVoid || RVoid) {
3689 // ... then the [l2r] conversions are performed on the second and third
3690 // operands ...
John Wiegley429bb272011-04-08 18:41:53 +00003691 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3692 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3693 if (LHS.isInvalid() || RHS.isInvalid())
3694 return QualType();
3695 LTy = LHS.get()->getType();
3696 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003697
3698 // ... and one of the following shall hold:
3699 // -- The second or the third operand (but not both) is a throw-
3700 // expression; the result is of the type of the other and is an rvalue.
John Wiegley429bb272011-04-08 18:41:53 +00003701 bool LThrow = isa<CXXThrowExpr>(LHS.get());
3702 bool RThrow = isa<CXXThrowExpr>(RHS.get());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003703 if (LThrow && !RThrow)
3704 return RTy;
3705 if (RThrow && !LThrow)
3706 return LTy;
3707
3708 // -- Both the second and third operands have type void; the result is of
3709 // type void and is an rvalue.
3710 if (LVoid && RVoid)
3711 return Context.VoidTy;
3712
3713 // Neither holds, error.
3714 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
3715 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley429bb272011-04-08 18:41:53 +00003716 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003717 return QualType();
3718 }
3719
3720 // Neither is void.
3721
3722 // C++0x 5.16p3
3723 // Otherwise, if the second and third operand have different types, and
3724 // either has (cv) class type, and attempt is made to convert each of those
3725 // operands to the other.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003726 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003727 (LTy->isRecordType() || RTy->isRecordType())) {
3728 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
3729 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003730 QualType L2RType, R2LType;
3731 bool HaveL2R, HaveR2L;
John Wiegley429bb272011-04-08 18:41:53 +00003732 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003733 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003734 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003735 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003736
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003737 // If both can be converted, [...] the program is ill-formed.
3738 if (HaveL2R && HaveR2L) {
3739 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley429bb272011-04-08 18:41:53 +00003740 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003741 return QualType();
3742 }
3743
3744 // If exactly one conversion is possible, that conversion is applied to
3745 // the chosen operand and the converted operands are used in place of the
3746 // original operands for the remainder of this section.
3747 if (HaveL2R) {
John Wiegley429bb272011-04-08 18:41:53 +00003748 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003749 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003750 LTy = LHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003751 } else if (HaveR2L) {
John Wiegley429bb272011-04-08 18:41:53 +00003752 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003753 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003754 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003755 }
3756 }
3757
3758 // C++0x 5.16p4
John McCallf89e55a2010-11-18 06:31:45 +00003759 // If the second and third operands are glvalues of the same value
3760 // category and have the same type, the result is of that type and
3761 // value category and it is a bit-field if the second or the third
3762 // operand is a bit-field, or if both are bit-fields.
John McCall09431682010-11-18 19:01:18 +00003763 // We only extend this to bitfields, not to the crazy other kinds of
3764 // l-values.
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003765 bool Same = Context.hasSameType(LTy, RTy);
John McCallf89e55a2010-11-18 06:31:45 +00003766 if (Same &&
John Wiegley429bb272011-04-08 18:41:53 +00003767 LHS.get()->isGLValue() &&
3768 LHS.get()->getValueKind() == RHS.get()->getValueKind() &&
3769 LHS.get()->isOrdinaryOrBitFieldObject() &&
3770 RHS.get()->isOrdinaryOrBitFieldObject()) {
3771 VK = LHS.get()->getValueKind();
3772 if (LHS.get()->getObjectKind() == OK_BitField ||
3773 RHS.get()->getObjectKind() == OK_BitField)
John McCall09431682010-11-18 19:01:18 +00003774 OK = OK_BitField;
John McCallf89e55a2010-11-18 06:31:45 +00003775 return LTy;
Fariborz Jahanian3911a1a2010-09-25 01:08:05 +00003776 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003777
3778 // C++0x 5.16p5
3779 // Otherwise, the result is an rvalue. If the second and third operands
3780 // do not have the same type, and either has (cv) class type, ...
3781 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
3782 // ... overload resolution is used to determine the conversions (if any)
3783 // to be applied to the operands. If the overload resolution fails, the
3784 // program is ill-formed.
3785 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
3786 return QualType();
3787 }
3788
3789 // C++0x 5.16p6
3790 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
3791 // conversions are performed on the second and third operands.
John Wiegley429bb272011-04-08 18:41:53 +00003792 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3793 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3794 if (LHS.isInvalid() || RHS.isInvalid())
3795 return QualType();
3796 LTy = LHS.get()->getType();
3797 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003798
3799 // After those conversions, one of the following shall hold:
3800 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00003801 // is of that type. If the operands have class type, the result
3802 // is a prvalue temporary of the result type, which is
3803 // copy-initialized from either the second operand or the third
3804 // operand depending on the value of the first operand.
3805 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
3806 if (LTy->isRecordType()) {
3807 // The operands have class type. Make a temporary copy.
3808 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003809 ExprResult LHSCopy = PerformCopyInitialization(Entity,
3810 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00003811 LHS);
Douglas Gregorb65a4582010-05-19 23:40:50 +00003812 if (LHSCopy.isInvalid())
3813 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003814
3815 ExprResult RHSCopy = PerformCopyInitialization(Entity,
3816 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00003817 RHS);
Douglas Gregorb65a4582010-05-19 23:40:50 +00003818 if (RHSCopy.isInvalid())
3819 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003820
John Wiegley429bb272011-04-08 18:41:53 +00003821 LHS = LHSCopy;
3822 RHS = RHSCopy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00003823 }
3824
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003825 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00003826 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003827
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003828 // Extension: conditional operator involving vector types.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003829 if (LTy->isVectorType() || RTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00003830 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003831
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003832 // -- The second and third operands have arithmetic or enumeration type;
3833 // the usual arithmetic conversions are performed to bring them to a
3834 // common type, and the result is of that type.
3835 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
3836 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00003837 if (LHS.isInvalid() || RHS.isInvalid())
3838 return QualType();
3839 return LHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003840 }
3841
3842 // -- The second and third operands have pointer type, or one has pointer
3843 // type and the other is a null pointer constant; pointer conversions
3844 // and qualification conversions are performed to bring them to their
3845 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00003846 // -- The second and third operands have pointer to member type, or one has
3847 // pointer to member type and the other is a null pointer constant;
3848 // pointer to member conversions and qualification conversions are
3849 // performed to bring them to a common type, whose cv-qualification
3850 // shall match the cv-qualification of either the second or the third
3851 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003852 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003853 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003854 isSFINAEContext()? 0 : &NonStandardCompositeType);
3855 if (!Composite.isNull()) {
3856 if (NonStandardCompositeType)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003857 Diag(QuestionLoc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003858 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
3859 << LTy << RTy << Composite
John Wiegley429bb272011-04-08 18:41:53 +00003860 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003861
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003862 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003863 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003864
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003865 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00003866 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
3867 if (!Composite.isNull())
3868 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003869
Chandler Carruth7ef93242011-02-19 00:13:59 +00003870 // Check if we are using a null with a non-pointer type.
John Wiegley429bb272011-04-08 18:41:53 +00003871 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth7ef93242011-02-19 00:13:59 +00003872 return QualType();
3873
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003874 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00003875 << LHS.get()->getType() << RHS.get()->getType()
3876 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003877 return QualType();
3878}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003879
3880/// \brief Find a merged pointer type and convert the two expressions to it.
3881///
Douglas Gregor20b3e992009-08-24 17:42:35 +00003882/// This finds the composite pointer type (or member pointer type) for @p E1
3883/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
3884/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003885/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003886///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003887/// \param Loc The location of the operator requiring these two expressions to
3888/// be converted to the composite pointer type.
3889///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003890/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
3891/// a non-standard (but still sane) composite type to which both expressions
3892/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
3893/// will be set true.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003894QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003895 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003896 bool *NonStandardCompositeType) {
3897 if (NonStandardCompositeType)
3898 *NonStandardCompositeType = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003899
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003900 assert(getLangOptions().CPlusPlus && "This function assumes C++");
3901 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003902
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00003903 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
3904 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00003905 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003906
3907 // C++0x 5.9p2
3908 // Pointer conversions and qualification conversions are performed on
3909 // pointer operands to bring them to their composite pointer type. If
3910 // one operand is a null pointer constant, the composite pointer type is
3911 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00003912 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003913 if (T2->isMemberPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00003914 E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003915 else
John Wiegley429bb272011-04-08 18:41:53 +00003916 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003917 return T2;
3918 }
Douglas Gregorce940492009-09-25 04:25:58 +00003919 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003920 if (T1->isMemberPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00003921 E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003922 else
John Wiegley429bb272011-04-08 18:41:53 +00003923 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003924 return T1;
3925 }
Mike Stump1eb44332009-09-09 15:08:12 +00003926
Douglas Gregor20b3e992009-08-24 17:42:35 +00003927 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003928 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
3929 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003930 return QualType();
3931
3932 // Otherwise, of one of the operands has type "pointer to cv1 void," then
3933 // the other has type "pointer to cv2 T" and the composite pointer type is
3934 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
3935 // Otherwise, the composite pointer type is a pointer type similar to the
3936 // type of one of the operands, with a cv-qualification signature that is
3937 // the union of the cv-qualification signatures of the operand types.
3938 // In practice, the first part here is redundant; it's subsumed by the second.
3939 // What we do here is, we build the two possible composite types, and try the
3940 // conversions in both directions. If only one works, or if the two composite
3941 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00003942 // FIXME: extended qualifiers?
Chris Lattner5f9e2722011-07-23 10:55:15 +00003943 typedef SmallVector<unsigned, 4> QualifierVector;
Sebastian Redla439e6f2009-11-16 21:03:45 +00003944 QualifierVector QualifierUnion;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003945 typedef SmallVector<std::pair<const Type *, const Type *>, 4>
Sebastian Redla439e6f2009-11-16 21:03:45 +00003946 ContainingClassVector;
3947 ContainingClassVector MemberOfClass;
3948 QualType Composite1 = Context.getCanonicalType(T1),
3949 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003950 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00003951 do {
3952 const PointerType *Ptr1, *Ptr2;
3953 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3954 (Ptr2 = Composite2->getAs<PointerType>())) {
3955 Composite1 = Ptr1->getPointeeType();
3956 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003957
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003958 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003959 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003960 if (NonStandardCompositeType &&
3961 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3962 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003963
Douglas Gregor20b3e992009-08-24 17:42:35 +00003964 QualifierUnion.push_back(
3965 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3966 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3967 continue;
3968 }
Mike Stump1eb44332009-09-09 15:08:12 +00003969
Douglas Gregor20b3e992009-08-24 17:42:35 +00003970 const MemberPointerType *MemPtr1, *MemPtr2;
3971 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3972 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3973 Composite1 = MemPtr1->getPointeeType();
3974 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003975
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003976 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003977 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003978 if (NonStandardCompositeType &&
3979 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3980 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003981
Douglas Gregor20b3e992009-08-24 17:42:35 +00003982 QualifierUnion.push_back(
3983 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3984 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
3985 MemPtr2->getClass()));
3986 continue;
3987 }
Mike Stump1eb44332009-09-09 15:08:12 +00003988
Douglas Gregor20b3e992009-08-24 17:42:35 +00003989 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00003990
Douglas Gregor20b3e992009-08-24 17:42:35 +00003991 // Cannot unwrap any more types.
3992 break;
3993 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00003994
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003995 if (NeedConstBefore && NonStandardCompositeType) {
3996 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003997 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003998 // requirements of C++ [conv.qual]p4 bullet 3.
3999 for (unsigned I = 0; I != NeedConstBefore; ++I) {
4000 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
4001 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
4002 *NonStandardCompositeType = true;
4003 }
4004 }
4005 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004006
Douglas Gregor20b3e992009-08-24 17:42:35 +00004007 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00004008 ContainingClassVector::reverse_iterator MOC
4009 = MemberOfClass.rbegin();
4010 for (QualifierVector::reverse_iterator
4011 I = QualifierUnion.rbegin(),
4012 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00004013 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00004014 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00004015 if (MOC->first && MOC->second) {
4016 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00004017 Composite1 = Context.getMemberPointerType(
4018 Context.getQualifiedType(Composite1, Quals),
4019 MOC->first);
4020 Composite2 = Context.getMemberPointerType(
4021 Context.getQualifiedType(Composite2, Quals),
4022 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00004023 } else {
4024 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00004025 Composite1
4026 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
4027 Composite2
4028 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00004029 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004030 }
4031
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004032 // Try to convert to the first composite pointer type.
4033 InitializedEntity Entity1
4034 = InitializedEntity::InitializeTemporary(Composite1);
4035 InitializationKind Kind
4036 = InitializationKind::CreateCopy(Loc, SourceLocation());
4037 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
4038 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00004039
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004040 if (E1ToC1 && E2ToC1) {
4041 // Conversion to Composite1 is viable.
4042 if (!Context.hasSameType(Composite1, Composite2)) {
4043 // Composite2 is a different type from Composite1. Check whether
4044 // Composite2 is also viable.
4045 InitializedEntity Entity2
4046 = InitializedEntity::InitializeTemporary(Composite2);
4047 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4048 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4049 if (E1ToC2 && E2ToC2) {
4050 // Both Composite1 and Composite2 are viable and are different;
4051 // this is an ambiguity.
4052 return QualType();
4053 }
4054 }
4055
4056 // Convert E1 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00004057 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00004058 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004059 if (E1Result.isInvalid())
4060 return QualType();
4061 E1 = E1Result.takeAs<Expr>();
4062
4063 // Convert E2 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00004064 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00004065 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004066 if (E2Result.isInvalid())
4067 return QualType();
4068 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004069
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004070 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004071 }
4072
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004073 // Check whether Composite2 is viable.
4074 InitializedEntity Entity2
4075 = InitializedEntity::InitializeTemporary(Composite2);
4076 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4077 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4078 if (!E1ToC2 || !E2ToC2)
4079 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004080
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004081 // Convert E1 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00004082 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00004083 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004084 if (E1Result.isInvalid())
4085 return QualType();
4086 E1 = E1Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004087
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004088 // Convert E2 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00004089 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00004090 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004091 if (E2Result.isInvalid())
4092 return QualType();
4093 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004094
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004095 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004096}
Anders Carlsson165a0a02009-05-17 18:41:29 +00004097
John McCall60d7b3a2010-08-24 06:29:42 +00004098ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor19cc1c72010-11-01 21:10:29 +00004099 if (!E)
4100 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004101
John McCallf85e1932011-06-15 23:02:42 +00004102 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
4103
4104 // If the result is a glvalue, we shouldn't bind it.
4105 if (!E->isRValue())
Anders Carlsson089c2602009-08-15 23:41:35 +00004106 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004107
John McCallf85e1932011-06-15 23:02:42 +00004108 // In ARC, calls that return a retainable type can return retained,
4109 // in which case we have to insert a consuming cast.
4110 if (getLangOptions().ObjCAutoRefCount &&
4111 E->getType()->isObjCRetainableType()) {
4112
4113 bool ReturnsRetained;
4114
4115 // For actual calls, we compute this by examining the type of the
4116 // called value.
4117 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
4118 Expr *Callee = Call->getCallee()->IgnoreParens();
4119 QualType T = Callee->getType();
4120
4121 if (T == Context.BoundMemberTy) {
4122 // Handle pointer-to-members.
4123 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
4124 T = BinOp->getRHS()->getType();
4125 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
4126 T = Mem->getMemberDecl()->getType();
4127 }
4128
4129 if (const PointerType *Ptr = T->getAs<PointerType>())
4130 T = Ptr->getPointeeType();
4131 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
4132 T = Ptr->getPointeeType();
4133 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
4134 T = MemPtr->getPointeeType();
4135
4136 const FunctionType *FTy = T->getAs<FunctionType>();
4137 assert(FTy && "call to value not of function type?");
4138 ReturnsRetained = FTy->getExtInfo().getProducesResult();
4139
4140 // ActOnStmtExpr arranges things so that StmtExprs of retainable
4141 // type always produce a +1 object.
4142 } else if (isa<StmtExpr>(E)) {
4143 ReturnsRetained = true;
4144
4145 // For message sends and property references, we try to find an
4146 // actual method. FIXME: we should infer retention by selector in
4147 // cases where we don't have an actual method.
4148 } else {
John McCallfc4b1912011-08-03 07:02:44 +00004149 ObjCMethodDecl *D = 0;
John McCallf85e1932011-06-15 23:02:42 +00004150 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
4151 D = Send->getMethodDecl();
John McCallf85e1932011-06-15 23:02:42 +00004152 }
4153
4154 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCallfc4b1912011-08-03 07:02:44 +00004155
4156 // Don't do reclaims on performSelector calls; despite their
4157 // return type, the invoked method doesn't necessarily actually
4158 // return an object.
4159 if (!ReturnsRetained &&
4160 D && D->getMethodFamily() == OMF_performSelector)
4161 return Owned(E);
John McCallf85e1932011-06-15 23:02:42 +00004162 }
4163
John McCall567c5862011-11-14 19:53:16 +00004164 // Don't reclaim an object of Class type.
4165 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
4166 return Owned(E);
4167
John McCall7e5e5f42011-07-07 06:58:02 +00004168 ExprNeedsCleanups = true;
4169
John McCall33e56f32011-09-10 06:18:15 +00004170 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
4171 : CK_ARCReclaimReturnedObject);
John McCall7e5e5f42011-07-07 06:58:02 +00004172 return Owned(ImplicitCastExpr::Create(Context, E->getType(), ck, E, 0,
4173 VK_RValue));
John McCallf85e1932011-06-15 23:02:42 +00004174 }
4175
4176 if (!getLangOptions().CPlusPlus)
4177 return Owned(E);
Douglas Gregor51326552009-12-24 18:51:59 +00004178
Peter Collingbournebceb7552011-11-27 22:09:28 +00004179 QualType ET = Context.getBaseElementType(E->getType());
4180 const RecordType *RT = ET->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00004181 if (!RT)
4182 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004183
John McCall86ff3082010-02-04 22:26:26 +00004184 // That should be enough to guarantee that this type is complete.
4185 // If it has a trivial destructor, we can avoid the extra copy.
Jeffrey Yasskinb7ee2e52011-01-27 19:17:54 +00004186 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall507384f2010-08-12 02:40:37 +00004187 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall86ff3082010-02-04 22:26:26 +00004188 return Owned(E);
4189
John McCallf85e1932011-06-15 23:02:42 +00004190 CXXDestructorDecl *Destructor = LookupDestructor(RD);
4191
4192 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
4193 if (Destructor) {
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00004194 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00004195 CheckDestructorAccess(E->getExprLoc(), Destructor,
4196 PDiag(diag::err_access_dtor_temp)
4197 << E->getType());
John McCallf85e1932011-06-15 23:02:42 +00004198
John McCall80ee6e82011-11-10 05:35:25 +00004199 // We need a cleanup, but we don't need to remember the temporary.
John McCallf85e1932011-06-15 23:02:42 +00004200 ExprNeedsCleanups = true;
John McCallc91cc662010-04-07 00:41:46 +00004201 }
Anders Carlssondef11992009-05-30 20:36:53 +00004202 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
4203}
4204
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004205ExprResult
John McCall4765fa02010-12-06 08:20:24 +00004206Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregor90f93822009-12-22 22:17:25 +00004207 if (SubExpr.isInvalid())
4208 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004209
John McCall4765fa02010-12-06 08:20:24 +00004210 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregor90f93822009-12-22 22:17:25 +00004211}
4212
John McCall80ee6e82011-11-10 05:35:25 +00004213Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
4214 assert(SubExpr && "sub expression can't be null!");
4215
4216 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
4217 assert(ExprCleanupObjects.size() >= FirstCleanup);
4218 assert(ExprNeedsCleanups || ExprCleanupObjects.size() == FirstCleanup);
4219 if (!ExprNeedsCleanups)
4220 return SubExpr;
4221
4222 ArrayRef<ExprWithCleanups::CleanupObject> Cleanups
4223 = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
4224 ExprCleanupObjects.size() - FirstCleanup);
4225
4226 Expr *E = ExprWithCleanups::Create(Context, SubExpr, Cleanups);
4227 DiscardCleanupsInEvaluationContext();
4228
4229 return E;
4230}
4231
John McCall4765fa02010-12-06 08:20:24 +00004232Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004233 assert(SubStmt && "sub statement can't be null!");
4234
John McCallf85e1932011-06-15 23:02:42 +00004235 if (!ExprNeedsCleanups)
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004236 return SubStmt;
4237
4238 // FIXME: In order to attach the temporaries, wrap the statement into
4239 // a StmtExpr; currently this is only used for asm statements.
4240 // This is hacky, either create a new CXXStmtWithTemporaries statement or
4241 // a new AsmStmtWithTemporaries.
4242 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
4243 SourceLocation(),
4244 SourceLocation());
4245 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
4246 SourceLocation());
John McCall4765fa02010-12-06 08:20:24 +00004247 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004248}
4249
John McCall60d7b3a2010-08-24 06:29:42 +00004250ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004251Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallb3d87482010-08-24 05:47:05 +00004252 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00004253 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004254 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004255 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00004256 if (Result.isInvalid()) return ExprError();
4257 Base = Result.get();
Mike Stump1eb44332009-09-09 15:08:12 +00004258
John McCall3c3b7f92011-10-25 17:37:35 +00004259 Result = CheckPlaceholderExpr(Base);
4260 if (Result.isInvalid()) return ExprError();
4261 Base = Result.take();
4262
John McCall9ae2f072010-08-23 23:25:46 +00004263 QualType BaseType = Base->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00004264 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004265 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00004266 // If we have a pointer to a dependent type and are using the -> operator,
4267 // the object type is the type that the pointer points to. We might still
4268 // have enough information about that type to do something useful.
4269 if (OpKind == tok::arrow)
4270 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4271 BaseType = Ptr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004272
John McCallb3d87482010-08-24 05:47:05 +00004273 ObjectType = ParsedType::make(BaseType);
Douglas Gregord4dca082010-02-24 18:44:31 +00004274 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00004275 return Owned(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004276 }
Mike Stump1eb44332009-09-09 15:08:12 +00004277
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004278 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00004279 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004280 // returned, with the original second operand.
4281 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00004282 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00004283 llvm::SmallPtrSet<CanQualType,8> CTypes;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004284 SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00004285 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004286
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004287 while (BaseType->isRecordType()) {
John McCall9ae2f072010-08-23 23:25:46 +00004288 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
4289 if (Result.isInvalid())
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004290 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00004291 Base = Result.get();
4292 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonde699e52009-10-13 22:55:59 +00004293 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCall9ae2f072010-08-23 23:25:46 +00004294 BaseType = Base->getType();
John McCallc4e83212009-09-30 01:01:30 +00004295 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00004296 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00004297 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00004298 for (unsigned i = 0; i < Locations.size(); i++)
4299 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00004300 return ExprError();
4301 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004302 }
Mike Stump1eb44332009-09-09 15:08:12 +00004303
Douglas Gregor1d7049a2012-01-12 16:11:24 +00004304 if (BaseType->isPointerType() || BaseType->isObjCObjectPointerType())
Douglas Gregor31658df2009-11-20 19:58:21 +00004305 BaseType = BaseType->getPointeeType();
4306 }
Mike Stump1eb44332009-09-09 15:08:12 +00004307
Douglas Gregor1d7049a2012-01-12 16:11:24 +00004308 // Objective-C properties allow "." access on Objective-C pointer types,
4309 // so adjust the base type to the object type itself.
4310 if (BaseType->isObjCObjectPointerType())
4311 BaseType = BaseType->getPointeeType();
4312
4313 // C++ [basic.lookup.classref]p2:
4314 // [...] If the type of the object expression is of pointer to scalar
4315 // type, the unqualified-id is looked up in the context of the complete
4316 // postfix-expression.
4317 //
4318 // This also indicates that we could be parsing a pseudo-destructor-name.
4319 // Note that Objective-C class and object types can be pseudo-destructor
4320 // expressions or normal member (ivar or property) access expressions.
4321 if (BaseType->isObjCObjectOrInterfaceType()) {
4322 MayBePseudoDestructor = true;
4323 } else if (!BaseType->isRecordType()) {
John McCallb3d87482010-08-24 05:47:05 +00004324 ObjectType = ParsedType();
Douglas Gregord4dca082010-02-24 18:44:31 +00004325 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00004326 return Owned(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00004327 }
Mike Stump1eb44332009-09-09 15:08:12 +00004328
Douglas Gregor03c57052009-11-17 05:17:33 +00004329 // The object type must be complete (or dependent).
4330 if (!BaseType->isDependentType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004331 RequireCompleteType(OpLoc, BaseType,
Douglas Gregor03c57052009-11-17 05:17:33 +00004332 PDiag(diag::err_incomplete_member_access)))
4333 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004334
Douglas Gregorc68afe22009-09-03 21:38:09 +00004335 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004336 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00004337 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00004338 // type C (or of pointer to a class type C), the unqualified-id is looked
4339 // up in the scope of class C. [...]
John McCallb3d87482010-08-24 05:47:05 +00004340 ObjectType = ParsedType::make(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00004341 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004342}
4343
John McCall60d7b3a2010-08-24 06:29:42 +00004344ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCall9ae2f072010-08-23 23:25:46 +00004345 Expr *MemExpr) {
Douglas Gregor77549082010-02-24 21:29:12 +00004346 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCall9ae2f072010-08-23 23:25:46 +00004347 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
4348 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregor849b2432010-03-31 17:46:05 +00004349 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004350
Douglas Gregor77549082010-02-24 21:29:12 +00004351 return ActOnCallExpr(/*Scope*/ 0,
John McCall9ae2f072010-08-23 23:25:46 +00004352 MemExpr,
Douglas Gregor77549082010-02-24 21:29:12 +00004353 /*LPLoc*/ ExpectedLParenLoc,
John McCallf312b1e2010-08-26 23:41:50 +00004354 MultiExprArg(),
Douglas Gregor77549082010-02-24 21:29:12 +00004355 /*RPLoc*/ ExpectedLParenLoc);
4356}
Douglas Gregord4dca082010-02-24 18:44:31 +00004357
Eli Friedmane0dbedf2012-01-25 04:29:24 +00004358static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie91ec7892011-12-16 16:03:09 +00004359 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedmane0dbedf2012-01-25 04:29:24 +00004360 if (Base->hasPlaceholderType()) {
4361 ExprResult result = S.CheckPlaceholderExpr(Base);
4362 if (result.isInvalid()) return true;
4363 Base = result.take();
4364 }
4365 ObjectType = Base->getType();
4366
David Blaikie91ec7892011-12-16 16:03:09 +00004367 // C++ [expr.pseudo]p2:
4368 // The left-hand side of the dot operator shall be of scalar type. The
4369 // left-hand side of the arrow operator shall be of pointer to scalar type.
4370 // This scalar type is the object type.
Eli Friedmane0dbedf2012-01-25 04:29:24 +00004371 // Note that this is rather different from the normal handling for the
4372 // arrow operator.
David Blaikie91ec7892011-12-16 16:03:09 +00004373 if (OpKind == tok::arrow) {
4374 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4375 ObjectType = Ptr->getPointeeType();
4376 } else if (!Base->isTypeDependent()) {
4377 // The user wrote "p->" when she probably meant "p."; fix it.
4378 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4379 << ObjectType << true
4380 << FixItHint::CreateReplacement(OpLoc, ".");
4381 if (S.isSFINAEContext())
4382 return true;
4383
4384 OpKind = tok::period;
4385 }
4386 }
4387
4388 return false;
4389}
4390
John McCall60d7b3a2010-08-24 06:29:42 +00004391ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00004392 SourceLocation OpLoc,
4393 tok::TokenKind OpKind,
4394 const CXXScopeSpec &SS,
4395 TypeSourceInfo *ScopeTypeInfo,
4396 SourceLocation CCLoc,
4397 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004398 PseudoDestructorTypeStorage Destructed,
John McCall2d9f5fa2011-02-25 05:21:17 +00004399 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004400 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004401
Eli Friedman8c9fe202012-01-25 04:35:06 +00004402 QualType ObjectType;
David Blaikie91ec7892011-12-16 16:03:09 +00004403 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4404 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004405
Douglas Gregorb57fb492010-02-24 22:38:50 +00004406 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
Nico Weberdf1be862012-01-23 05:50:57 +00004407 if (getLangOptions().MicrosoftMode && ObjectType->isVoidType())
Nico Weber2d757ec2012-01-23 06:08:16 +00004408 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Nico Weberdf1be862012-01-23 05:50:57 +00004409 else
4410 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
4411 << ObjectType << Base->getSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00004412 return ExprError();
4413 }
4414
4415 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004416 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb57fb492010-02-24 22:38:50 +00004417 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004418 if (DestructedTypeInfo) {
4419 QualType DestructedType = DestructedTypeInfo->getType();
4420 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004421 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCallf85e1932011-06-15 23:02:42 +00004422 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
4423 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
4424 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
4425 << ObjectType << DestructedType << Base->getSourceRange()
4426 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004427
John McCallf85e1932011-06-15 23:02:42 +00004428 // Recover by setting the destructed type to the object type.
4429 DestructedType = ObjectType;
4430 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004431 DestructedTypeStart);
John McCallf85e1932011-06-15 23:02:42 +00004432 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4433 } else if (DestructedType.getObjCLifetime() !=
4434 ObjectType.getObjCLifetime()) {
4435
4436 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
4437 // Okay: just pretend that the user provided the correctly-qualified
4438 // type.
4439 } else {
4440 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
4441 << ObjectType << DestructedType << Base->getSourceRange()
4442 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
4443 }
4444
4445 // Recover by setting the destructed type to the object type.
4446 DestructedType = ObjectType;
4447 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
4448 DestructedTypeStart);
4449 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4450 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004451 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00004452 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004453
Douglas Gregorb57fb492010-02-24 22:38:50 +00004454 // C++ [expr.pseudo]p2:
4455 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
4456 // form
4457 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004458 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb57fb492010-02-24 22:38:50 +00004459 //
4460 // shall designate the same scalar type.
4461 if (ScopeTypeInfo) {
4462 QualType ScopeType = ScopeTypeInfo->getType();
4463 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00004464 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004465
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004466 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00004467 diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00004468 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004469 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004470
Douglas Gregorb57fb492010-02-24 22:38:50 +00004471 ScopeType = QualType();
4472 ScopeTypeInfo = 0;
4473 }
4474 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004475
John McCall9ae2f072010-08-23 23:25:46 +00004476 Expr *Result
4477 = new (Context) CXXPseudoDestructorExpr(Context, Base,
4478 OpKind == tok::arrow, OpLoc,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00004479 SS.getWithLocInContext(Context),
John McCall9ae2f072010-08-23 23:25:46 +00004480 ScopeTypeInfo,
4481 CCLoc,
4482 TildeLoc,
4483 Destructed);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004484
Douglas Gregorb57fb492010-02-24 22:38:50 +00004485 if (HasTrailingLParen)
John McCall9ae2f072010-08-23 23:25:46 +00004486 return Owned(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004487
John McCall9ae2f072010-08-23 23:25:46 +00004488 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor77549082010-02-24 21:29:12 +00004489}
4490
John McCall60d7b3a2010-08-24 06:29:42 +00004491ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00004492 SourceLocation OpLoc,
4493 tok::TokenKind OpKind,
4494 CXXScopeSpec &SS,
4495 UnqualifiedId &FirstTypeName,
4496 SourceLocation CCLoc,
4497 SourceLocation TildeLoc,
4498 UnqualifiedId &SecondTypeName,
4499 bool HasTrailingLParen) {
Douglas Gregor77549082010-02-24 21:29:12 +00004500 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4501 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4502 "Invalid first type name in pseudo-destructor");
4503 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4504 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4505 "Invalid second type name in pseudo-destructor");
4506
Eli Friedman8c9fe202012-01-25 04:35:06 +00004507 QualType ObjectType;
David Blaikie91ec7892011-12-16 16:03:09 +00004508 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4509 return ExprError();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004510
4511 // Compute the object type that we should use for name lookup purposes. Only
4512 // record types and dependent types matter.
John McCallb3d87482010-08-24 05:47:05 +00004513 ParsedType ObjectTypePtrForLookup;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004514 if (!SS.isSet()) {
John McCall2d9f5fa2011-02-25 05:21:17 +00004515 if (ObjectType->isRecordType())
4516 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallb3d87482010-08-24 05:47:05 +00004517 else if (ObjectType->isDependentType())
4518 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004519 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004520
4521 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb57fb492010-02-24 22:38:50 +00004522 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00004523 QualType DestructedType;
4524 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004525 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00004526 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004527 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00004528 SecondTypeName.StartLocation,
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +00004529 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004530 if (!T &&
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004531 ((SS.isSet() && !computeDeclContext(SS, false)) ||
4532 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004533 // The name of the type being destroyed is a dependent name, and we
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004534 // couldn't find anything useful in scope. Just store the identifier and
4535 // it's location, and we'll perform (qualified) name lookup again at
4536 // template instantiation time.
4537 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
4538 SecondTypeName.StartLocation);
4539 } else if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004540 Diag(SecondTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00004541 diag::err_pseudo_dtor_destructor_non_type)
4542 << SecondTypeName.Identifier << ObjectType;
4543 if (isSFINAEContext())
4544 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004545
Douglas Gregor77549082010-02-24 21:29:12 +00004546 // Recover by assuming we had the right type all along.
4547 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004548 } else
Douglas Gregor77549082010-02-24 21:29:12 +00004549 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004550 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00004551 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00004552 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004553 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4554 TemplateId->getTemplateArgs(),
4555 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00004556 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4557 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004558 TemplateId->TemplateNameLoc,
4559 TemplateId->LAngleLoc,
4560 TemplateArgsPtr,
4561 TemplateId->RAngleLoc);
4562 if (T.isInvalid() || !T.get()) {
4563 // Recover by assuming we had the right type all along.
4564 DestructedType = ObjectType;
4565 } else
4566 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004567 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004568
4569 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb57fb492010-02-24 22:38:50 +00004570 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004571 if (!DestructedType.isNull()) {
4572 if (!DestructedTypeInfo)
4573 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004574 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004575 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4576 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004577
Douglas Gregorb57fb492010-02-24 22:38:50 +00004578 // Convert the name of the scope type (the type prior to '::') into a type.
4579 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00004580 QualType ScopeType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004581 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor77549082010-02-24 21:29:12 +00004582 FirstTypeName.Identifier) {
4583 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004584 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00004585 FirstTypeName.StartLocation,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00004586 S, &SS, true, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00004587 if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004588 Diag(FirstTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00004589 diag::err_pseudo_dtor_destructor_non_type)
4590 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004591
Douglas Gregorb57fb492010-02-24 22:38:50 +00004592 if (isSFINAEContext())
4593 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004594
Douglas Gregorb57fb492010-02-24 22:38:50 +00004595 // Just drop this type. It's unnecessary anyway.
4596 ScopeType = QualType();
4597 } else
4598 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004599 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00004600 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00004601 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004602 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4603 TemplateId->getTemplateArgs(),
4604 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00004605 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4606 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004607 TemplateId->TemplateNameLoc,
4608 TemplateId->LAngleLoc,
4609 TemplateArgsPtr,
4610 TemplateId->RAngleLoc);
4611 if (T.isInvalid() || !T.get()) {
4612 // Recover by dropping this type.
4613 ScopeType = QualType();
4614 } else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004615 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004616 }
4617 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004618
Douglas Gregorb4a418f2010-02-24 23:02:30 +00004619 if (!ScopeType.isNull() && !ScopeTypeInfo)
4620 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
4621 FirstTypeName.StartLocation);
4622
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004623
John McCall9ae2f072010-08-23 23:25:46 +00004624 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00004625 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004626 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00004627}
4628
David Blaikie91ec7892011-12-16 16:03:09 +00004629ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4630 SourceLocation OpLoc,
4631 tok::TokenKind OpKind,
4632 SourceLocation TildeLoc,
4633 const DeclSpec& DS,
4634 bool HasTrailingLParen) {
Eli Friedman8c9fe202012-01-25 04:35:06 +00004635 QualType ObjectType;
David Blaikie91ec7892011-12-16 16:03:09 +00004636 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4637 return ExprError();
4638
4639 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
4640
4641 TypeLocBuilder TLB;
4642 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
4643 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
4644 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
4645 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
4646
4647 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
4648 0, SourceLocation(), TildeLoc,
4649 Destructed, HasTrailingLParen);
4650}
4651
John Wiegley429bb272011-04-08 18:41:53 +00004652ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004653 CXXMethodDecl *Method,
4654 bool HadMultipleCandidates) {
John Wiegley429bb272011-04-08 18:41:53 +00004655 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
4656 FoundDecl, Method);
4657 if (Exp.isInvalid())
Douglas Gregorf2ae5262011-01-20 00:18:04 +00004658 return true;
Eli Friedman772fffa2009-12-09 04:53:56 +00004659
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004660 MemberExpr *ME =
John Wiegley429bb272011-04-08 18:41:53 +00004661 new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
Abramo Bagnara960809e2011-11-16 22:46:05 +00004662 SourceLocation(), Context.BoundMemberTy,
John McCallf89e55a2010-11-18 06:31:45 +00004663 VK_RValue, OK_Ordinary);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004664 if (HadMultipleCandidates)
4665 ME->setHadMultipleCandidates(true);
4666
John McCallf89e55a2010-11-18 06:31:45 +00004667 QualType ResultType = Method->getResultType();
4668 ExprValueKind VK = Expr::getValueKindForType(ResultType);
4669 ResultType = ResultType.getNonLValueExprType(Context);
4670
John Wiegley429bb272011-04-08 18:41:53 +00004671 MarkDeclarationReferenced(Exp.get()->getLocStart(), Method);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004672 CXXMemberCallExpr *CE =
John McCallf89e55a2010-11-18 06:31:45 +00004673 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
John Wiegley429bb272011-04-08 18:41:53 +00004674 Exp.get()->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00004675 return CE;
4676}
4677
Sebastian Redl2e156222010-09-10 20:55:43 +00004678ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4679 SourceLocation RParen) {
Sebastian Redl2e156222010-09-10 20:55:43 +00004680 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
4681 Operand->CanThrow(Context),
4682 KeyLoc, RParen));
4683}
4684
4685ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
4686 Expr *Operand, SourceLocation RParen) {
4687 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl02bc21a2010-09-10 20:55:37 +00004688}
4689
John McCallf6a16482010-12-04 03:47:34 +00004690/// Perform the conversions required for an expression used in a
4691/// context that ignores the result.
John Wiegley429bb272011-04-08 18:41:53 +00004692ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall3c3b7f92011-10-25 17:37:35 +00004693 if (E->hasPlaceholderType()) {
4694 ExprResult result = CheckPlaceholderExpr(E);
4695 if (result.isInvalid()) return Owned(E);
4696 E = result.take();
4697 }
4698
John McCalla878cda2010-12-02 02:07:15 +00004699 // C99 6.3.2.1:
4700 // [Except in specific positions,] an lvalue that does not have
4701 // array type is converted to the value stored in the
4702 // designated object (and is no longer an lvalue).
John McCalle6d134b2011-06-27 21:24:11 +00004703 if (E->isRValue()) {
4704 // In C, function designators (i.e. expressions of function type)
4705 // are r-values, but we still want to do function-to-pointer decay
4706 // on them. This is both technically correct and convenient for
4707 // some clients.
4708 if (!getLangOptions().CPlusPlus && E->getType()->isFunctionType())
4709 return DefaultFunctionArrayConversion(E);
4710
4711 return Owned(E);
4712 }
John McCalla878cda2010-12-02 02:07:15 +00004713
John McCallf6a16482010-12-04 03:47:34 +00004714 // Otherwise, this rule does not apply in C++, at least not for the moment.
John Wiegley429bb272011-04-08 18:41:53 +00004715 if (getLangOptions().CPlusPlus) return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004716
4717 // GCC seems to also exclude expressions of incomplete enum type.
4718 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
4719 if (!T->getDecl()->isComplete()) {
4720 // FIXME: stupid workaround for a codegen bug!
John Wiegley429bb272011-04-08 18:41:53 +00004721 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
4722 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004723 }
4724 }
4725
John Wiegley429bb272011-04-08 18:41:53 +00004726 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
4727 if (Res.isInvalid())
4728 return Owned(E);
4729 E = Res.take();
4730
John McCall85515d62010-12-04 12:29:11 +00004731 if (!E->getType()->isVoidType())
4732 RequireCompleteType(E->getExprLoc(), E->getType(),
4733 diag::err_incomplete_type);
John Wiegley429bb272011-04-08 18:41:53 +00004734 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004735}
4736
John Wiegley429bb272011-04-08 18:41:53 +00004737ExprResult Sema::ActOnFinishFullExpr(Expr *FE) {
4738 ExprResult FullExpr = Owned(FE);
4739
4740 if (!FullExpr.get())
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00004741 return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00004742
John Wiegley429bb272011-04-08 18:41:53 +00004743 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregord0937222010-12-13 22:49:22 +00004744 return ExprError();
4745
Douglas Gregor5e3a8be2011-12-15 00:53:32 +00004746 // Top-level message sends default to 'id' when we're in a debugger.
4747 if (getLangOptions().DebuggerSupport &&
4748 FullExpr.get()->getType() == Context.UnknownAnyTy &&
4749 isa<ObjCMessageExpr>(FullExpr.get())) {
4750 FullExpr = forceUnknownAnyToType(FullExpr.take(), Context.getObjCIdType());
4751 if (FullExpr.isInvalid())
4752 return ExprError();
4753 }
4754
John McCallfb8721c2011-04-10 19:13:55 +00004755 FullExpr = CheckPlaceholderExpr(FullExpr.take());
4756 if (FullExpr.isInvalid())
4757 return ExprError();
Douglas Gregor353ee242011-03-07 02:05:23 +00004758
John Wiegley429bb272011-04-08 18:41:53 +00004759 FullExpr = IgnoredValueConversions(FullExpr.take());
4760 if (FullExpr.isInvalid())
4761 return ExprError();
4762
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004763 CheckImplicitConversions(FullExpr.get(), FullExpr.get()->getExprLoc());
John McCall4765fa02010-12-06 08:20:24 +00004764 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson165a0a02009-05-17 18:41:29 +00004765}
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004766
4767StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
4768 if (!FullStmt) return StmtError();
4769
John McCall4765fa02010-12-06 08:20:24 +00004770 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004771}
Francois Pichet1e862692011-05-06 20:48:22 +00004772
Douglas Gregorba0513d2011-10-25 01:33:02 +00004773Sema::IfExistsResult
4774Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
4775 CXXScopeSpec &SS,
4776 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet1e862692011-05-06 20:48:22 +00004777 DeclarationName TargetName = TargetNameInfo.getName();
4778 if (!TargetName)
Douglas Gregor3896fc52011-10-24 22:31:10 +00004779 return IER_DoesNotExist;
Douglas Gregorba0513d2011-10-25 01:33:02 +00004780
Douglas Gregor3896fc52011-10-24 22:31:10 +00004781 // If the name itself is dependent, then the result is dependent.
4782 if (TargetName.isDependentName())
4783 return IER_Dependent;
Douglas Gregorba0513d2011-10-25 01:33:02 +00004784
Francois Pichet1e862692011-05-06 20:48:22 +00004785 // Do the redeclaration lookup in the current scope.
4786 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
4787 Sema::NotForRedeclaration);
Douglas Gregor3896fc52011-10-24 22:31:10 +00004788 LookupParsedName(R, S, &SS);
Francois Pichet1e862692011-05-06 20:48:22 +00004789 R.suppressDiagnostics();
Douglas Gregor3896fc52011-10-24 22:31:10 +00004790
4791 switch (R.getResultKind()) {
4792 case LookupResult::Found:
4793 case LookupResult::FoundOverloaded:
4794 case LookupResult::FoundUnresolvedValue:
4795 case LookupResult::Ambiguous:
4796 return IER_Exists;
4797
4798 case LookupResult::NotFound:
4799 return IER_DoesNotExist;
4800
4801 case LookupResult::NotFoundInCurrentInstantiation:
4802 return IER_Dependent;
4803 }
David Blaikie7530c032012-01-17 06:56:22 +00004804
4805 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet1e862692011-05-06 20:48:22 +00004806}
Douglas Gregorba0513d2011-10-25 01:33:02 +00004807
Douglas Gregor65019ac2011-10-25 03:44:56 +00004808Sema::IfExistsResult
4809Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4810 bool IsIfExists, CXXScopeSpec &SS,
4811 UnqualifiedId &Name) {
Douglas Gregorba0513d2011-10-25 01:33:02 +00004812 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Douglas Gregor65019ac2011-10-25 03:44:56 +00004813
4814 // Check for unexpanded parameter packs.
4815 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
4816 collectUnexpandedParameterPacks(SS, Unexpanded);
4817 collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
4818 if (!Unexpanded.empty()) {
4819 DiagnoseUnexpandedParameterPacks(KeywordLoc,
4820 IsIfExists? UPPC_IfExists
4821 : UPPC_IfNotExists,
4822 Unexpanded);
4823 return IER_Error;
4824 }
4825
Douglas Gregorba0513d2011-10-25 01:33:02 +00004826 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
4827}
4828
Eli Friedmandc3b7232012-01-04 02:40:39 +00004829//===----------------------------------------------------------------------===//
4830// Lambdas.
4831//===----------------------------------------------------------------------===//
4832
Eli Friedmanec9ea722012-01-05 03:35:19 +00004833void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
4834 Declarator &ParamInfo,
4835 Scope *CurScope) {
4836 DeclContext *DC = CurContext;
Eli Friedman906a7e12012-01-06 03:05:34 +00004837 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
Eli Friedmanec9ea722012-01-05 03:35:19 +00004838 DC = DC->getParent();
Eli Friedmandc3b7232012-01-04 02:40:39 +00004839
Eli Friedmanec9ea722012-01-05 03:35:19 +00004840 // Start constructing the lambda class.
4841 CXXRecordDecl *Class = CXXRecordDecl::Create(Context, TTK_Class, DC,
4842 Intro.Range.getBegin(),
4843 /*IdLoc=*/SourceLocation(),
4844 /*Id=*/0);
4845 Class->startDefinition();
Eli Friedman72899c32012-01-07 04:59:52 +00004846 Class->setLambda(true);
Eli Friedmanec9ea722012-01-05 03:35:19 +00004847 CurContext->addDecl(Class);
Eli Friedmandc3b7232012-01-04 02:40:39 +00004848
Eli Friedmane81d7e92012-01-07 01:08:17 +00004849 QualType ThisCaptureType;
Eli Friedmanb69b42c2012-01-11 02:36:31 +00004850 llvm::DenseMap<VarDecl*, unsigned> CaptureMap;
4851 unsigned CXXThisCaptureIndex = 0;
Eli Friedman72899c32012-01-07 04:59:52 +00004852 llvm::SmallVector<LambdaScopeInfo::Capture, 4> Captures;
Eli Friedmane81d7e92012-01-07 01:08:17 +00004853 for (llvm::SmallVector<LambdaCapture, 4>::const_iterator
4854 C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E; ++C) {
4855 if (C->Kind == LCK_This) {
4856 if (!ThisCaptureType.isNull()) {
4857 Diag(C->Loc, diag::err_capture_more_than_once) << "'this'";
4858 continue;
4859 }
4860
4861 if (Intro.Default == LCD_ByCopy) {
4862 Diag(C->Loc, diag::err_this_capture_with_copy_default);
4863 continue;
4864 }
4865
4866 ThisCaptureType = getCurrentThisType();
Eli Friedmane81d7e92012-01-07 01:08:17 +00004867 if (ThisCaptureType.isNull()) {
4868 Diag(C->Loc, diag::err_invalid_this_use);
4869 continue;
4870 }
Eli Friedman72899c32012-01-07 04:59:52 +00004871 CheckCXXThisCapture(C->Loc);
4872
Eli Friedmanb69b42c2012-01-11 02:36:31 +00004873 // FIXME: Need getCurCapture().
4874 bool isNested = getCurBlock() || getCurLambda();
4875 CapturingScopeInfo::Capture Cap(CapturingScopeInfo::Capture::ThisCapture,
4876 isNested);
4877 Captures.push_back(Cap);
4878 CXXThisCaptureIndex = Captures.size();
Eli Friedmane81d7e92012-01-07 01:08:17 +00004879 continue;
4880 }
4881
4882 assert(C->Id && "missing identifier for capture");
4883
4884 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
4885 Diag(C->Loc, diag::err_reference_capture_with_reference_default);
4886 continue;
4887 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
4888 Diag(C->Loc, diag::err_copy_capture_with_copy_default);
4889 continue;
4890 }
4891
Eli Friedmane81d7e92012-01-07 01:08:17 +00004892 DeclarationNameInfo Name(C->Id, C->Loc);
4893 LookupResult R(*this, Name, LookupOrdinaryName);
4894 CXXScopeSpec ScopeSpec;
4895 LookupParsedName(R, CurScope, &ScopeSpec);
4896 if (R.isAmbiguous())
4897 continue;
Kaelyn Uhrain4798f8d2012-01-18 05:58:54 +00004898 if (R.empty()) {
4899 DeclFilterCCC<VarDecl> Validator;
4900 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
Eli Friedmane81d7e92012-01-07 01:08:17 +00004901 continue;
Kaelyn Uhrain4798f8d2012-01-18 05:58:54 +00004902 }
Eli Friedmane81d7e92012-01-07 01:08:17 +00004903
4904 VarDecl *Var = R.getAsSingle<VarDecl>();
4905 if (!Var) {
4906 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
4907 continue;
4908 }
4909
Eli Friedmanb69b42c2012-01-11 02:36:31 +00004910 if (CaptureMap.count(Var)) {
4911 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
4912 continue;
4913 }
4914
Eli Friedmane81d7e92012-01-07 01:08:17 +00004915 if (!Var->hasLocalStorage()) {
4916 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
4917 continue;
4918 }
4919
Eli Friedmanb69b42c2012-01-11 02:36:31 +00004920 // FIXME: This is completely wrong for nested captures and variables
4921 // with a non-trivial constructor.
4922 // FIXME: We should refuse to capture __block variables.
4923 Captures.push_back(LambdaScopeInfo::Capture(Var, C->Kind == LCK_ByRef,
4924 /*isNested*/false, 0));
4925 CaptureMap[Var] = Captures.size();
Eli Friedmane81d7e92012-01-07 01:08:17 +00004926 }
4927
Eli Friedmanec9ea722012-01-05 03:35:19 +00004928 // Build the call operator; we don't really have all the relevant information
4929 // at this point, but we need something to attach child declarations to.
Eli Friedman906a7e12012-01-06 03:05:34 +00004930 QualType MethodTy;
Eli Friedmanf88c4002012-01-04 04:41:38 +00004931 TypeSourceInfo *MethodTyInfo;
Eli Friedman906a7e12012-01-06 03:05:34 +00004932 if (ParamInfo.getNumTypeObjects() == 0) {
4933 FunctionProtoType::ExtProtoInfo EPI;
4934 EPI.TypeQuals |= DeclSpec::TQ_const;
4935 MethodTy = Context.getFunctionType(Context.DependentTy,
4936 /*Args=*/0, /*NumArgs=*/0, EPI);
4937 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
4938 } else {
4939 assert(ParamInfo.isFunctionDeclarator() &&
4940 "lambda-declarator is a function");
4941 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
4942 if (!FTI.hasMutableQualifier())
4943 FTI.TypeQuals |= DeclSpec::TQ_const;
4944 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
4945 // FIXME: Can these asserts actually fail?
4946 assert(MethodTyInfo && "no type from lambda-declarator");
4947 MethodTy = MethodTyInfo->getType();
4948 assert(!MethodTy.isNull() && "no type from lambda declarator");
4949 }
Eli Friedmanf88c4002012-01-04 04:41:38 +00004950
Eli Friedmanec9ea722012-01-05 03:35:19 +00004951 DeclarationName MethodName
4952 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
4953 CXXMethodDecl *Method
4954 = CXXMethodDecl::Create(Context,
4955 Class,
4956 ParamInfo.getSourceRange().getEnd(),
4957 DeclarationNameInfo(MethodName,
4958 /*NameLoc=*/SourceLocation()),
Eli Friedman906a7e12012-01-06 03:05:34 +00004959 MethodTy,
Eli Friedmanec9ea722012-01-05 03:35:19 +00004960 MethodTyInfo,
4961 /*isStatic=*/false,
4962 SC_None,
4963 /*isInline=*/true,
4964 /*isConstExpr=*/false,
4965 ParamInfo.getSourceRange().getEnd());
4966 Method->setAccess(AS_public);
4967 Class->addDecl(Method);
4968 Method->setLexicalDeclContext(DC); // FIXME: Is this really correct?
4969
Eli Friedmanec9ea722012-01-05 03:35:19 +00004970 ProcessDeclAttributes(CurScope, Method, ParamInfo);
4971
Eli Friedmanec9ea722012-01-05 03:35:19 +00004972 // Enter a new evaluation context to insulate the block from any
4973 // cleanups from the enclosing full-expression.
4974 PushExpressionEvaluationContext(PotentiallyEvaluated);
4975
4976 PushDeclContext(CurScope, Method);
Eli Friedman906a7e12012-01-06 03:05:34 +00004977
Eli Friedman906a7e12012-01-06 03:05:34 +00004978 // Set the parameters on the decl, if specified.
4979 if (isa<FunctionProtoTypeLoc>(MethodTyInfo->getTypeLoc())) {
4980 FunctionProtoTypeLoc Proto =
4981 cast<FunctionProtoTypeLoc>(MethodTyInfo->getTypeLoc());
4982 Method->setParams(Proto.getParams());
4983 CheckParmsForFunctionDef(Method->param_begin(),
4984 Method->param_end(),
4985 /*CheckParameterNames=*/false);
4986
4987 // Introduce our parameters into the function scope
4988 for (unsigned p = 0, NumParams = Method->getNumParams(); p < NumParams; ++p) {
4989 ParmVarDecl *Param = Method->getParamDecl(p);
4990 Param->setOwningFunction(Method);
4991
4992 // If this has an identifier, add it to the scope stack.
4993 if (Param->getIdentifier()) {
4994 CheckShadow(CurScope, Param);
4995
4996 PushOnScopeChains(Param, CurScope);
4997 }
4998 }
4999 }
5000
Eli Friedman72899c32012-01-07 04:59:52 +00005001 // Introduce the lambda scope.
5002 PushLambdaScope(Class);
5003
5004 LambdaScopeInfo *LSI = getCurLambda();
Eli Friedmanb69b42c2012-01-11 02:36:31 +00005005 LSI->CXXThisCaptureIndex = CXXThisCaptureIndex;
5006 std::swap(LSI->CaptureMap, CaptureMap);
Eli Friedman72899c32012-01-07 04:59:52 +00005007 std::swap(LSI->Captures, Captures);
Eli Friedmanb69b42c2012-01-11 02:36:31 +00005008 LSI->NumExplicitCaptures = Captures.size();
5009 if (Intro.Default == LCD_ByCopy)
5010 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
5011 else if (Intro.Default == LCD_ByRef)
5012 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
Eli Friedman72899c32012-01-07 04:59:52 +00005013
Eli Friedman906a7e12012-01-06 03:05:34 +00005014 const FunctionType *Fn = MethodTy->getAs<FunctionType>();
5015 QualType RetTy = Fn->getResultType();
5016 if (RetTy != Context.DependentTy) {
5017 LSI->ReturnType = RetTy;
Eli Friedmanb69b42c2012-01-11 02:36:31 +00005018 } else {
Eli Friedman906a7e12012-01-06 03:05:34 +00005019 LSI->HasImplicitReturnType = true;
5020 }
5021
5022 // FIXME: Check return type is complete, !isObjCObjectType
5023
Eli Friedmandc3b7232012-01-04 02:40:39 +00005024}
5025
5026void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope) {
5027 // Leave the expression-evaluation context.
5028 DiscardCleanupsInEvaluationContext();
5029 PopExpressionEvaluationContext();
5030
5031 // Leave the context of the lambda.
Eli Friedmanec9ea722012-01-05 03:35:19 +00005032 PopDeclContext();
5033 PopFunctionScopeInfo();
Eli Friedmandc3b7232012-01-04 02:40:39 +00005034}
5035
5036ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc,
5037 Stmt *Body, Scope *CurScope) {
5038 // FIXME: Implement
5039 Diag(StartLoc, diag::err_lambda_unsupported);
5040 ActOnLambdaError(StartLoc, CurScope);
5041 return ExprError();
5042}