blob: 7d345073d792c8446d915a4058423a7dd7413e74 [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"
Sebastian Redlbd45d252012-02-16 12:59:47 +000033#include "llvm/ADT/APInt.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000034#include "llvm/ADT/STLExtras.h"
Chandler Carruth73e0a912011-05-01 07:23:17 +000035#include "llvm/Support/ErrorHandling.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000036using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000037using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000038
John McCallb3d87482010-08-24 05:47:05 +000039ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000040 IdentifierInfo &II,
John McCallb3d87482010-08-24 05:47:05 +000041 SourceLocation NameLoc,
42 Scope *S, CXXScopeSpec &SS,
43 ParsedType ObjectTypePtr,
44 bool EnteringContext) {
Douglas Gregor124b8782010-02-16 19:09:40 +000045 // Determine where to perform name lookup.
46
47 // FIXME: This area of the standard is very messy, and the current
48 // wording is rather unclear about which scopes we search for the
49 // destructor name; see core issues 399 and 555. Issue 399 in
50 // particular shows where the current description of destructor name
51 // lookup is completely out of line with existing practice, e.g.,
52 // this appears to be ill-formed:
53 //
54 // namespace N {
55 // template <typename T> struct S {
56 // ~S();
57 // };
58 // }
59 //
60 // void f(N::S<int>* s) {
61 // s->N::S<int>::~S();
62 // }
63 //
Douglas Gregor93649fd2010-02-23 00:15:22 +000064 // See also PR6358 and PR6359.
Sebastian Redlc0fee502010-07-07 23:17:38 +000065 // For this reason, we're currently only doing the C++03 version of this
66 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregor124b8782010-02-16 19:09:40 +000067 QualType SearchType;
68 DeclContext *LookupCtx = 0;
69 bool isDependent = false;
70 bool LookInScope = false;
71
72 // If we have an object type, it's because we are in a
73 // pseudo-destructor-expression or a member access expression, and
74 // we know what type we're looking for.
75 if (ObjectTypePtr)
76 SearchType = GetTypeFromParser(ObjectTypePtr);
77
78 if (SS.isSet()) {
Douglas Gregor93649fd2010-02-23 00:15:22 +000079 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000080
Douglas Gregor93649fd2010-02-23 00:15:22 +000081 bool AlreadySearched = false;
82 bool LookAtPrefix = true;
Sebastian Redlc0fee502010-07-07 23:17:38 +000083 // C++ [basic.lookup.qual]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000084 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redlc0fee502010-07-07 23:17:38 +000085 // the type-names are looked up as types in the scope designated by the
86 // nested-name-specifier. In a qualified-id of the form:
NAKAMURA Takumi00995302011-01-27 07:09:49 +000087 //
88 // ::[opt] nested-name-specifier ~ class-name
Sebastian Redlc0fee502010-07-07 23:17:38 +000089 //
90 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth5e895a82010-02-21 10:19:54 +000091 // a qualified-id of the form:
Douglas Gregor124b8782010-02-16 19:09:40 +000092 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +000093 // ::opt nested-name-specifier class-name :: ~ class-name
Douglas Gregor124b8782010-02-16 19:09:40 +000094 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000095 // the class-names are looked up as types in the scope designated by
Sebastian Redlc0fee502010-07-07 23:17:38 +000096 // the nested-name-specifier.
Douglas Gregor124b8782010-02-16 19:09:40 +000097 //
Sebastian Redlc0fee502010-07-07 23:17:38 +000098 // Here, we check the first case (completely) and determine whether the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000099 // code below is permitted to look at the prefix of the
Sebastian Redlc0fee502010-07-07 23:17:38 +0000100 // nested-name-specifier.
101 DeclContext *DC = computeDeclContext(SS, EnteringContext);
102 if (DC && DC->isFileContext()) {
103 AlreadySearched = true;
104 LookupCtx = DC;
105 isDependent = false;
106 } else if (DC && isa<CXXRecordDecl>(DC))
107 LookAtPrefix = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000108
Sebastian Redlc0fee502010-07-07 23:17:38 +0000109 // The second case from the C++03 rules quoted further above.
Douglas Gregor93649fd2010-02-23 00:15:22 +0000110 NestedNameSpecifier *Prefix = 0;
111 if (AlreadySearched) {
112 // Nothing left to do.
113 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
114 CXXScopeSpec PrefixSS;
Douglas Gregor7e384942011-02-25 16:07:42 +0000115 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor93649fd2010-02-23 00:15:22 +0000116 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
117 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000118 } else if (ObjectTypePtr) {
Douglas Gregor124b8782010-02-16 19:09:40 +0000119 LookupCtx = computeDeclContext(SearchType);
120 isDependent = SearchType->isDependentType();
121 } else {
122 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000123 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregor124b8782010-02-16 19:09:40 +0000124 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000125
Douglas Gregoredc90502010-02-25 04:46:04 +0000126 LookInScope = false;
Douglas Gregor124b8782010-02-16 19:09:40 +0000127 } else if (ObjectTypePtr) {
128 // C++ [basic.lookup.classref]p3:
129 // If the unqualified-id is ~type-name, the type-name is looked up
130 // in the context of the entire postfix-expression. If the type T
131 // of the object expression is of a class type C, the type-name is
132 // also looked up in the scope of class C. At least one of the
133 // lookups shall find a name that refers to (possibly
134 // cv-qualified) T.
135 LookupCtx = computeDeclContext(SearchType);
136 isDependent = SearchType->isDependentType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000137 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregor124b8782010-02-16 19:09:40 +0000138 "Caller should have completed object type");
139
140 LookInScope = true;
141 } else {
142 // Perform lookup into the current scope (only).
143 LookInScope = true;
144 }
145
Douglas Gregor7ec18732011-03-04 22:32:08 +0000146 TypeDecl *NonMatchingTypeDecl = 0;
Douglas Gregor124b8782010-02-16 19:09:40 +0000147 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
148 for (unsigned Step = 0; Step != 2; ++Step) {
149 // Look for the name first in the computed lookup context (if we
Douglas Gregor7ec18732011-03-04 22:32:08 +0000150 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregor124b8782010-02-16 19:09:40 +0000151 // we're allowed to look there).
152 Found.clear();
153 if (Step == 0 && LookupCtx)
154 LookupQualifiedName(Found, LookupCtx);
Douglas Gregora2e7dd22010-02-25 01:56:36 +0000155 else if (Step == 1 && LookInScope && S)
Douglas Gregor124b8782010-02-16 19:09:40 +0000156 LookupName(Found, S);
157 else
158 continue;
159
160 // FIXME: Should we be suppressing ambiguities here?
161 if (Found.isAmbiguous())
John McCallb3d87482010-08-24 05:47:05 +0000162 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000163
164 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
165 QualType T = Context.getTypeDeclType(Type);
Douglas Gregor124b8782010-02-16 19:09:40 +0000166
167 if (SearchType.isNull() || SearchType->isDependentType() ||
168 Context.hasSameUnqualifiedType(T, SearchType)) {
169 // We found our type!
170
John McCallb3d87482010-08-24 05:47:05 +0000171 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000172 }
John Wiegley36784e72011-03-08 08:13:22 +0000173
Douglas Gregor7ec18732011-03-04 22:32:08 +0000174 if (!SearchType.isNull())
175 NonMatchingTypeDecl = Type;
Douglas Gregor124b8782010-02-16 19:09:40 +0000176 }
177
178 // If the name that we found is a class template name, and it is
179 // the same name as the template name in the last part of the
180 // nested-name-specifier (if present) or the object type, then
181 // this is the destructor for that class.
182 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000183 // issue 399, for which there isn't even an obvious direction.
Douglas Gregor124b8782010-02-16 19:09:40 +0000184 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
185 QualType MemberOfType;
186 if (SS.isSet()) {
187 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
188 // Figure out the type of the context, if it has one.
John McCall3cb0ebd2010-03-10 03:28:59 +0000189 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
190 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregor124b8782010-02-16 19:09:40 +0000191 }
192 }
193 if (MemberOfType.isNull())
194 MemberOfType = SearchType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000195
Douglas Gregor124b8782010-02-16 19:09:40 +0000196 if (MemberOfType.isNull())
197 continue;
198
199 // We're referring into a class template specialization. If the
200 // class template we found is the same as the template being
201 // specialized, we found what we are looking for.
202 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
203 if (ClassTemplateSpecializationDecl *Spec
204 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
205 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
206 Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000207 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000208 }
209
210 continue;
211 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000212
Douglas Gregor124b8782010-02-16 19:09:40 +0000213 // We're referring to an unresolved class template
214 // specialization. Determine whether we class template we found
215 // is the same as the template being specialized or, if we don't
216 // know which template is being specialized, that it at least
217 // has the same name.
218 if (const TemplateSpecializationType *SpecType
219 = MemberOfType->getAs<TemplateSpecializationType>()) {
220 TemplateName SpecName = SpecType->getTemplateName();
221
222 // The class template we found is the same template being
223 // specialized.
224 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
225 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000226 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000227
228 continue;
229 }
230
231 // The class template we found has the same name as the
232 // (dependent) template name being specialized.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000233 if (DependentTemplateName *DepTemplate
Douglas Gregor124b8782010-02-16 19:09:40 +0000234 = SpecName.getAsDependentTemplateName()) {
235 if (DepTemplate->isIdentifier() &&
236 DepTemplate->getIdentifier() == Template->getIdentifier())
John McCallb3d87482010-08-24 05:47:05 +0000237 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000238
239 continue;
240 }
241 }
242 }
243 }
244
245 if (isDependent) {
246 // We didn't find our type, but that's okay: it's dependent
247 // anyway.
Douglas Gregore29425b2011-02-28 22:42:13 +0000248
249 // FIXME: What if we have no nested-name-specifier?
250 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
251 SS.getWithLocInContext(Context),
252 II, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000253 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000254 }
255
Douglas Gregor7ec18732011-03-04 22:32:08 +0000256 if (NonMatchingTypeDecl) {
257 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
258 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
259 << T << SearchType;
260 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
261 << T;
262 } else if (ObjectTypePtr)
263 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000264 << &II;
Douglas Gregor124b8782010-02-16 19:09:40 +0000265 else
266 Diag(NameLoc, diag::err_destructor_class_name);
267
John McCallb3d87482010-08-24 05:47:05 +0000268 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000269}
270
David Blaikie53a75c02011-12-08 16:13:53 +0000271ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) {
David Blaikie4db8c442011-12-12 04:13:55 +0000272 if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType)
David Blaikie53a75c02011-12-08 16:13:53 +0000273 return ParsedType();
274 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype
275 && "only get destructor types from declspecs");
276 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
277 QualType SearchType = GetTypeFromParser(ObjectType);
278 if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(SearchType, T)) {
279 return ParsedType::make(T);
280 }
281
282 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
283 << T << SearchType;
284 return ParsedType();
285}
286
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000287/// \brief Build a C++ typeid expression with a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000288ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000289 SourceLocation TypeidLoc,
290 TypeSourceInfo *Operand,
291 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000292 // C++ [expr.typeid]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000293 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000294 // that is the operand of typeid are always ignored.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000295 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000296 // type, the class shall be completely-defined.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000297 Qualifiers Quals;
298 QualType T
299 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
300 Quals);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000301 if (T->getAs<RecordType>() &&
302 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
303 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000304
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000305 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
306 Operand,
307 SourceRange(TypeidLoc, RParenLoc)));
308}
309
310/// \brief Build a C++ typeid expression with an expression operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000311ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000312 SourceLocation TypeidLoc,
313 Expr *E,
314 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000315 if (E && !E->isTypeDependent()) {
John McCall6dbba4f2011-10-11 23:14:30 +0000316 if (E->getType()->isPlaceholderType()) {
317 ExprResult result = CheckPlaceholderExpr(E);
318 if (result.isInvalid()) return ExprError();
319 E = result.take();
320 }
321
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000322 QualType T = E->getType();
323 if (const RecordType *RecordT = T->getAs<RecordType>()) {
324 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
325 // C++ [expr.typeid]p3:
326 // [...] If the type of the expression is a class type, the class
327 // shall be completely-defined.
328 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
329 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000330
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000331 // C++ [expr.typeid]p3:
Sebastian Redl906082e2010-07-20 04:20:21 +0000332 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000333 // polymorphic class type [...] [the] expression is an unevaluated
334 // operand. [...]
Sebastian Redl906082e2010-07-20 04:20:21 +0000335 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
Eli Friedmanef331b72012-01-20 01:26:23 +0000336 // The subexpression is potentially evaluated; switch the context
337 // and recheck the subexpression.
338 ExprResult Result = TranformToPotentiallyEvaluated(E);
339 if (Result.isInvalid()) return ExprError();
340 E = Result.take();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000341
342 // We require a vtable to query the type at run time.
343 MarkVTableUsed(TypeidLoc, RecordD);
344 }
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000345 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000346
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000347 // C++ [expr.typeid]p4:
348 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000349 // cv-qualified type, the result of the typeid expression refers to a
350 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000351 // type.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000352 Qualifiers Quals;
353 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
354 if (!Context.hasSameType(T, UnqualT)) {
355 T = UnqualT;
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +0000356 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).take();
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000357 }
358 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000359
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000360 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCall9ae2f072010-08-23 23:25:46 +0000361 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000362 SourceRange(TypeidLoc, RParenLoc)));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000363}
364
365/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCall60d7b3a2010-08-24 06:29:42 +0000366ExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000367Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
368 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000369 // Find the std::type_info type.
Sebastian Redlce0682f2011-03-31 19:29:24 +0000370 if (!getStdNamespace())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000371 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000372
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000373 if (!CXXTypeInfoDecl) {
374 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
375 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
376 LookupQualifiedName(R, getStdNamespace());
377 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
378 if (!CXXTypeInfoDecl)
379 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
380 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000381
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000382 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000383
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000384 if (isType) {
385 // The operand is a type; handle it as such.
386 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +0000387 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
388 &TInfo);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000389 if (T.isNull())
390 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000391
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000392 if (!TInfo)
393 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000394
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000395 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000396 }
Mike Stump1eb44332009-09-09 15:08:12 +0000397
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000398 // The operand is an expression.
John McCall9ae2f072010-08-23 23:25:46 +0000399 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000400}
401
Francois Pichet6915c522010-12-27 01:32:00 +0000402/// Retrieve the UuidAttr associated with QT.
403static UuidAttr *GetUuidAttrOfType(QualType QT) {
404 // Optionally remove one level of pointer, reference or array indirection.
John McCallf4c73712011-01-19 06:33:43 +0000405 const Type *Ty = QT.getTypePtr();;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000406 if (QT->isPointerType() || QT->isReferenceType())
407 Ty = QT->getPointeeType().getTypePtr();
408 else if (QT->isArrayType())
409 Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
410
Francois Pichet8db75a22011-05-08 10:02:20 +0000411 // Loop all record redeclaration looking for an uuid attribute.
Francois Pichet6915c522010-12-27 01:32:00 +0000412 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Francois Pichet8db75a22011-05-08 10:02:20 +0000413 for (CXXRecordDecl::redecl_iterator I = RD->redecls_begin(),
414 E = RD->redecls_end(); I != E; ++I) {
415 if (UuidAttr *Uuid = I->getAttr<UuidAttr>())
Francois Pichet6915c522010-12-27 01:32:00 +0000416 return Uuid;
Francois Pichet6915c522010-12-27 01:32:00 +0000417 }
Francois Pichet8db75a22011-05-08 10:02:20 +0000418
Francois Pichet6915c522010-12-27 01:32:00 +0000419 return 0;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000420}
421
Francois Pichet01b7c302010-09-08 12:20:18 +0000422/// \brief Build a Microsoft __uuidof expression with a type operand.
423ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
424 SourceLocation TypeidLoc,
425 TypeSourceInfo *Operand,
426 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000427 if (!Operand->getType()->isDependentType()) {
428 if (!GetUuidAttrOfType(Operand->getType()))
429 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
430 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000431
Francois Pichet01b7c302010-09-08 12:20:18 +0000432 // FIXME: add __uuidof semantic analysis for type operand.
433 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
434 Operand,
435 SourceRange(TypeidLoc, RParenLoc)));
436}
437
438/// \brief Build a Microsoft __uuidof expression with an expression operand.
439ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
440 SourceLocation TypeidLoc,
441 Expr *E,
442 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000443 if (!E->getType()->isDependentType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000444 if (!GetUuidAttrOfType(E->getType()) &&
Francois Pichet6915c522010-12-27 01:32:00 +0000445 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
446 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
447 }
448 // FIXME: add __uuidof semantic analysis for type operand.
Francois Pichet01b7c302010-09-08 12:20:18 +0000449 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
450 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000451 SourceRange(TypeidLoc, RParenLoc)));
Francois Pichet01b7c302010-09-08 12:20:18 +0000452}
453
454/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
455ExprResult
456Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
457 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000458 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet01b7c302010-09-08 12:20:18 +0000459 if (!MSVCGuidDecl) {
460 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
461 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
462 LookupQualifiedName(R, Context.getTranslationUnitDecl());
463 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
464 if (!MSVCGuidDecl)
465 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000466 }
467
Francois Pichet01b7c302010-09-08 12:20:18 +0000468 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000469
Francois Pichet01b7c302010-09-08 12:20:18 +0000470 if (isType) {
471 // The operand is a type; handle it as such.
472 TypeSourceInfo *TInfo = 0;
473 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
474 &TInfo);
475 if (T.isNull())
476 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000477
Francois Pichet01b7c302010-09-08 12:20:18 +0000478 if (!TInfo)
479 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
480
481 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
482 }
483
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000484 // The operand is an expression.
Francois Pichet01b7c302010-09-08 12:20:18 +0000485 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
486}
487
Steve Naroff1b273c42007-09-16 14:56:35 +0000488/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCall60d7b3a2010-08-24 06:29:42 +0000489ExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000490Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000491 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000492 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000493 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
494 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000495}
Chris Lattner50dd2892008-02-26 00:51:44 +0000496
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000497/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCall60d7b3a2010-08-24 06:29:42 +0000498ExprResult
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000499Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
500 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
501}
502
Chris Lattner50dd2892008-02-26 00:51:44 +0000503/// ActOnCXXThrow - Parse throw expressions.
John McCall60d7b3a2010-08-24 06:29:42 +0000504ExprResult
Douglas Gregorbca01b42011-07-06 22:04:06 +0000505Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
506 bool IsThrownVarInScope = false;
507 if (Ex) {
508 // C++0x [class.copymove]p31:
509 // When certain criteria are met, an implementation is allowed to omit the
510 // copy/move construction of a class object [...]
511 //
512 // - in a throw-expression, when the operand is the name of a
513 // non-volatile automatic object (other than a function or catch-
514 // clause parameter) whose scope does not extend beyond the end of the
515 // innermost enclosing try-block (if there is one), the copy/move
516 // operation from the operand to the exception object (15.1) can be
517 // omitted by constructing the automatic object directly into the
518 // exception object
519 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
520 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
521 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
522 for( ; S; S = S->getParent()) {
523 if (S->isDeclScope(Var)) {
524 IsThrownVarInScope = true;
525 break;
526 }
527
528 if (S->getFlags() &
529 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
530 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
531 Scope::TryScope))
532 break;
533 }
534 }
535 }
536 }
537
538 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
539}
540
541ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
542 bool IsThrownVarInScope) {
Anders Carlsson729b8532011-02-23 03:46:46 +0000543 // Don't report an error if 'throw' is used in system headers.
David Blaikie4e4d0842012-03-11 07:00:24 +0000544 if (!getLangOpts().CXXExceptions &&
Anders Carlsson729b8532011-02-23 03:46:46 +0000545 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb1fba312011-02-19 21:53:09 +0000546 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Douglas Gregorbca01b42011-07-06 22:04:06 +0000547
John Wiegley429bb272011-04-08 18:41:53 +0000548 if (Ex && !Ex->isTypeDependent()) {
Douglas Gregorbca01b42011-07-06 22:04:06 +0000549 ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex, IsThrownVarInScope);
John Wiegley429bb272011-04-08 18:41:53 +0000550 if (ExRes.isInvalid())
551 return ExprError();
552 Ex = ExRes.take();
553 }
Douglas Gregorbca01b42011-07-06 22:04:06 +0000554
555 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc,
556 IsThrownVarInScope));
Sebastian Redl972041f2009-04-27 20:27:31 +0000557}
558
559/// CheckCXXThrowOperand - Validate the operand of a throw.
Douglas Gregorbca01b42011-07-06 22:04:06 +0000560ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
561 bool IsThrownVarInScope) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000562 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000563 // A throw-expression initializes a temporary object, called the exception
564 // object, the type of which is determined by removing any top-level
565 // cv-qualifiers from the static type of the operand of throw and adjusting
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000566 // the type from "array of T" or "function returning T" to "pointer to T"
Douglas Gregor154fe982009-12-23 22:04:40 +0000567 // or "pointer to function returning T", [...]
568 if (E->getType().hasQualifiers())
John Wiegley429bb272011-04-08 18:41:53 +0000569 E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +0000570 E->getValueKind()).take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000571
John Wiegley429bb272011-04-08 18:41:53 +0000572 ExprResult Res = DefaultFunctionArrayConversion(E);
573 if (Res.isInvalid())
574 return ExprError();
575 E = Res.take();
Sebastian Redl972041f2009-04-27 20:27:31 +0000576
577 // If the type of the exception would be an incomplete type or a pointer
578 // to an incomplete type other than (cv) void the program is ill-formed.
579 QualType Ty = E->getType();
John McCallac418162010-04-22 01:10:34 +0000580 bool isPointer = false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000581 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000582 Ty = Ptr->getPointeeType();
John McCallac418162010-04-22 01:10:34 +0000583 isPointer = true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000584 }
585 if (!isPointer || !Ty->isVoidType()) {
586 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000587 PDiag(isPointer ? diag::err_throw_incomplete_ptr
588 : diag::err_throw_incomplete)
589 << E->getSourceRange()))
John Wiegley429bb272011-04-08 18:41:53 +0000590 return ExprError();
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000591
Douglas Gregorbf422f92010-04-15 18:05:39 +0000592 if (RequireNonAbstractType(ThrowLoc, E->getType(),
593 PDiag(diag::err_throw_abstract_type)
594 << E->getSourceRange()))
John Wiegley429bb272011-04-08 18:41:53 +0000595 return ExprError();
Sebastian Redl972041f2009-04-27 20:27:31 +0000596 }
597
John McCallac418162010-04-22 01:10:34 +0000598 // Initialize the exception result. This implicitly weeds out
599 // abstract types or types with inaccessible copy constructors.
Douglas Gregorbca01b42011-07-06 22:04:06 +0000600
601 // C++0x [class.copymove]p31:
602 // When certain criteria are met, an implementation is allowed to omit the
603 // copy/move construction of a class object [...]
604 //
605 // - in a throw-expression, when the operand is the name of a
606 // non-volatile automatic object (other than a function or catch-clause
607 // parameter) whose scope does not extend beyond the end of the
608 // innermost enclosing try-block (if there is one), the copy/move
609 // operation from the operand to the exception object (15.1) can be
610 // omitted by constructing the automatic object directly into the
611 // exception object
612 const VarDecl *NRVOVariable = 0;
613 if (IsThrownVarInScope)
614 NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
615
John McCallac418162010-04-22 01:10:34 +0000616 InitializedEntity Entity =
Douglas Gregor72dfa272011-01-21 22:46:35 +0000617 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
Douglas Gregorbca01b42011-07-06 22:04:06 +0000618 /*NRVO=*/NRVOVariable != 0);
John Wiegley429bb272011-04-08 18:41:53 +0000619 Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
Douglas Gregorbca01b42011-07-06 22:04:06 +0000620 QualType(), E,
621 IsThrownVarInScope);
John McCallac418162010-04-22 01:10:34 +0000622 if (Res.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000623 return ExprError();
624 E = Res.take();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000625
Eli Friedman5ed9b932010-06-03 20:39:03 +0000626 // If the exception has class type, we need additional handling.
627 const RecordType *RecordTy = Ty->getAs<RecordType>();
628 if (!RecordTy)
John Wiegley429bb272011-04-08 18:41:53 +0000629 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000630 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
631
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000632 // If we are throwing a polymorphic class type or pointer thereof,
633 // exception handling will make use of the vtable.
Eli Friedman5ed9b932010-06-03 20:39:03 +0000634 MarkVTableUsed(ThrowLoc, RD);
635
Eli Friedman98efb9f2010-10-12 20:32:36 +0000636 // If a pointer is thrown, the referenced object will not be destroyed.
637 if (isPointer)
John Wiegley429bb272011-04-08 18:41:53 +0000638 return Owned(E);
Eli Friedman98efb9f2010-10-12 20:32:36 +0000639
Richard Smith213d70b2012-02-18 04:13:32 +0000640 // If the class has a destructor, we must be able to call it.
641 if (RD->hasIrrelevantDestructor())
John Wiegley429bb272011-04-08 18:41:53 +0000642 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000643
Sebastian Redl28357452012-03-05 19:35:43 +0000644 CXXDestructorDecl *Destructor = 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
Eli Friedman5f2987c2012-02-02 03:46:19 +0000648 MarkFunctionReferenced(E->getExprLoc(), Destructor);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000649 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregored8abf12010-07-08 06:14:04 +0000650 PDiag(diag::err_access_dtor_exception) << Ty);
Richard Smith213d70b2012-02-18 04:13:32 +0000651 DiagnoseUseOfDecl(Destructor, E->getExprLoc());
John Wiegley429bb272011-04-08 18:41:53 +0000652 return Owned(E);
Chris Lattner50dd2892008-02-26 00:51:44 +0000653}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000654
Eli Friedman72899c32012-01-07 04:59:52 +0000655QualType Sema::getCurrentThisType() {
656 DeclContext *DC = getFunctionLevelDeclContext();
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000657 QualType ThisTy = CXXThisTypeOverride;
Richard Smith7a614d82011-06-11 17:19:42 +0000658 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
659 if (method && method->isInstance())
660 ThisTy = method->getThisType(Context);
Richard Smith7a614d82011-06-11 17:19:42 +0000661 }
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000662
Richard Smith7a614d82011-06-11 17:19:42 +0000663 return ThisTy;
John McCall5808ce42011-02-03 08:15:49 +0000664}
665
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000666Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
667 Decl *ContextDecl,
668 unsigned CXXThisTypeQuals,
669 bool Enabled)
670 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
671{
672 if (!Enabled || !ContextDecl)
673 return;
674
675 CXXRecordDecl *Record = 0;
676 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
677 Record = Template->getTemplatedDecl();
678 else
679 Record = cast<CXXRecordDecl>(ContextDecl);
680
681 S.CXXThisTypeOverride
682 = S.Context.getPointerType(
683 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
684
685 this->Enabled = true;
686}
687
688
689Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
690 if (Enabled) {
691 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
692 }
693}
694
Douglas Gregora1f21142012-02-01 17:04:21 +0000695void Sema::CheckCXXThisCapture(SourceLocation Loc, bool Explicit) {
Richard Smith86e6fdc2012-04-26 01:51:03 +0000696 if (getLangOpts().CPlusPlus0x &&
697 !dyn_cast_or_null<CXXMethodDecl>(getFunctionLevelDeclContext()))
698 Diag(Loc, diag::warn_cxx98_compat_this_outside_method);
699
Eli Friedman72899c32012-01-07 04:59:52 +0000700 // We don't need to capture this in an unevaluated context.
Douglas Gregora1f21142012-02-01 17:04:21 +0000701 if (ExprEvalContexts.back().Context == Unevaluated && !Explicit)
Eli Friedman72899c32012-01-07 04:59:52 +0000702 return;
703
704 // Otherwise, check that we can capture 'this'.
705 unsigned NumClosures = 0;
706 for (unsigned idx = FunctionScopes.size() - 1; idx != 0; idx--) {
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000707 if (CapturingScopeInfo *CSI =
708 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
709 if (CSI->CXXThisCaptureIndex != 0) {
710 // 'this' is already being captured; there isn't anything more to do.
Eli Friedman72899c32012-01-07 04:59:52 +0000711 break;
712 }
Douglas Gregora1f21142012-02-01 17:04:21 +0000713
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000714 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000715 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
Douglas Gregora1f21142012-02-01 17:04:21 +0000716 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
717 Explicit) {
718 // This closure can capture 'this'; continue looking upwards.
Eli Friedman72899c32012-01-07 04:59:52 +0000719 NumClosures++;
Douglas Gregora1f21142012-02-01 17:04:21 +0000720 Explicit = false;
Eli Friedman72899c32012-01-07 04:59:52 +0000721 continue;
722 }
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000723 // This context can't implicitly capture 'this'; fail out.
Douglas Gregora1f21142012-02-01 17:04:21 +0000724 Diag(Loc, diag::err_this_capture) << Explicit;
Eli Friedman72899c32012-01-07 04:59:52 +0000725 return;
726 }
Eli Friedman72899c32012-01-07 04:59:52 +0000727 break;
728 }
729
730 // Mark that we're implicitly capturing 'this' in all the scopes we skipped.
731 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
732 // contexts.
733 for (unsigned idx = FunctionScopes.size() - 1;
734 NumClosures; --idx, --NumClosures) {
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000735 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
Eli Friedman668165a2012-02-11 02:51:16 +0000736 Expr *ThisExpr = 0;
Douglas Gregor999713e2012-02-18 09:37:24 +0000737 QualType ThisTy = getCurrentThisType();
Eli Friedman668165a2012-02-11 02:51:16 +0000738 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
739 // For lambda expressions, build a field and an initializing expression.
Eli Friedman668165a2012-02-11 02:51:16 +0000740 CXXRecordDecl *Lambda = LSI->Lambda;
741 FieldDecl *Field
742 = FieldDecl::Create(Context, Lambda, Loc, Loc, 0, ThisTy,
743 Context.getTrivialTypeSourceInfo(ThisTy, Loc),
744 0, false, false);
745 Field->setImplicit(true);
746 Field->setAccess(AS_private);
747 Lambda->addDecl(Field);
748 ThisExpr = new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/true);
749 }
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000750 bool isNested = NumClosures > 1;
Douglas Gregor999713e2012-02-18 09:37:24 +0000751 CSI->addThisCapture(isNested, Loc, ThisTy, ThisExpr);
Eli Friedman72899c32012-01-07 04:59:52 +0000752 }
753}
754
Richard Smith7a614d82011-06-11 17:19:42 +0000755ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCall5808ce42011-02-03 08:15:49 +0000756 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
757 /// is a non-lvalue expression whose value is the address of the object for
758 /// which the function is called.
759
Douglas Gregor341350e2011-10-18 16:47:30 +0000760 QualType ThisTy = getCurrentThisType();
Richard Smith7a614d82011-06-11 17:19:42 +0000761 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCall5808ce42011-02-03 08:15:49 +0000762
Eli Friedman72899c32012-01-07 04:59:52 +0000763 CheckCXXThisCapture(Loc);
Richard Smith7a614d82011-06-11 17:19:42 +0000764 return Owned(new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000765}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000766
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000767bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
768 // If we're outside the body of a member function, then we'll have a specified
769 // type for 'this'.
770 if (CXXThisTypeOverride.isNull())
771 return false;
772
773 // Determine whether we're looking into a class that's currently being
774 // defined.
775 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
776 return Class && Class->isBeingDefined();
777}
778
John McCall60d7b3a2010-08-24 06:29:42 +0000779ExprResult
Douglas Gregorab6677e2010-09-08 00:15:04 +0000780Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000781 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000782 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000783 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000784 if (!TypeRep)
785 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000786
John McCall9d125032010-01-15 18:39:57 +0000787 TypeSourceInfo *TInfo;
788 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
789 if (!TInfo)
790 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregorab6677e2010-09-08 00:15:04 +0000791
792 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
793}
794
795/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
796/// Can be interpreted either as function-style casting ("int(x)")
797/// or class type construction ("ClassType(x,y,z)")
798/// or creation of a value-initialized type ("int()").
799ExprResult
800Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
801 SourceLocation LParenLoc,
802 MultiExprArg exprs,
803 SourceLocation RParenLoc) {
804 QualType Ty = TInfo->getType();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000805 unsigned NumExprs = exprs.size();
806 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000807 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000808
Sebastian Redlf53597f2009-03-15 17:47:39 +0000809 if (Ty->isDependentType() ||
Ahmed Charles13a140c2012-02-25 11:00:22 +0000810 CallExpr::hasAnyTypeDependentArguments(
811 llvm::makeArrayRef(Exprs, NumExprs))) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000812 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000813
Douglas Gregorab6677e2010-09-08 00:15:04 +0000814 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000815 LParenLoc,
816 Exprs, NumExprs,
817 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000818 }
819
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000820 bool ListInitialization = LParenLoc.isInvalid();
821 assert((!ListInitialization || (NumExprs == 1 && isa<InitListExpr>(Exprs[0])))
822 && "List initialization must have initializer list as expression.");
823 SourceRange FullRange = SourceRange(TyBeginLoc,
824 ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
825
Douglas Gregor506ae412009-01-16 18:33:17 +0000826 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000827 // If the expression list is a single expression, the type conversion
828 // expression is equivalent (in definedness, and if defined in meaning) to the
829 // corresponding cast expression.
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000830 if (NumExprs == 1 && !ListInitialization) {
John McCallb45ae252011-10-05 07:41:44 +0000831 Expr *Arg = Exprs[0];
Anders Carlsson0aebc812009-09-09 21:33:21 +0000832 exprs.release();
John McCallb45ae252011-10-05 07:41:44 +0000833 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000834 }
835
Eli Friedmanc60ccf52012-02-29 00:00:28 +0000836 QualType ElemTy = Ty;
837 if (Ty->isArrayType()) {
838 if (!ListInitialization)
839 return ExprError(Diag(TyBeginLoc,
840 diag::err_value_init_for_array_type) << FullRange);
841 ElemTy = Context.getBaseElementType(Ty);
842 }
843
844 if (!Ty->isVoidType() &&
845 RequireCompleteType(TyBeginLoc, ElemTy,
846 PDiag(diag::err_invalid_incomplete_type_use)
847 << FullRange))
848 return ExprError();
849
850 if (RequireNonAbstractType(TyBeginLoc, Ty,
851 diag::err_allocation_of_abstract_type))
852 return ExprError();
853
Douglas Gregor19311e72010-09-08 21:40:08 +0000854 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
855 InitializationKind Kind
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000856 = NumExprs ? ListInitialization
857 ? InitializationKind::CreateDirectList(TyBeginLoc)
858 : InitializationKind::CreateDirect(TyBeginLoc,
859 LParenLoc, RParenLoc)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000860 : InitializationKind::CreateValue(TyBeginLoc,
Douglas Gregor19311e72010-09-08 21:40:08 +0000861 LParenLoc, RParenLoc);
862 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
863 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redlf53597f2009-03-15 17:47:39 +0000864
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000865 if (!Result.isInvalid() && ListInitialization &&
866 isa<InitListExpr>(Result.get())) {
867 // If the list-initialization doesn't involve a constructor call, we'll get
868 // the initializer-list (with corrected type) back, but that's not what we
869 // want, since it will be treated as an initializer list in further
870 // processing. Explicitly insert a cast here.
871 InitListExpr *List = cast<InitListExpr>(Result.take());
872 Result = Owned(CXXFunctionalCastExpr::Create(Context, List->getType(),
873 Expr::getValueKindForType(TInfo->getType()),
874 TInfo, TyBeginLoc, CK_NoOp,
875 List, /*Path=*/0, RParenLoc));
876 }
877
Douglas Gregor19311e72010-09-08 21:40:08 +0000878 // FIXME: Improve AST representation?
879 return move(Result);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000880}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000881
John McCall6ec278d2011-01-27 09:37:56 +0000882/// doesUsualArrayDeleteWantSize - Answers whether the usual
883/// operator delete[] for the given type has a size_t parameter.
884static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
885 QualType allocType) {
886 const RecordType *record =
887 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
888 if (!record) return false;
889
890 // Try to find an operator delete[] in class scope.
891
892 DeclarationName deleteName =
893 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
894 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
895 S.LookupQualifiedName(ops, record->getDecl());
896
897 // We're just doing this for information.
898 ops.suppressDiagnostics();
899
900 // Very likely: there's no operator delete[].
901 if (ops.empty()) return false;
902
903 // If it's ambiguous, it should be illegal to call operator delete[]
904 // on this thing, so it doesn't matter if we allocate extra space or not.
905 if (ops.isAmbiguous()) return false;
906
907 LookupResult::Filter filter = ops.makeFilter();
908 while (filter.hasNext()) {
909 NamedDecl *del = filter.next()->getUnderlyingDecl();
910
911 // C++0x [basic.stc.dynamic.deallocation]p2:
912 // A template instance is never a usual deallocation function,
913 // regardless of its signature.
914 if (isa<FunctionTemplateDecl>(del)) {
915 filter.erase();
916 continue;
917 }
918
919 // C++0x [basic.stc.dynamic.deallocation]p2:
920 // If class T does not declare [an operator delete[] with one
921 // parameter] but does declare a member deallocation function
922 // named operator delete[] with exactly two parameters, the
923 // second of which has type std::size_t, then this function
924 // is a usual deallocation function.
925 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
926 filter.erase();
927 continue;
928 }
929 }
930 filter.done();
931
932 if (!ops.isSingleResult()) return false;
933
934 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
935 return (del->getNumParams() == 2);
936}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000937
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000938/// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
939
940/// E.g.:
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000941/// @code new (memory) int[size][4] @endcode
942/// or
943/// @code ::new Foo(23, "hello") @endcode
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000944///
945/// \param StartLoc The first location of the expression.
946/// \param UseGlobal True if 'new' was prefixed with '::'.
947/// \param PlacementLParen Opening paren of the placement arguments.
948/// \param PlacementArgs Placement new arguments.
949/// \param PlacementRParen Closing paren of the placement arguments.
950/// \param TypeIdParens If the type is in parens, the source range.
951/// \param D The type to be allocated, as well as array dimensions.
952/// \param ConstructorLParen Opening paren of the constructor args, empty if
953/// initializer-list syntax is used.
954/// \param ConstructorArgs Constructor/initialization arguments.
955/// \param ConstructorRParen Closing paren of the constructor args.
John McCall60d7b3a2010-08-24 06:29:42 +0000956ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000957Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000958 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000959 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000960 Declarator &D, Expr *Initializer) {
Richard Smith34b41d92011-02-20 03:19:35 +0000961 bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
962
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000963 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000964 // If the specified type is an array, unwrap it and save the expression.
965 if (D.getNumTypeObjects() > 0 &&
966 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
967 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smith34b41d92011-02-20 03:19:35 +0000968 if (TypeContainsAuto)
969 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
970 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000971 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000972 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
973 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000974 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000975 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
976 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000977
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000978 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000979 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000980 }
981
Douglas Gregor043cad22009-09-11 00:18:58 +0000982 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000983 if (ArraySize) {
984 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000985 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
986 break;
987
988 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
989 if (Expr *NumElts = (Expr *)Array.NumElts) {
Richard Smith282e7e62012-02-04 09:53:13 +0000990 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
991 Array.NumElts = VerifyIntegerConstantExpression(NumElts, 0,
992 PDiag(diag::err_new_array_nonconst)).take();
993 if (!Array.NumElts)
994 return ExprError();
Douglas Gregor043cad22009-09-11 00:18:58 +0000995 }
996 }
997 }
998 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000999
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +00001000 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
John McCallbf1a0282010-06-04 23:28:52 +00001001 QualType AllocType = TInfo->getType();
Chris Lattnereaaebc72009-04-25 08:06:05 +00001002 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001003 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001004
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001005 SourceRange DirectInitRange;
1006 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1007 DirectInitRange = List->getSourceRange();
1008
Mike Stump1eb44332009-09-09 15:08:12 +00001009 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +00001010 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +00001011 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +00001012 PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +00001013 TypeIdParens,
Mike Stump1eb44332009-09-09 15:08:12 +00001014 AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001015 TInfo,
John McCall9ae2f072010-08-23 23:25:46 +00001016 ArraySize,
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001017 DirectInitRange,
1018 Initializer,
Richard Smith34b41d92011-02-20 03:19:35 +00001019 TypeContainsAuto);
Douglas Gregor3433cf72009-05-21 00:00:09 +00001020}
1021
Sebastian Redlbd45d252012-02-16 12:59:47 +00001022static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1023 Expr *Init) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001024 if (!Init)
1025 return true;
Sebastian Redl1f278052012-02-17 08:42:32 +00001026 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1027 return PLE->getNumExprs() == 0;
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001028 if (isa<ImplicitValueInitExpr>(Init))
1029 return true;
1030 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1031 return !CCE->isListInitialization() &&
1032 CCE->getConstructor()->isDefaultConstructor();
Sebastian Redlbd45d252012-02-16 12:59:47 +00001033 else if (Style == CXXNewExpr::ListInit) {
1034 assert(isa<InitListExpr>(Init) &&
1035 "Shouldn't create list CXXConstructExprs for arrays.");
1036 return true;
1037 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001038 return false;
1039}
1040
John McCall60d7b3a2010-08-24 06:29:42 +00001041ExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +00001042Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
1043 SourceLocation PlacementLParen,
1044 MultiExprArg PlacementArgs,
1045 SourceLocation PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +00001046 SourceRange TypeIdParens,
Douglas Gregor3433cf72009-05-21 00:00:09 +00001047 QualType AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001048 TypeSourceInfo *AllocTypeInfo,
John McCall9ae2f072010-08-23 23:25:46 +00001049 Expr *ArraySize,
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001050 SourceRange DirectInitRange,
1051 Expr *Initializer,
Richard Smith34b41d92011-02-20 03:19:35 +00001052 bool TypeMayContainAuto) {
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001053 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001054
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001055 CXXNewExpr::InitializationStyle initStyle;
1056 if (DirectInitRange.isValid()) {
1057 assert(Initializer && "Have parens but no initializer.");
1058 initStyle = CXXNewExpr::CallInit;
1059 } else if (Initializer && isa<InitListExpr>(Initializer))
1060 initStyle = CXXNewExpr::ListInit;
1061 else {
Sebastian Redl428c6202012-02-22 09:07:21 +00001062 // In template instantiation, the initializer could be a CXXDefaultArgExpr
1063 // unwrapped from a CXXConstructExpr that was implicitly built. There is no
1064 // particularly sane way we can handle this (especially since it can even
1065 // occur for array new), so we throw the initializer away and have it be
1066 // rebuilt.
1067 if (Initializer && isa<CXXDefaultArgExpr>(Initializer))
1068 Initializer = 0;
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001069 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1070 isa<CXXConstructExpr>(Initializer)) &&
1071 "Initializer expression that cannot have been implicitly created.");
1072 initStyle = CXXNewExpr::NoInit;
1073 }
1074
1075 Expr **Inits = &Initializer;
1076 unsigned NumInits = Initializer ? 1 : 0;
1077 if (initStyle == CXXNewExpr::CallInit) {
1078 if (ParenListExpr *List = dyn_cast<ParenListExpr>(Initializer)) {
1079 Inits = List->getExprs();
1080 NumInits = List->getNumExprs();
1081 } else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Initializer)){
1082 if (!isa<CXXTemporaryObjectExpr>(CCE)) {
1083 // Can happen in template instantiation. Since this is just an implicit
1084 // construction, we just take it apart and rebuild it.
1085 Inits = CCE->getArgs();
1086 NumInits = CCE->getNumArgs();
1087 }
1088 }
1089 }
1090
Richard Smith34b41d92011-02-20 03:19:35 +00001091 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1092 if (TypeMayContainAuto && AllocType->getContainedAutoType()) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001093 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
Richard Smith34b41d92011-02-20 03:19:35 +00001094 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1095 << AllocType << TypeRange);
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001096 if (initStyle == CXXNewExpr::ListInit)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001097 return ExprError(Diag(Inits[0]->getLocStart(),
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001098 diag::err_auto_new_requires_parens)
1099 << AllocType << TypeRange);
1100 if (NumInits > 1) {
1101 Expr *FirstBad = Inits[1];
Daniel Dunbar96a00142012-03-09 18:35:03 +00001102 return ExprError(Diag(FirstBad->getLocStart(),
Richard Smith34b41d92011-02-20 03:19:35 +00001103 diag::err_auto_new_ctor_multiple_expressions)
1104 << AllocType << TypeRange);
1105 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001106 Expr *Deduce = Inits[0];
Richard Smitha085da82011-03-17 16:11:59 +00001107 TypeSourceInfo *DeducedType = 0;
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001108 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) ==
Sebastian Redlb832f6d2012-01-23 22:09:39 +00001109 DAR_Failed)
Richard Smith34b41d92011-02-20 03:19:35 +00001110 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001111 << AllocType << Deduce->getType()
1112 << TypeRange << Deduce->getSourceRange());
Richard Smitha085da82011-03-17 16:11:59 +00001113 if (!DeducedType)
1114 return ExprError();
Richard Smith34b41d92011-02-20 03:19:35 +00001115
Richard Smitha085da82011-03-17 16:11:59 +00001116 AllocTypeInfo = DeducedType;
1117 AllocType = AllocTypeInfo->getType();
Richard Smith34b41d92011-02-20 03:19:35 +00001118 }
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001119
Douglas Gregor3caf04e2010-05-16 16:01:03 +00001120 // Per C++0x [expr.new]p5, the type being constructed may be a
1121 // typedef of an array type.
John McCall9ae2f072010-08-23 23:25:46 +00001122 if (!ArraySize) {
Douglas Gregor3caf04e2010-05-16 16:01:03 +00001123 if (const ConstantArrayType *Array
1124 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00001125 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1126 Context.getSizeType(),
1127 TypeRange.getEnd());
Douglas Gregor3caf04e2010-05-16 16:01:03 +00001128 AllocType = Array->getElementType();
1129 }
1130 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001131
Douglas Gregora0750762010-10-06 16:00:31 +00001132 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1133 return ExprError();
1134
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001135 if (initStyle == CXXNewExpr::ListInit && isStdInitializerList(AllocType, 0)) {
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001136 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1137 diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00001138 << /*at end of FE*/0 << Inits[0]->getSourceRange();
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001139 }
1140
John McCallf85e1932011-06-15 23:02:42 +00001141 // In ARC, infer 'retaining' for the allocated
David Blaikie4e4d0842012-03-11 07:00:24 +00001142 if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001143 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1144 AllocType->isObjCLifetimeType()) {
1145 AllocType = Context.getLifetimeQualifiedType(AllocType,
1146 AllocType->getObjCARCImplicitLifetime());
1147 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001148
John McCallf85e1932011-06-15 23:02:42 +00001149 QualType ResultType = Context.getPointerType(AllocType);
1150
Richard Smithf39aec12012-02-04 07:07:42 +00001151 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1152 // integral or enumeration type with a non-negative value."
1153 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1154 // enumeration type, or a class type for which a single non-explicit
1155 // conversion function to integral or unscoped enumeration type exists.
Sebastian Redl28507842009-02-26 14:39:58 +00001156 if (ArraySize && !ArraySize->isTypeDependent()) {
Eli Friedmanceccab92012-01-26 00:26:18 +00001157 ExprResult ConvertedSize = ConvertToIntegralOrEnumerationType(
Richard Smithebaf0e62011-10-18 20:49:44 +00001158 StartLoc, ArraySize,
David Blaikie4e4d0842012-03-11 07:00:24 +00001159 PDiag(diag::err_array_size_not_integral) << getLangOpts().CPlusPlus0x,
Richard Smithebaf0e62011-10-18 20:49:44 +00001160 PDiag(diag::err_array_size_incomplete_type)
1161 << ArraySize->getSourceRange(),
1162 PDiag(diag::err_array_size_explicit_conversion),
1163 PDiag(diag::note_array_size_conversion),
1164 PDiag(diag::err_array_size_ambiguous_conversion),
1165 PDiag(diag::note_array_size_conversion),
David Blaikie4e4d0842012-03-11 07:00:24 +00001166 PDiag(getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00001167 diag::warn_cxx98_compat_array_size_conversion :
Richard Smithf39aec12012-02-04 07:07:42 +00001168 diag::ext_array_size_conversion),
1169 /*AllowScopedEnumerations*/ false);
Douglas Gregor6bc574d2010-06-30 00:20:43 +00001170 if (ConvertedSize.isInvalid())
1171 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001172
John McCall9ae2f072010-08-23 23:25:46 +00001173 ArraySize = ConvertedSize.take();
John McCall806054d2012-01-11 00:14:46 +00001174 QualType SizeType = ArraySize->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001175 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor6bc574d2010-06-30 00:20:43 +00001176 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001177
Richard Smith0b458fd2012-02-04 05:35:53 +00001178 // C++98 [expr.new]p7:
1179 // The expression in a direct-new-declarator shall have integral type
1180 // with a non-negative value.
1181 //
1182 // Let's see if this is a constant < 0. If so, we reject it out of
1183 // hand. Otherwise, if it's not a constant, we must have an unparenthesized
1184 // array type.
1185 //
1186 // Note: such a construct has well-defined semantics in C++11: it throws
1187 // std::bad_array_new_length.
Sebastian Redl28507842009-02-26 14:39:58 +00001188 if (!ArraySize->isValueDependent()) {
1189 llvm::APSInt Value;
Richard Smith282e7e62012-02-04 09:53:13 +00001190 // We've already performed any required implicit conversion to integer or
1191 // unscoped enumeration type.
Richard Smith0b458fd2012-02-04 05:35:53 +00001192 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
Sebastian Redl28507842009-02-26 14:39:58 +00001193 if (Value < llvm::APSInt(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001194 llvm::APInt::getNullValue(Value.getBitWidth()),
Richard Smith0b458fd2012-02-04 05:35:53 +00001195 Value.isUnsigned())) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001196 if (getLangOpts().CPlusPlus0x)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001197 Diag(ArraySize->getLocStart(),
Richard Smith0b458fd2012-02-04 05:35:53 +00001198 diag::warn_typecheck_negative_array_new_size)
Douglas Gregor2767ce22010-08-18 00:39:00 +00001199 << ArraySize->getSourceRange();
Richard Smith0b458fd2012-02-04 05:35:53 +00001200 else
Daniel Dunbar96a00142012-03-09 18:35:03 +00001201 return ExprError(Diag(ArraySize->getLocStart(),
Richard Smith0b458fd2012-02-04 05:35:53 +00001202 diag::err_typecheck_negative_array_size)
1203 << ArraySize->getSourceRange());
1204 } else if (!AllocType->isDependentType()) {
1205 unsigned ActiveSizeBits =
1206 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1207 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001208 if (getLangOpts().CPlusPlus0x)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001209 Diag(ArraySize->getLocStart(),
Richard Smith0b458fd2012-02-04 05:35:53 +00001210 diag::warn_array_new_too_large)
1211 << Value.toString(10)
1212 << ArraySize->getSourceRange();
1213 else
Daniel Dunbar96a00142012-03-09 18:35:03 +00001214 return ExprError(Diag(ArraySize->getLocStart(),
Richard Smith0b458fd2012-02-04 05:35:53 +00001215 diag::err_array_too_large)
1216 << Value.toString(10)
1217 << ArraySize->getSourceRange());
Douglas Gregor2767ce22010-08-18 00:39:00 +00001218 }
1219 }
Douglas Gregor4bd40312010-07-13 15:54:32 +00001220 } else if (TypeIdParens.isValid()) {
1221 // Can't have dynamic array size when the type-id is in parentheses.
1222 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1223 << ArraySize->getSourceRange()
1224 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1225 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001226
Douglas Gregor4bd40312010-07-13 15:54:32 +00001227 TypeIdParens = SourceRange();
Sebastian Redl28507842009-02-26 14:39:58 +00001228 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001229 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001230
John McCallf85e1932011-06-15 23:02:42 +00001231 // ARC: warn about ABI issues.
David Blaikie4e4d0842012-03-11 07:00:24 +00001232 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00001233 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1234 if (BaseAllocType.hasStrongOrWeakObjCLifetime())
1235 Diag(StartLoc, diag::warn_err_new_delete_object_array)
1236 << 0 << BaseAllocType;
1237 }
1238
John McCall7d166272011-05-15 07:14:44 +00001239 // Note that we do *not* convert the argument in any way. It can
1240 // be signed, larger than size_t, whatever.
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001241 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001242
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001243 FunctionDecl *OperatorNew = 0;
1244 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +00001245 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
1246 unsigned NumPlaceArgs = PlacementArgs.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001247
Sebastian Redl28507842009-02-26 14:39:58 +00001248 if (!AllocType->isDependentType() &&
Ahmed Charles13a140c2012-02-25 11:00:22 +00001249 !Expr::hasAnyTypeDependentArguments(
1250 llvm::makeArrayRef(PlaceArgs, NumPlaceArgs)) &&
Sebastian Redl28507842009-02-26 14:39:58 +00001251 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +00001252 SourceRange(PlacementLParen, PlacementRParen),
1253 UseGlobal, AllocType, ArraySize, PlaceArgs,
1254 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +00001255 return ExprError();
John McCall6ec278d2011-01-27 09:37:56 +00001256
1257 // If this is an array allocation, compute whether the usual array
1258 // deallocation function for the type has a size_t parameter.
1259 bool UsualArrayDeleteWantsSize = false;
1260 if (ArraySize && !AllocType->isDependentType())
1261 UsualArrayDeleteWantsSize
1262 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1263
Chris Lattner5f9e2722011-07-23 10:55:15 +00001264 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001265 if (OperatorNew) {
1266 // Add default arguments, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001267 const FunctionProtoType *Proto =
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001268 OperatorNew->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001269 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00001270 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001271
Anders Carlsson28e94832010-05-03 02:07:56 +00001272 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001273 Proto, 1, PlaceArgs, NumPlaceArgs,
Anders Carlsson28e94832010-05-03 02:07:56 +00001274 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001275 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001276
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001277 NumPlaceArgs = AllPlaceArgs.size();
1278 if (NumPlaceArgs > 0)
1279 PlaceArgs = &AllPlaceArgs[0];
Eli Friedmane61eb042012-02-18 04:48:30 +00001280
1281 DiagnoseSentinelCalls(OperatorNew, PlacementLParen,
1282 PlaceArgs, NumPlaceArgs);
1283
1284 // FIXME: Missing call to CheckFunctionCall or equivalent
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001285 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001286
Nick Lewyckyfca84b22012-01-24 21:15:41 +00001287 // Warn if the type is over-aligned and is being allocated by global operator
1288 // new.
Nick Lewycky507a8a32012-02-04 03:30:14 +00001289 if (NumPlaceArgs == 0 && OperatorNew &&
Nick Lewyckyfca84b22012-01-24 21:15:41 +00001290 (OperatorNew->isImplicit() ||
1291 getSourceManager().isInSystemHeader(OperatorNew->getLocStart()))) {
1292 if (unsigned Align = Context.getPreferredTypeAlign(AllocType.getTypePtr())){
1293 unsigned SuitableAlign = Context.getTargetInfo().getSuitableAlign();
1294 if (Align > SuitableAlign)
1295 Diag(StartLoc, diag::warn_overaligned_type)
1296 << AllocType
1297 << unsigned(Align / Context.getCharWidth())
1298 << unsigned(SuitableAlign / Context.getCharWidth());
1299 }
1300 }
1301
Sebastian Redlbd45d252012-02-16 12:59:47 +00001302 QualType InitType = AllocType;
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001303 // Array 'new' can't have any initializers except empty parentheses.
Sebastian Redlbd45d252012-02-16 12:59:47 +00001304 // Initializer lists are also allowed, in C++11. Rely on the parser for the
1305 // dialect distinction.
1306 if (ResultType->isArrayType() || ArraySize) {
1307 if (!isLegalArrayNewInitializer(initStyle, Initializer)) {
1308 SourceRange InitRange(Inits[0]->getLocStart(),
1309 Inits[NumInits - 1]->getLocEnd());
1310 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1311 return ExprError();
1312 }
1313 if (InitListExpr *ILE = dyn_cast_or_null<InitListExpr>(Initializer)) {
1314 // We do the initialization typechecking against the array type
1315 // corresponding to the number of initializers + 1 (to also check
1316 // default-initialization).
1317 unsigned NumElements = ILE->getNumInits() + 1;
1318 InitType = Context.getConstantArrayType(AllocType,
1319 llvm::APInt(Context.getTypeSize(Context.getSizeType()), NumElements),
1320 ArrayType::Normal, 0);
1321 }
Anders Carlsson48c95012010-05-03 15:45:23 +00001322 }
1323
Douglas Gregor99a2e602009-12-16 01:38:02 +00001324 if (!AllocType->isDependentType() &&
Ahmed Charles13a140c2012-02-25 11:00:22 +00001325 !Expr::hasAnyTypeDependentArguments(
1326 llvm::makeArrayRef(Inits, NumInits))) {
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001327 // C++11 [expr.new]p15:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001328 // A new-expression that creates an object of type T initializes that
1329 // object as follows:
1330 InitializationKind Kind
1331 // - If the new-initializer is omitted, the object is default-
1332 // initialized (8.5); if no initialization is performed,
1333 // the object has indeterminate value
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001334 = initStyle == CXXNewExpr::NoInit
1335 ? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001336 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor99a2e602009-12-16 01:38:02 +00001337 // initialization rules of 8.5 for direct-initialization.
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001338 : initStyle == CXXNewExpr::ListInit
1339 ? InitializationKind::CreateDirectList(TypeRange.getBegin())
1340 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1341 DirectInitRange.getBegin(),
1342 DirectInitRange.getEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001343
Douglas Gregor99a2e602009-12-16 01:38:02 +00001344 InitializedEntity Entity
Sebastian Redlbd45d252012-02-16 12:59:47 +00001345 = InitializedEntity::InitializeNew(StartLoc, InitType);
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001346 InitializationSequence InitSeq(*this, Entity, Kind, Inits, NumInits);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001347 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001348 MultiExprArg(Inits, NumInits));
Douglas Gregor99a2e602009-12-16 01:38:02 +00001349 if (FullInit.isInvalid())
1350 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001351
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001352 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
1353 // we don't want the initialized object to be destructed.
1354 if (CXXBindTemporaryExpr *Binder =
1355 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
1356 FullInit = Owned(Binder->getSubExpr());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001357
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001358 Initializer = FullInit.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001359 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001360
Douglas Gregor6d908702010-02-26 05:06:18 +00001361 // Mark the new and delete operators as referenced.
1362 if (OperatorNew)
Eli Friedman5f2987c2012-02-02 03:46:19 +00001363 MarkFunctionReferenced(StartLoc, OperatorNew);
Douglas Gregor6d908702010-02-26 05:06:18 +00001364 if (OperatorDelete)
Eli Friedman5f2987c2012-02-02 03:46:19 +00001365 MarkFunctionReferenced(StartLoc, OperatorDelete);
Douglas Gregor6d908702010-02-26 05:06:18 +00001366
John McCall84ff0fc2011-07-13 20:12:57 +00001367 // C++0x [expr.new]p17:
1368 // If the new expression creates an array of objects of class type,
1369 // access and ambiguity control are done for the destructor.
David Blaikie426d6ca2012-03-10 23:40:02 +00001370 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1371 if (ArraySize && !BaseAllocType->isDependentType()) {
1372 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
1373 if (CXXDestructorDecl *dtor = LookupDestructor(
1374 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
1375 MarkFunctionReferenced(StartLoc, dtor);
1376 CheckDestructorAccess(StartLoc, dtor,
1377 PDiag(diag::err_access_dtor)
1378 << BaseAllocType);
1379 DiagnoseUseOfDecl(dtor, StartLoc);
1380 }
John McCall84ff0fc2011-07-13 20:12:57 +00001381 }
1382 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001383
Sebastian Redlf53597f2009-03-15 17:47:39 +00001384 PlacementArgs.release();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001385
Ted Kremenekad7fe862010-02-11 22:51:03 +00001386 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001387 OperatorDelete,
John McCall6ec278d2011-01-27 09:37:56 +00001388 UsualArrayDeleteWantsSize,
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001389 PlaceArgs, NumPlaceArgs, TypeIdParens,
1390 ArraySize, initStyle, Initializer,
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001391 ResultType, AllocTypeInfo,
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001392 StartLoc, DirectInitRange));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001393}
1394
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001395/// \brief Checks that a type is suitable as the allocated type
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001396/// in a new-expression.
Douglas Gregor3433cf72009-05-21 00:00:09 +00001397bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00001398 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001399 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1400 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +00001401 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001402 return Diag(Loc, diag::err_bad_new_type)
1403 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001404 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001405 return Diag(Loc, diag::err_bad_new_type)
1406 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001407 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +00001408 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001409 PDiag(diag::err_new_incomplete_type)
1410 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001411 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +00001412 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +00001413 diag::err_allocation_of_abstract_type))
1414 return true;
Douglas Gregora0750762010-10-06 16:00:31 +00001415 else if (AllocType->isVariablyModifiedType())
1416 return Diag(Loc, diag::err_variably_modified_new_type)
1417 << AllocType;
Douglas Gregor5666d362011-04-15 19:46:20 +00001418 else if (unsigned AddressSpace = AllocType.getAddressSpace())
1419 return Diag(Loc, diag::err_address_space_qualified_new)
1420 << AllocType.getUnqualifiedType() << AddressSpace;
David Blaikie4e4d0842012-03-11 07:00:24 +00001421 else if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00001422 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
1423 QualType BaseAllocType = Context.getBaseElementType(AT);
1424 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1425 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001426 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001427 << BaseAllocType;
1428 }
1429 }
Douglas Gregor5666d362011-04-15 19:46:20 +00001430
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001431 return false;
1432}
1433
Douglas Gregor6d908702010-02-26 05:06:18 +00001434/// \brief Determine whether the given function is a non-placement
1435/// deallocation function.
1436static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1437 if (FD->isInvalidDecl())
1438 return false;
1439
1440 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1441 return Method->isUsualDeallocationFunction();
1442
1443 return ((FD->getOverloadedOperator() == OO_Delete ||
1444 FD->getOverloadedOperator() == OO_Array_Delete) &&
1445 FD->getNumParams() == 1);
1446}
1447
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001448/// FindAllocationFunctions - Finds the overloads of operator new and delete
1449/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001450bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1451 bool UseGlobal, QualType AllocType,
1452 bool IsArray, Expr **PlaceArgs,
1453 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001454 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +00001455 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001456 // --- Choosing an allocation function ---
1457 // C++ 5.3.4p8 - 14 & 18
1458 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1459 // in the scope of the allocated class.
1460 // 2) If an array size is given, look for operator new[], else look for
1461 // operator new.
1462 // 3) The first argument is always size_t. Append the arguments from the
1463 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001464
Chris Lattner5f9e2722011-07-23 10:55:15 +00001465 SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001466 // We don't care about the actual value of this argument.
1467 // FIXME: Should the Sema create the expression and embed it in the syntax
1468 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00001469 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001470 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssond67c4c32009-08-16 20:29:29 +00001471 Context.getSizeType(),
1472 SourceLocation());
1473 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001474 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1475
Douglas Gregor6d908702010-02-26 05:06:18 +00001476 // C++ [expr.new]p8:
1477 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001478 // function's name is operator new and the deallocation function's
Douglas Gregor6d908702010-02-26 05:06:18 +00001479 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001480 // type, the allocation function's name is operator new[] and the
1481 // deallocation function's name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001482 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1483 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +00001484 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1485 IsArray ? OO_Array_Delete : OO_Delete);
1486
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001487 QualType AllocElemType = Context.getBaseElementType(AllocType);
1488
1489 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +00001490 CXXRecordDecl *Record
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001491 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +00001492 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001493 AllocArgs.size(), Record, /*AllowMissing=*/true,
1494 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001495 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001496 }
1497 if (!OperatorNew) {
1498 // Didn't find a member overload. Look for a global one.
1499 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +00001500 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +00001501 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001502 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1503 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001504 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001505 }
1506
John McCall9c82afc2010-04-20 02:18:25 +00001507 // We don't need an operator delete if we're running under
1508 // -fno-exceptions.
David Blaikie4e4d0842012-03-11 07:00:24 +00001509 if (!getLangOpts().Exceptions) {
John McCall9c82afc2010-04-20 02:18:25 +00001510 OperatorDelete = 0;
1511 return false;
1512 }
1513
Anders Carlssond9583892009-05-31 20:26:12 +00001514 // FindAllocationOverload can change the passed in arguments, so we need to
1515 // copy them back.
1516 if (NumPlaceArgs > 0)
1517 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001518
Douglas Gregor6d908702010-02-26 05:06:18 +00001519 // C++ [expr.new]p19:
1520 //
1521 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001522 // deallocation function's name is looked up in the global
Douglas Gregor6d908702010-02-26 05:06:18 +00001523 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001524 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6d908702010-02-26 05:06:18 +00001525 // the scope of T. If this lookup fails to find the name, or if
1526 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001527 // deallocation function's name is looked up in the global scope.
Douglas Gregor6d908702010-02-26 05:06:18 +00001528 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001529 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001530 CXXRecordDecl *RD
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001531 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6d908702010-02-26 05:06:18 +00001532 LookupQualifiedName(FoundDelete, RD);
1533 }
John McCall90c8c572010-03-18 08:19:33 +00001534 if (FoundDelete.isAmbiguous())
1535 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +00001536
1537 if (FoundDelete.empty()) {
1538 DeclareGlobalNewDelete();
1539 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1540 }
1541
1542 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +00001543
Chris Lattner5f9e2722011-07-23 10:55:15 +00001544 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCall9aa472c2010-03-19 07:35:19 +00001545
John McCalledeb6c92010-09-14 21:34:24 +00001546 // Whether we're looking for a placement operator delete is dictated
1547 // by whether we selected a placement operator new, not by whether
1548 // we had explicit placement arguments. This matters for things like
1549 // struct A { void *operator new(size_t, int = 0); ... };
1550 // A *a = new A()
1551 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1552
1553 if (isPlacementNew) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001554 // C++ [expr.new]p20:
1555 // A declaration of a placement deallocation function matches the
1556 // declaration of a placement allocation function if it has the
1557 // same number of parameters and, after parameter transformations
1558 // (8.3.5), all parameter types except the first are
1559 // identical. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001560 //
Douglas Gregor6d908702010-02-26 05:06:18 +00001561 // To perform this comparison, we compute the function type that
1562 // the deallocation function should have, and use that type both
1563 // for template argument deduction and for comparison purposes.
John McCalle23cf432010-12-14 08:05:40 +00001564 //
1565 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6d908702010-02-26 05:06:18 +00001566 QualType ExpectedFunctionType;
1567 {
1568 const FunctionProtoType *Proto
1569 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00001570
Chris Lattner5f9e2722011-07-23 10:55:15 +00001571 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001572 ArgTypes.push_back(Context.VoidPtrTy);
Douglas Gregor6d908702010-02-26 05:06:18 +00001573 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1574 ArgTypes.push_back(Proto->getArgType(I));
1575
John McCalle23cf432010-12-14 08:05:40 +00001576 FunctionProtoType::ExtProtoInfo EPI;
1577 EPI.Variadic = Proto->isVariadic();
1578
Douglas Gregor6d908702010-02-26 05:06:18 +00001579 ExpectedFunctionType
1580 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
John McCalle23cf432010-12-14 08:05:40 +00001581 ArgTypes.size(), EPI);
Douglas Gregor6d908702010-02-26 05:06:18 +00001582 }
1583
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001584 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001585 DEnd = FoundDelete.end();
1586 D != DEnd; ++D) {
1587 FunctionDecl *Fn = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001588 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6d908702010-02-26 05:06:18 +00001589 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1590 // Perform template argument deduction to try to match the
1591 // expected function type.
1592 TemplateDeductionInfo Info(Context, StartLoc);
1593 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1594 continue;
1595 } else
1596 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1597
1598 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001599 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001600 }
1601 } else {
1602 // C++ [expr.new]p20:
1603 // [...] Any non-placement deallocation function matches a
1604 // non-placement allocation function. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001605 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001606 DEnd = FoundDelete.end();
1607 D != DEnd; ++D) {
1608 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1609 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001610 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001611 }
1612 }
1613
1614 // C++ [expr.new]p20:
1615 // [...] If the lookup finds a single matching deallocation
1616 // function, that function will be called; otherwise, no
1617 // deallocation function will be called.
1618 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001619 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001620
1621 // C++0x [expr.new]p20:
1622 // If the lookup finds the two-parameter form of a usual
1623 // deallocation function (3.7.4.2) and that function, considered
1624 // as a placement deallocation function, would have been
1625 // selected as a match for the allocation function, the program
1626 // is ill-formed.
David Blaikie4e4d0842012-03-11 07:00:24 +00001627 if (NumPlaceArgs && getLangOpts().CPlusPlus0x &&
Douglas Gregor6d908702010-02-26 05:06:18 +00001628 isNonPlacementDeallocationFunction(OperatorDelete)) {
1629 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001630 << SourceRange(PlaceArgs[0]->getLocStart(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001631 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1632 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1633 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001634 } else {
1635 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001636 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001637 }
1638 }
1639
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001640 return false;
1641}
1642
Sebastian Redl7f662392008-12-04 22:20:51 +00001643/// FindAllocationOverload - Find an fitting overload for the allocation
1644/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001645bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1646 DeclarationName Name, Expr** Args,
1647 unsigned NumArgs, DeclContext *Ctx,
Sean Hunt2be7e902011-05-12 22:46:29 +00001648 bool AllowMissing, FunctionDecl *&Operator,
1649 bool Diagnose) {
John McCalla24dc2e2009-11-17 02:14:36 +00001650 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1651 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001652 if (R.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001653 if (AllowMissing || !Diagnose)
Sebastian Redl7f662392008-12-04 22:20:51 +00001654 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001655 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001656 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001657 }
1658
John McCall90c8c572010-03-18 08:19:33 +00001659 if (R.isAmbiguous())
1660 return true;
1661
1662 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001663
John McCall5769d612010-02-08 23:07:23 +00001664 OverloadCandidateSet Candidates(StartLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001665 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001666 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001667 // Even member operator new/delete are implicitly treated as
1668 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001669 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001670
John McCall9aa472c2010-03-19 07:35:19 +00001671 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1672 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00001673 /*ExplicitTemplateArgs=*/0,
1674 llvm::makeArrayRef(Args, NumArgs),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001675 Candidates,
1676 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001677 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001678 }
1679
John McCall9aa472c2010-03-19 07:35:19 +00001680 FunctionDecl *Fn = cast<FunctionDecl>(D);
Ahmed Charles13a140c2012-02-25 11:00:22 +00001681 AddOverloadCandidate(Fn, Alloc.getPair(),
1682 llvm::makeArrayRef(Args, NumArgs), Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001683 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001684 }
1685
1686 // Do the resolution.
1687 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00001688 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001689 case OR_Success: {
1690 // Got one!
1691 FunctionDecl *FnDecl = Best->Function;
Eli Friedman5f2987c2012-02-02 03:46:19 +00001692 MarkFunctionReferenced(StartLoc, FnDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001693 // The first argument is size_t, and the first parameter must be size_t,
1694 // too. This is checked on declaration and can be assumed. (It can't be
1695 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001696 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001697 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1698 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001699 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1700 FnDecl->getParamDecl(i));
1701
1702 if (!Diagnose && !CanPerformCopyInitialization(Entity, Owned(Args[i])))
1703 return true;
1704
John McCall60d7b3a2010-08-24 06:29:42 +00001705 ExprResult Result
Sean Hunt2be7e902011-05-12 22:46:29 +00001706 = PerformCopyInitialization(Entity, SourceLocation(), Owned(Args[i]));
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001707 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001708 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001709
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001710 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001711 }
Richard Smith9a561d52012-02-26 09:11:52 +00001712
Sebastian Redl7f662392008-12-04 22:20:51 +00001713 Operator = FnDecl;
Richard Smith9a561d52012-02-26 09:11:52 +00001714
1715 if (CheckAllocationAccess(StartLoc, Range, R.getNamingClass(),
1716 Best->FoundDecl, Diagnose) == AR_inaccessible)
1717 return true;
1718
Sebastian Redl7f662392008-12-04 22:20:51 +00001719 return false;
1720 }
1721
1722 case OR_No_Viable_Function:
Chandler Carruth361d3802011-06-08 10:26:03 +00001723 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001724 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1725 << Name << Range;
Ahmed Charles13a140c2012-02-25 11:00:22 +00001726 Candidates.NoteCandidates(*this, OCD_AllCandidates,
1727 llvm::makeArrayRef(Args, NumArgs));
Chandler Carruth361d3802011-06-08 10:26:03 +00001728 }
Sebastian Redl7f662392008-12-04 22:20:51 +00001729 return true;
1730
1731 case OR_Ambiguous:
Chandler Carruth361d3802011-06-08 10:26:03 +00001732 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001733 Diag(StartLoc, diag::err_ovl_ambiguous_call)
1734 << Name << Range;
Ahmed Charles13a140c2012-02-25 11:00:22 +00001735 Candidates.NoteCandidates(*this, OCD_ViableCandidates,
1736 llvm::makeArrayRef(Args, NumArgs));
Chandler Carruth361d3802011-06-08 10:26:03 +00001737 }
Sebastian Redl7f662392008-12-04 22:20:51 +00001738 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001739
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001740 case OR_Deleted: {
Chandler Carruth361d3802011-06-08 10:26:03 +00001741 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001742 Diag(StartLoc, diag::err_ovl_deleted_call)
1743 << Best->Function->isDeleted()
1744 << Name
1745 << getDeletedOrUnavailableSuffix(Best->Function)
1746 << Range;
Ahmed Charles13a140c2012-02-25 11:00:22 +00001747 Candidates.NoteCandidates(*this, OCD_AllCandidates,
1748 llvm::makeArrayRef(Args, NumArgs));
Chandler Carruth361d3802011-06-08 10:26:03 +00001749 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001750 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001751 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001752 }
David Blaikieb219cfc2011-09-23 05:06:16 +00001753 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Sebastian Redl7f662392008-12-04 22:20:51 +00001754}
1755
1756
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001757/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1758/// delete. These are:
1759/// @code
Sebastian Redl8999fe12011-03-14 18:08:30 +00001760/// // C++03:
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001761/// void* operator new(std::size_t) throw(std::bad_alloc);
1762/// void* operator new[](std::size_t) throw(std::bad_alloc);
1763/// void operator delete(void *) throw();
1764/// void operator delete[](void *) throw();
Sebastian Redl8999fe12011-03-14 18:08:30 +00001765/// // C++0x:
1766/// void* operator new(std::size_t);
1767/// void* operator new[](std::size_t);
1768/// void operator delete(void *);
1769/// void operator delete[](void *);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001770/// @endcode
Sebastian Redl8999fe12011-03-14 18:08:30 +00001771/// C++0x operator delete is implicitly noexcept.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001772/// Note that the placement and nothrow forms of new are *not* implicitly
1773/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001774void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001775 if (GlobalNewDeleteDeclared)
1776 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001777
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001778 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001779 // [...] The following allocation and deallocation functions (18.4) are
1780 // implicitly declared in global scope in each translation unit of a
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001781 // program
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001782 //
Sebastian Redl8999fe12011-03-14 18:08:30 +00001783 // C++03:
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001784 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001785 // void* operator new[](std::size_t) throw(std::bad_alloc);
1786 // void operator delete(void*) throw();
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001787 // void operator delete[](void*) throw();
Sebastian Redl8999fe12011-03-14 18:08:30 +00001788 // C++0x:
1789 // void* operator new(std::size_t);
1790 // void* operator new[](std::size_t);
1791 // void operator delete(void*);
1792 // void operator delete[](void*);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001793 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001794 // These implicit declarations introduce only the function names operator
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001795 // new, operator new[], operator delete, operator delete[].
1796 //
1797 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1798 // "std" or "bad_alloc" as necessary to form the exception specification.
1799 // However, we do not make these implicit declarations visible to name
1800 // lookup.
Sebastian Redl8999fe12011-03-14 18:08:30 +00001801 // Note that the C++0x versions of operator delete are deallocation functions,
1802 // and thus are implicitly noexcept.
David Blaikie4e4d0842012-03-11 07:00:24 +00001803 if (!StdBadAlloc && !getLangOpts().CPlusPlus0x) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001804 // The "std::bad_alloc" class has not yet been declared, so build it
1805 // implicitly.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001806 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1807 getOrCreateStdNamespace(),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001808 SourceLocation(), SourceLocation(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001809 &PP.getIdentifierTable().get("bad_alloc"),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001810 0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001811 getStdBadAlloc()->setImplicit(true);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001812 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001813
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001814 GlobalNewDeleteDeclared = true;
1815
1816 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1817 QualType SizeT = Context.getSizeType();
David Blaikie4e4d0842012-03-11 07:00:24 +00001818 bool AssumeSaneOperatorNew = getLangOpts().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001819
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001820 DeclareGlobalAllocationFunction(
1821 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001822 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001823 DeclareGlobalAllocationFunction(
1824 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001825 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001826 DeclareGlobalAllocationFunction(
1827 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1828 Context.VoidTy, VoidPtr);
1829 DeclareGlobalAllocationFunction(
1830 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1831 Context.VoidTy, VoidPtr);
1832}
1833
1834/// DeclareGlobalAllocationFunction - Declares a single implicit global
1835/// allocation function if it doesn't already exist.
1836void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001837 QualType Return, QualType Argument,
1838 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001839 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1840
1841 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001842 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001843 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001844 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001845 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001846 // Only look at non-template functions, as it is the predefined,
1847 // non-templated allocation function we are trying to declare here.
1848 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1849 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001850 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001851 Func->getParamDecl(0)->getType().getUnqualifiedType());
1852 // FIXME: Do we need to check for default arguments here?
Douglas Gregor7b868622010-08-18 15:06:25 +00001853 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1854 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00001855 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001856 return;
Douglas Gregor7b868622010-08-18 15:06:25 +00001857 }
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001858 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001859 }
1860 }
1861
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001862 QualType BadAllocType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001863 bool HasBadAllocExceptionSpec
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001864 = (Name.getCXXOverloadedOperator() == OO_New ||
1865 Name.getCXXOverloadedOperator() == OO_Array_New);
David Blaikie4e4d0842012-03-11 07:00:24 +00001866 if (HasBadAllocExceptionSpec && !getLangOpts().CPlusPlus0x) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001867 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001868 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001869 }
John McCalle23cf432010-12-14 08:05:40 +00001870
1871 FunctionProtoType::ExtProtoInfo EPI;
John McCalle23cf432010-12-14 08:05:40 +00001872 if (HasBadAllocExceptionSpec) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001873 if (!getLangOpts().CPlusPlus0x) {
Sebastian Redl8999fe12011-03-14 18:08:30 +00001874 EPI.ExceptionSpecType = EST_Dynamic;
1875 EPI.NumExceptions = 1;
1876 EPI.Exceptions = &BadAllocType;
1877 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00001878 } else {
David Blaikie4e4d0842012-03-11 07:00:24 +00001879 EPI.ExceptionSpecType = getLangOpts().CPlusPlus0x ?
Sebastian Redl8999fe12011-03-14 18:08:30 +00001880 EST_BasicNoexcept : EST_DynamicNone;
John McCalle23cf432010-12-14 08:05:40 +00001881 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001882
John McCalle23cf432010-12-14 08:05:40 +00001883 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001884 FunctionDecl *Alloc =
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001885 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
1886 SourceLocation(), Name,
John McCalld931b082010-08-26 03:08:43 +00001887 FnType, /*TInfo=*/0, SC_None,
1888 SC_None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001889 Alloc->setImplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001890
Nuno Lopesfc284482009-12-16 16:59:22 +00001891 if (AddMallocAttr)
Sean Huntcf807c42010-08-18 23:23:40 +00001892 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001893
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001894 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001895 SourceLocation(), 0,
1896 Argument, /*TInfo=*/0,
1897 SC_None, SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00001898 Alloc->setParams(Param);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001899
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001900 // FIXME: Also add this declaration to the IdentifierResolver, but
1901 // make sure it is at the end of the chain to coincide with the
1902 // global scope.
John McCall5f1e0942010-08-24 08:50:51 +00001903 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001904}
1905
Anders Carlsson78f74552009-11-15 18:45:20 +00001906bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1907 DeclarationName Name,
Sean Hunt2be7e902011-05-12 22:46:29 +00001908 FunctionDecl* &Operator, bool Diagnose) {
John McCalla24dc2e2009-11-17 02:14:36 +00001909 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001910 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001911 LookupQualifiedName(Found, RD);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001912
John McCalla24dc2e2009-11-17 02:14:36 +00001913 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001914 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001915
Chandler Carruth23893242010-06-28 00:30:51 +00001916 Found.suppressDiagnostics();
1917
Chris Lattner5f9e2722011-07-23 10:55:15 +00001918 SmallVector<DeclAccessPair,4> Matches;
Anders Carlsson78f74552009-11-15 18:45:20 +00001919 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1920 F != FEnd; ++F) {
Chandler Carruth09556fd2010-08-08 07:04:00 +00001921 NamedDecl *ND = (*F)->getUnderlyingDecl();
1922
1923 // Ignore template operator delete members from the check for a usual
1924 // deallocation function.
1925 if (isa<FunctionTemplateDecl>(ND))
1926 continue;
1927
1928 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall046a7462010-08-04 00:31:26 +00001929 Matches.push_back(F.getPair());
1930 }
1931
1932 // There's exactly one suitable operator; pick it.
1933 if (Matches.size() == 1) {
1934 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
Sean Hunt2be7e902011-05-12 22:46:29 +00001935
1936 if (Operator->isDeleted()) {
1937 if (Diagnose) {
1938 Diag(StartLoc, diag::err_deleted_function_use);
Richard Smith6c4c36c2012-03-30 20:53:28 +00001939 NoteDeletedFunction(Operator);
Sean Hunt2be7e902011-05-12 22:46:29 +00001940 }
1941 return true;
1942 }
1943
Richard Smith9a561d52012-02-26 09:11:52 +00001944 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1945 Matches[0], Diagnose) == AR_inaccessible)
1946 return true;
1947
John McCall046a7462010-08-04 00:31:26 +00001948 return false;
1949
1950 // We found multiple suitable operators; complain about the ambiguity.
1951 } else if (!Matches.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001952 if (Diagnose) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00001953 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1954 << Name << RD;
John McCall046a7462010-08-04 00:31:26 +00001955
Chris Lattner5f9e2722011-07-23 10:55:15 +00001956 for (SmallVectorImpl<DeclAccessPair>::iterator
Sean Huntcb45a0f2011-05-12 22:46:25 +00001957 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1958 Diag((*F)->getUnderlyingDecl()->getLocation(),
1959 diag::note_member_declared_here) << Name;
1960 }
John McCall046a7462010-08-04 00:31:26 +00001961 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001962 }
1963
1964 // We did find operator delete/operator delete[] declarations, but
1965 // none of them were suitable.
1966 if (!Found.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001967 if (Diagnose) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00001968 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1969 << Name << RD;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001970
Sean Huntcb45a0f2011-05-12 22:46:25 +00001971 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1972 F != FEnd; ++F)
1973 Diag((*F)->getUnderlyingDecl()->getLocation(),
1974 diag::note_member_declared_here) << Name;
1975 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001976 return true;
1977 }
1978
1979 // Look for a global declaration.
1980 DeclareGlobalNewDelete();
1981 DeclContext *TUDecl = Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001982
Anders Carlsson78f74552009-11-15 18:45:20 +00001983 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1984 Expr* DeallocArgs[1];
1985 DeallocArgs[0] = &Null;
1986 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
Sean Hunt2be7e902011-05-12 22:46:29 +00001987 DeallocArgs, 1, TUDecl, !Diagnose,
1988 Operator, Diagnose))
Anders Carlsson78f74552009-11-15 18:45:20 +00001989 return true;
1990
1991 assert(Operator && "Did not find a deallocation function!");
1992 return false;
1993}
1994
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001995/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1996/// @code ::delete ptr; @endcode
1997/// or
1998/// @code delete [] ptr; @endcode
John McCall60d7b3a2010-08-24 06:29:42 +00001999ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002000Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley429bb272011-04-08 18:41:53 +00002001 bool ArrayForm, Expr *ExE) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00002002 // C++ [expr.delete]p1:
2003 // The operand shall have a pointer type, or a class type having a single
2004 // conversion function to a pointer type. The result has type void.
2005 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002006 // DR599 amends "pointer type" to "pointer to object type" in both cases.
2007
John Wiegley429bb272011-04-08 18:41:53 +00002008 ExprResult Ex = Owned(ExE);
Anders Carlssond67c4c32009-08-16 20:29:29 +00002009 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00002010 bool ArrayFormAsWritten = ArrayForm;
John McCall6ec278d2011-01-27 09:37:56 +00002011 bool UsualArrayDeleteWantsSize = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002012
John Wiegley429bb272011-04-08 18:41:53 +00002013 if (!Ex.get()->isTypeDependent()) {
John McCall5aba3eb2012-03-09 04:08:29 +00002014 // Perform lvalue-to-rvalue cast, if needed.
2015 Ex = DefaultLvalueConversion(Ex.take());
2016
John Wiegley429bb272011-04-08 18:41:53 +00002017 QualType Type = Ex.get()->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002018
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00002019 if (const RecordType *Record = Type->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002020 if (RequireCompleteType(StartLoc, Type,
Douglas Gregor254a9422010-07-29 14:44:35 +00002021 PDiag(diag::err_delete_incomplete_class_type)))
2022 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002023
Chris Lattner5f9e2722011-07-23 10:55:15 +00002024 SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
John McCall32daa422010-03-31 01:36:47 +00002025
Fariborz Jahanian53462782009-09-11 21:44:33 +00002026 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002027 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002028 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00002029 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00002030 NamedDecl *D = I.getDecl();
2031 if (isa<UsingShadowDecl>(D))
2032 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2033
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00002034 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00002035 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00002036 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002037
John McCall32daa422010-03-31 01:36:47 +00002038 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002039
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00002040 QualType ConvType = Conv->getConversionType().getNonReferenceType();
2041 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedman13578692010-08-05 02:49:48 +00002042 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00002043 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00002044 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00002045 if (ObjectPtrConversions.size() == 1) {
2046 // We have a single conversion to a pointer-to-object type. Perform
2047 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00002048 // TODO: don't redo the conversion calculation.
John Wiegley429bb272011-04-08 18:41:53 +00002049 ExprResult Res =
2050 PerformImplicitConversion(Ex.get(),
John McCall32daa422010-03-31 01:36:47 +00002051 ObjectPtrConversions.front()->getConversionType(),
John Wiegley429bb272011-04-08 18:41:53 +00002052 AA_Converting);
2053 if (Res.isUsable()) {
2054 Ex = move(Res);
2055 Type = Ex.get()->getType();
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00002056 }
2057 }
2058 else if (ObjectPtrConversions.size() > 1) {
2059 Diag(StartLoc, diag::err_ambiguous_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00002060 << Type << Ex.get()->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00002061 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
2062 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00002063 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00002064 }
Sebastian Redl28507842009-02-26 14:39:58 +00002065 }
2066
Sebastian Redlf53597f2009-03-15 17:47:39 +00002067 if (!Type->isPointerType())
2068 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00002069 << Type << Ex.get()->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00002070
Ted Kremenek6217b802009-07-29 21:53:49 +00002071 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmane52c9142011-07-26 22:25:31 +00002072 QualType PointeeElem = Context.getBaseElementType(Pointee);
2073
2074 if (unsigned AddressSpace = Pointee.getAddressSpace())
2075 return Diag(Ex.get()->getLocStart(),
2076 diag::err_address_space_qualified_delete)
2077 << Pointee.getUnqualifiedType() << AddressSpace;
2078
2079 CXXRecordDecl *PointeeRD = 0;
Douglas Gregor94a61572010-05-24 17:01:56 +00002080 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002081 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregor94a61572010-05-24 17:01:56 +00002082 // effectively bans deletion of "void*". However, most compilers support
2083 // this, so we treat it as a warning unless we're in a SFINAE context.
2084 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley429bb272011-04-08 18:41:53 +00002085 << Type << Ex.get()->getSourceRange();
Eli Friedmane52c9142011-07-26 22:25:31 +00002086 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00002087 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00002088 << Type << Ex.get()->getSourceRange());
Eli Friedmane52c9142011-07-26 22:25:31 +00002089 } else if (!Pointee->isDependentType()) {
2090 if (!RequireCompleteType(StartLoc, Pointee,
2091 PDiag(diag::warn_delete_incomplete)
2092 << Ex.get()->getSourceRange())) {
2093 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
2094 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
2095 }
2096 }
2097
Douglas Gregor1070c9f2009-09-29 21:38:53 +00002098 // C++ [expr.delete]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002099 // [Note: a pointer to a const type can be the operand of a
2100 // delete-expression; it is not necessary to cast away the constness
2101 // (5.2.11) of the pointer expression before it is used as the operand
Douglas Gregor1070c9f2009-09-29 21:38:53 +00002102 // of the delete-expression. ]
John McCallf85e1932011-06-15 23:02:42 +00002103 if (!Context.hasSameType(Ex.get()->getType(), Context.VoidPtrTy))
Abramo Bagnara30bb4202011-11-16 15:42:13 +00002104 Ex = Owned(ImplicitCastExpr::Create(Context, Context.VoidPtrTy,
2105 CK_BitCast, Ex.take(), 0, VK_RValue));
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00002106
2107 if (Pointee->isArrayType() && !ArrayForm) {
2108 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley429bb272011-04-08 18:41:53 +00002109 << Type << Ex.get()->getSourceRange()
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00002110 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
2111 ArrayForm = true;
2112 }
2113
Anders Carlssond67c4c32009-08-16 20:29:29 +00002114 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2115 ArrayForm ? OO_Array_Delete : OO_Delete);
2116
Eli Friedmane52c9142011-07-26 22:25:31 +00002117 if (PointeeRD) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002118 if (!UseGlobal &&
Eli Friedmane52c9142011-07-26 22:25:31 +00002119 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
2120 OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00002121 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002122
John McCall6ec278d2011-01-27 09:37:56 +00002123 // If we're allocating an array of records, check whether the
2124 // usual operator delete[] has a size_t parameter.
2125 if (ArrayForm) {
2126 // If the user specifically asked to use the global allocator,
2127 // we'll need to do the lookup into the class.
2128 if (UseGlobal)
2129 UsualArrayDeleteWantsSize =
2130 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
2131
2132 // Otherwise, the usual operator delete[] should be the
2133 // function we just found.
2134 else if (isa<CXXMethodDecl>(OperatorDelete))
2135 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
2136 }
2137
Richard Smith213d70b2012-02-18 04:13:32 +00002138 if (!PointeeRD->hasIrrelevantDestructor())
Eli Friedmane52c9142011-07-26 22:25:31 +00002139 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00002140 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002141 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor9b623632010-10-12 23:32:35 +00002142 DiagnoseUseOfDecl(Dtor, StartLoc);
2143 }
Argyrios Kyrtzidis6f0074a2011-05-24 19:53:26 +00002144
2145 // C++ [expr.delete]p3:
2146 // In the first alternative (delete object), if the static type of the
2147 // object to be deleted is different from its dynamic type, the static
2148 // type shall be a base class of the dynamic type of the object to be
2149 // deleted and the static type shall have a virtual destructor or the
2150 // behavior is undefined.
2151 //
2152 // Note: a final class cannot be derived from, no issue there
Eli Friedmanef8c79c2011-07-26 23:27:24 +00002153 if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) {
Eli Friedmane52c9142011-07-26 22:25:31 +00002154 CXXDestructorDecl *dtor = PointeeRD->getDestructor();
Eli Friedmanef8c79c2011-07-26 23:27:24 +00002155 if (dtor && !dtor->isVirtual()) {
2156 if (PointeeRD->isAbstract()) {
2157 // If the class is abstract, we warn by default, because we're
2158 // sure the code has undefined behavior.
2159 Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor)
2160 << PointeeElem;
2161 } else if (!ArrayForm) {
2162 // Otherwise, if this is not an array delete, it's a bit suspect,
2163 // but not necessarily wrong.
2164 Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
2165 }
2166 }
Argyrios Kyrtzidis6f0074a2011-05-24 19:53:26 +00002167 }
John McCallf85e1932011-06-15 23:02:42 +00002168
David Blaikie4e4d0842012-03-11 07:00:24 +00002169 } else if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002170 PointeeElem->isObjCLifetimeType() &&
2171 (PointeeElem.getObjCLifetime() == Qualifiers::OCL_Strong ||
2172 PointeeElem.getObjCLifetime() == Qualifiers::OCL_Weak) &&
2173 ArrayForm) {
2174 Diag(StartLoc, diag::warn_err_new_delete_object_array)
2175 << 1 << PointeeElem;
Anders Carlssond67c4c32009-08-16 20:29:29 +00002176 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002177
Anders Carlssond67c4c32009-08-16 20:29:29 +00002178 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00002179 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00002180 DeclareGlobalNewDelete();
2181 DeclContext *TUDecl = Context.getTranslationUnitDecl();
John Wiegley429bb272011-04-08 18:41:53 +00002182 Expr *Arg = Ex.get();
Mike Stump1eb44332009-09-09 15:08:12 +00002183 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
John Wiegley429bb272011-04-08 18:41:53 +00002184 &Arg, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00002185 OperatorDelete))
2186 return ExprError();
2187 }
Mike Stump1eb44332009-09-09 15:08:12 +00002188
Eli Friedman5f2987c2012-02-02 03:46:19 +00002189 MarkFunctionReferenced(StartLoc, OperatorDelete);
John McCall6ec278d2011-01-27 09:37:56 +00002190
Douglas Gregord880f522011-02-01 15:50:11 +00002191 // Check access and ambiguity of operator delete and destructor.
Eli Friedmane52c9142011-07-26 22:25:31 +00002192 if (PointeeRD) {
2193 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
John Wiegley429bb272011-04-08 18:41:53 +00002194 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregord880f522011-02-01 15:50:11 +00002195 PDiag(diag::err_access_dtor) << PointeeElem);
2196 }
2197 }
2198
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002199 }
2200
Sebastian Redlf53597f2009-03-15 17:47:39 +00002201 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
John McCall6ec278d2011-01-27 09:37:56 +00002202 ArrayFormAsWritten,
2203 UsualArrayDeleteWantsSize,
John Wiegley429bb272011-04-08 18:41:53 +00002204 OperatorDelete, Ex.take(), StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002205}
2206
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002207/// \brief Check the use of the given variable as a C++ condition in an if,
2208/// while, do-while, or switch statement.
John McCall60d7b3a2010-08-24 06:29:42 +00002209ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCallf89e55a2010-11-18 06:31:45 +00002210 SourceLocation StmtLoc,
2211 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002212 QualType T = ConditionVar->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002213
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002214 // C++ [stmt.select]p2:
2215 // The declarator shall not specify a function or an array.
2216 if (T->isFunctionType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002217 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002218 diag::err_invalid_use_of_function_type)
2219 << ConditionVar->getSourceRange());
2220 else if (T->isArrayType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002221 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002222 diag::err_invalid_use_of_array_type)
2223 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00002224
John Wiegley429bb272011-04-08 18:41:53 +00002225 ExprResult Condition =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002226 Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2227 SourceLocation(),
2228 ConditionVar,
John McCallf4b88a42012-03-10 09:33:50 +00002229 /*enclosing*/ false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002230 ConditionVar->getLocation(),
2231 ConditionVar->getType().getNonReferenceType(),
John Wiegley429bb272011-04-08 18:41:53 +00002232 VK_LValue));
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002233
Eli Friedman5f2987c2012-02-02 03:46:19 +00002234 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002235
John Wiegley429bb272011-04-08 18:41:53 +00002236 if (ConvertToBoolean) {
2237 Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
2238 if (Condition.isInvalid())
2239 return ExprError();
2240 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002241
John Wiegley429bb272011-04-08 18:41:53 +00002242 return move(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002243}
2244
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002245/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
John Wiegley429bb272011-04-08 18:41:53 +00002246ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002247 // C++ 6.4p4:
2248 // The value of a condition that is an initialized declaration in a statement
2249 // other than a switch statement is the value of the declared variable
2250 // implicitly converted to type bool. If that conversion is ill-formed, the
2251 // program is ill-formed.
2252 // The value of a condition that is an expression is the value of the
2253 // expression, implicitly converted to bool.
2254 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002255 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002256}
Douglas Gregor77a52232008-09-12 00:47:35 +00002257
2258/// Helper function to determine whether this is the (deprecated) C++
2259/// conversion from a string literal to a pointer to non-const char or
2260/// non-const wchar_t (for narrow and wide string literals,
2261/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00002262bool
Douglas Gregor77a52232008-09-12 00:47:35 +00002263Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
2264 // Look inside the implicit cast, if it exists.
2265 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
2266 From = Cast->getSubExpr();
2267
2268 // A string literal (2.13.4) that is not a wide string literal can
2269 // be converted to an rvalue of type "pointer to char"; a wide
2270 // string literal can be converted to an rvalue of type "pointer
2271 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00002272 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00002273 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00002274 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00002275 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00002276 // This conversion is considered only when there is an
2277 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregor5cee1192011-07-27 05:40:30 +00002278 if (!ToPtrType->getPointeeType().hasQualifiers()) {
2279 switch (StrLit->getKind()) {
2280 case StringLiteral::UTF8:
2281 case StringLiteral::UTF16:
2282 case StringLiteral::UTF32:
2283 // We don't allow UTF literals to be implicitly converted
2284 break;
2285 case StringLiteral::Ascii:
2286 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
2287 ToPointeeType->getKind() == BuiltinType::Char_S);
2288 case StringLiteral::Wide:
2289 return ToPointeeType->isWideCharType();
2290 }
2291 }
Douglas Gregor77a52232008-09-12 00:47:35 +00002292 }
2293
2294 return false;
2295}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002296
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002297static ExprResult BuildCXXCastArgument(Sema &S,
John McCall2de56d12010-08-25 11:45:40 +00002298 SourceLocation CastLoc,
2299 QualType Ty,
2300 CastKind Kind,
2301 CXXMethodDecl *Method,
John McCallca82a822011-09-21 08:36:56 +00002302 DeclAccessPair FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002303 bool HadMultipleCandidates,
John McCall2de56d12010-08-25 11:45:40 +00002304 Expr *From) {
Douglas Gregorba70ab62010-04-16 22:17:36 +00002305 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002306 default: llvm_unreachable("Unhandled cast kind!");
John McCall2de56d12010-08-25 11:45:40 +00002307 case CK_ConstructorConversion: {
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002308 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
John McCallca0408f2010-08-23 06:44:23 +00002309 ASTOwningVector<Expr*> ConstructorArgs(S);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002310
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002311 if (S.CompleteConstructorCall(Constructor,
John McCallf312b1e2010-08-26 23:41:50 +00002312 MultiExprArg(&From, 1),
Douglas Gregorba70ab62010-04-16 22:17:36 +00002313 CastLoc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00002314 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002315
John McCallb9abd8722012-04-07 03:04:20 +00002316 S.CheckConstructorAccess(CastLoc, Constructor,
2317 InitializedEntity::InitializeTemporary(Ty),
2318 Constructor->getAccess());
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002319
2320 ExprResult Result
2321 = S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2322 move_arg(ConstructorArgs),
2323 HadMultipleCandidates, /*ZeroInit*/ false,
2324 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregorba70ab62010-04-16 22:17:36 +00002325 if (Result.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00002326 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002327
Douglas Gregorba70ab62010-04-16 22:17:36 +00002328 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
2329 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002330
John McCall2de56d12010-08-25 11:45:40 +00002331 case CK_UserDefinedConversion: {
Douglas Gregorba70ab62010-04-16 22:17:36 +00002332 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002333
Douglas Gregorba70ab62010-04-16 22:17:36 +00002334 // Create an implicit call expr that calls it.
Eli Friedman3f01c8a2012-03-01 01:30:04 +00002335 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
2336 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002337 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00002338 if (Result.isInvalid())
2339 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00002340 // Record usage of conversion in an implicit cast.
2341 Result = S.Owned(ImplicitCastExpr::Create(S.Context,
2342 Result.get()->getType(),
2343 CK_UserDefinedConversion,
2344 Result.get(), 0,
2345 Result.get()->getValueKind()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002346
John McCallca82a822011-09-21 08:36:56 +00002347 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ 0, FoundDecl);
2348
Douglas Gregorf2ae5262011-01-20 00:18:04 +00002349 return S.MaybeBindToTemporary(Result.get());
Douglas Gregorba70ab62010-04-16 22:17:36 +00002350 }
2351 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002352}
Douglas Gregorba70ab62010-04-16 22:17:36 +00002353
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002354/// PerformImplicitConversion - Perform an implicit conversion of the
2355/// expression From to the type ToType using the pre-computed implicit
John Wiegley429bb272011-04-08 18:41:53 +00002356/// conversion sequence ICS. Returns the converted
Douglas Gregor68647482009-12-16 03:45:30 +00002357/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002358/// used in the error message.
John Wiegley429bb272011-04-08 18:41:53 +00002359ExprResult
2360Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002361 const ImplicitConversionSequence &ICS,
John McCallf85e1932011-06-15 23:02:42 +00002362 AssignmentAction Action,
2363 CheckedConversionKind CCK) {
John McCall1d318332010-01-12 00:44:57 +00002364 switch (ICS.getKind()) {
John Wiegley429bb272011-04-08 18:41:53 +00002365 case ImplicitConversionSequence::StandardConversion: {
Richard Smithc8d7f582011-11-29 22:48:16 +00002366 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
2367 Action, CCK);
John Wiegley429bb272011-04-08 18:41:53 +00002368 if (Res.isInvalid())
2369 return ExprError();
2370 From = Res.take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002371 break;
John Wiegley429bb272011-04-08 18:41:53 +00002372 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002373
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002374 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002375
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00002376 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCalldaa8e4e2010-11-15 09:13:47 +00002377 CastKind CastKind;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002378 QualType BeforeToType;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00002379 assert(FD && "FIXME: aggregate initialization from init list");
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002380 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCall2de56d12010-08-25 11:45:40 +00002381 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002382
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002383 // If the user-defined conversion is specified by a conversion function,
2384 // the initial standard conversion sequence converts the source type to
2385 // the implicit object parameter of the conversion function.
2386 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCall9ec94452010-12-04 09:57:16 +00002387 } else {
2388 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCall2de56d12010-08-25 11:45:40 +00002389 CastKind = CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002390 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00002391 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002392 // If the user-defined conversion is specified by a constructor, the
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002393 // initial standard conversion sequence converts the source type to the
2394 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00002395 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
2396 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002397 }
Douglas Gregora3998bd2010-12-02 21:47:04 +00002398 // Watch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00002399 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley429bb272011-04-08 18:41:53 +00002400 ExprResult Res =
Richard Smithc8d7f582011-11-29 22:48:16 +00002401 PerformImplicitConversion(From, BeforeToType,
2402 ICS.UserDefined.Before, AA_Converting,
2403 CCK);
John Wiegley429bb272011-04-08 18:41:53 +00002404 if (Res.isInvalid())
2405 return ExprError();
2406 From = Res.take();
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002407 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002408
2409 ExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00002410 = BuildCXXCastArgument(*this,
2411 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00002412 ToType.getNonReferenceType(),
Douglas Gregor83eecbe2011-01-20 01:32:05 +00002413 CastKind, cast<CXXMethodDecl>(FD),
2414 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002415 ICS.UserDefined.HadMultipleCandidates,
John McCall9ae2f072010-08-23 23:25:46 +00002416 From);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002417
2418 if (CastArg.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00002419 return ExprError();
Eli Friedmand8889622009-11-27 04:41:50 +00002420
John Wiegley429bb272011-04-08 18:41:53 +00002421 From = CastArg.take();
Eli Friedmand8889622009-11-27 04:41:50 +00002422
Richard Smithc8d7f582011-11-29 22:48:16 +00002423 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
2424 AA_Converting, CCK);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00002425 }
John McCall1d318332010-01-12 00:44:57 +00002426
2427 case ImplicitConversionSequence::AmbiguousConversion:
John McCall120d63c2010-08-24 20:38:10 +00002428 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall1d318332010-01-12 00:44:57 +00002429 PDiag(diag::err_typecheck_ambiguous_condition)
2430 << From->getSourceRange());
John Wiegley429bb272011-04-08 18:41:53 +00002431 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002432
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002433 case ImplicitConversionSequence::EllipsisConversion:
David Blaikieb219cfc2011-09-23 05:06:16 +00002434 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002435
2436 case ImplicitConversionSequence::BadConversion:
John Wiegley429bb272011-04-08 18:41:53 +00002437 return ExprError();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002438 }
2439
2440 // Everything went well.
John Wiegley429bb272011-04-08 18:41:53 +00002441 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002442}
2443
Richard Smithc8d7f582011-11-29 22:48:16 +00002444/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002445/// expression From to the type ToType by following the standard
John Wiegley429bb272011-04-08 18:41:53 +00002446/// conversion sequence SCS. Returns the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00002447/// expression. Flavor is the context in which we're performing this
2448/// conversion, for use in error messages.
John Wiegley429bb272011-04-08 18:41:53 +00002449ExprResult
Richard Smithc8d7f582011-11-29 22:48:16 +00002450Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00002451 const StandardConversionSequence& SCS,
John McCallf85e1932011-06-15 23:02:42 +00002452 AssignmentAction Action,
2453 CheckedConversionKind CCK) {
2454 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
2455
Mike Stump390b4cc2009-05-16 07:39:55 +00002456 // Overall FIXME: we are recomputing too many types here and doing far too
2457 // much extra work. What this means is that we need to keep track of more
2458 // information that is computed when we try the implicit conversion initially,
2459 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002460 QualType FromType = From->getType();
John McCallf85e1932011-06-15 23:02:42 +00002461
Douglas Gregor225c41e2008-11-03 19:09:14 +00002462 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00002463 // FIXME: When can ToType be a reference type?
2464 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002465 if (SCS.Second == ICK_Derived_To_Base) {
John McCallca0408f2010-08-23 06:44:23 +00002466 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002467 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCallca0408f2010-08-23 06:44:23 +00002468 MultiExprArg(*this, &From, 1),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002469 /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002470 ConstructorArgs))
John Wiegley429bb272011-04-08 18:41:53 +00002471 return ExprError();
2472 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2473 ToType, SCS.CopyConstructor,
2474 move_arg(ConstructorArgs),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002475 /*HadMultipleCandidates*/ false,
John Wiegley429bb272011-04-08 18:41:53 +00002476 /*ZeroInit*/ false,
2477 CXXConstructExpr::CK_Complete,
2478 SourceRange());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002479 }
John Wiegley429bb272011-04-08 18:41:53 +00002480 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2481 ToType, SCS.CopyConstructor,
2482 MultiExprArg(*this, &From, 1),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002483 /*HadMultipleCandidates*/ false,
John Wiegley429bb272011-04-08 18:41:53 +00002484 /*ZeroInit*/ false,
2485 CXXConstructExpr::CK_Complete,
2486 SourceRange());
Douglas Gregor225c41e2008-11-03 19:09:14 +00002487 }
2488
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002489 // Resolve overloaded function references.
2490 if (Context.hasSameType(FromType, Context.OverloadTy)) {
2491 DeclAccessPair Found;
2492 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2493 true, Found);
2494 if (!Fn)
John Wiegley429bb272011-04-08 18:41:53 +00002495 return ExprError();
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002496
Daniel Dunbar96a00142012-03-09 18:35:03 +00002497 if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
John Wiegley429bb272011-04-08 18:41:53 +00002498 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002499
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002500 From = FixOverloadedFunctionReference(From, Found, Fn);
2501 FromType = From->getType();
2502 }
2503
Richard Smithc8d7f582011-11-29 22:48:16 +00002504 // Perform the first implicit conversion.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002505 switch (SCS.First) {
2506 case ICK_Identity:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002507 // Nothing to do.
2508 break;
2509
Eli Friedmand814eaf2012-01-24 22:51:26 +00002510 case ICK_Lvalue_To_Rvalue: {
John McCall3c3b7f92011-10-25 17:37:35 +00002511 assert(From->getObjectKind() != OK_ObjCProperty);
John McCallf6a16482010-12-04 03:47:34 +00002512 FromType = FromType.getUnqualifiedType();
Eli Friedmand814eaf2012-01-24 22:51:26 +00002513 ExprResult FromRes = DefaultLvalueConversion(From);
2514 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
2515 From = FromRes.take();
John McCallf6a16482010-12-04 03:47:34 +00002516 break;
Eli Friedmand814eaf2012-01-24 22:51:26 +00002517 }
John McCallf6a16482010-12-04 03:47:34 +00002518
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002519 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002520 FromType = Context.getArrayDecayedType(FromType);
Richard Smithc8d7f582011-11-29 22:48:16 +00002521 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
2522 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002523 break;
2524
2525 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002526 FromType = Context.getPointerType(FromType);
Richard Smithc8d7f582011-11-29 22:48:16 +00002527 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
2528 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002529 break;
2530
2531 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002532 llvm_unreachable("Improper first standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002533 }
2534
Richard Smithc8d7f582011-11-29 22:48:16 +00002535 // Perform the second implicit conversion
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002536 switch (SCS.Second) {
2537 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002538 // If both sides are functions (or pointers/references to them), there could
2539 // be incompatible exception declarations.
2540 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002541 return ExprError();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002542 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002543 break;
2544
Douglas Gregor43c79c22009-12-09 00:47:37 +00002545 case ICK_NoReturn_Adjustment:
2546 // If both sides are functions (or pointers/references to them), there could
2547 // be incompatible exception declarations.
2548 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002549 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002550
Richard Smithc8d7f582011-11-29 22:48:16 +00002551 From = ImpCastExprToType(From, ToType, CK_NoOp,
2552 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor43c79c22009-12-09 00:47:37 +00002553 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002554
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002555 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002556 case ICK_Integral_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002557 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
2558 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002559 break;
2560
2561 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002562 case ICK_Floating_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002563 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
2564 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002565 break;
2566
2567 case ICK_Complex_Promotion:
John McCalldaa8e4e2010-11-15 09:13:47 +00002568 case ICK_Complex_Conversion: {
2569 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2570 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2571 CastKind CK;
2572 if (FromEl->isRealFloatingType()) {
2573 if (ToEl->isRealFloatingType())
2574 CK = CK_FloatingComplexCast;
2575 else
2576 CK = CK_FloatingComplexToIntegralComplex;
2577 } else if (ToEl->isRealFloatingType()) {
2578 CK = CK_IntegralComplexToFloatingComplex;
2579 } else {
2580 CK = CK_IntegralComplexCast;
2581 }
Richard Smithc8d7f582011-11-29 22:48:16 +00002582 From = ImpCastExprToType(From, ToType, CK,
2583 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002584 break;
John McCalldaa8e4e2010-11-15 09:13:47 +00002585 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00002586
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002587 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00002588 if (ToType->isRealFloatingType())
Richard Smithc8d7f582011-11-29 22:48:16 +00002589 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
2590 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002591 else
Richard Smithc8d7f582011-11-29 22:48:16 +00002592 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
2593 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002594 break;
2595
Douglas Gregorf9201e02009-02-11 23:02:49 +00002596 case ICK_Compatible_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002597 From = ImpCastExprToType(From, ToType, CK_NoOp,
2598 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002599 break;
2600
John McCallf85e1932011-06-15 23:02:42 +00002601 case ICK_Writeback_Conversion:
Anders Carlsson61faec12009-09-12 04:46:44 +00002602 case ICK_Pointer_Conversion: {
Douglas Gregora3998bd2010-12-02 21:47:04 +00002603 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor45920e82008-12-19 17:40:08 +00002604 // Diagnose incompatible Objective-C conversions
Douglas Gregor8cf0d222011-06-11 04:42:12 +00002605 if (Action == AA_Initializing || Action == AA_Assigning)
Daniel Dunbar96a00142012-03-09 18:35:03 +00002606 Diag(From->getLocStart(),
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002607 diag::ext_typecheck_convert_incompatible_pointer)
2608 << ToType << From->getType() << Action
Anna Zaks67221552011-07-28 19:51:27 +00002609 << From->getSourceRange() << 0;
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002610 else
Daniel Dunbar96a00142012-03-09 18:35:03 +00002611 Diag(From->getLocStart(),
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002612 diag::ext_typecheck_convert_incompatible_pointer)
2613 << From->getType() << ToType << Action
Anna Zaks67221552011-07-28 19:51:27 +00002614 << From->getSourceRange() << 0;
John McCallf85e1932011-06-15 23:02:42 +00002615
Douglas Gregor926df6c2011-06-11 01:09:30 +00002616 if (From->getType()->isObjCObjectPointerType() &&
2617 ToType->isObjCObjectPointerType())
2618 EmitRelatedResultTypeNote(From);
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002619 }
David Blaikie4e4d0842012-03-11 07:00:24 +00002620 else if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002621 !CheckObjCARCUnavailableWeakConversion(ToType,
2622 From->getType())) {
John McCall7f3a6d32011-09-09 06:12:06 +00002623 if (Action == AA_Initializing)
Daniel Dunbar96a00142012-03-09 18:35:03 +00002624 Diag(From->getLocStart(),
John McCall7f3a6d32011-09-09 06:12:06 +00002625 diag::err_arc_weak_unavailable_assign);
2626 else
Daniel Dunbar96a00142012-03-09 18:35:03 +00002627 Diag(From->getLocStart(),
John McCall7f3a6d32011-09-09 06:12:06 +00002628 diag::err_arc_convesion_of_weak_unavailable)
2629 << (Action == AA_Casting) << From->getType() << ToType
2630 << From->getSourceRange();
2631 }
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002632
John McCalldaa8e4e2010-11-15 09:13:47 +00002633 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002634 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002635 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002636 return ExprError();
John McCalldc05b112011-09-10 01:16:55 +00002637
2638 // Make sure we extend blocks if necessary.
2639 // FIXME: doing this here is really ugly.
2640 if (Kind == CK_BlockPointerToObjCPointerCast) {
2641 ExprResult E = From;
2642 (void) PrepareCastToObjCObjectPointer(E);
2643 From = E.take();
2644 }
2645
Richard Smithc8d7f582011-11-29 22:48:16 +00002646 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2647 .take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002648 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00002649 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002650
Anders Carlsson61faec12009-09-12 04:46:44 +00002651 case ICK_Pointer_Member: {
John McCalldaa8e4e2010-11-15 09:13:47 +00002652 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002653 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002654 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002655 return ExprError();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002656 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002657 return ExprError();
Richard Smithc8d7f582011-11-29 22:48:16 +00002658 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2659 .take();
Anders Carlsson61faec12009-09-12 04:46:44 +00002660 break;
2661 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002662
Abramo Bagnara737d5442011-04-07 09:26:19 +00002663 case ICK_Boolean_Conversion:
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00002664 // Perform half-to-boolean conversion via float.
2665 if (From->getType()->isHalfType()) {
2666 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).take();
2667 FromType = Context.FloatTy;
2668 }
2669
Richard Smithc8d7f582011-11-29 22:48:16 +00002670 From = ImpCastExprToType(From, Context.BoolTy,
2671 ScalarTypeToBooleanCastKind(FromType),
2672 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002673 break;
2674
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002675 case ICK_Derived_To_Base: {
John McCallf871d0c2010-08-07 06:22:56 +00002676 CXXCastPath BasePath;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002677 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002678 ToType.getNonReferenceType(),
2679 From->getLocStart(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002680 From->getSourceRange(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002681 &BasePath,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002682 CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002683 return ExprError();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002684
Richard Smithc8d7f582011-11-29 22:48:16 +00002685 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
2686 CK_DerivedToBase, From->getValueKind(),
2687 &BasePath, CCK).take();
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002688 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002689 }
2690
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002691 case ICK_Vector_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002692 From = ImpCastExprToType(From, ToType, CK_BitCast,
2693 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002694 break;
2695
2696 case ICK_Vector_Splat:
Richard Smithc8d7f582011-11-29 22:48:16 +00002697 From = ImpCastExprToType(From, ToType, CK_VectorSplat,
2698 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002699 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002700
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002701 case ICK_Complex_Real:
John McCalldaa8e4e2010-11-15 09:13:47 +00002702 // Case 1. x -> _Complex y
2703 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2704 QualType ElType = ToComplex->getElementType();
2705 bool isFloatingComplex = ElType->isRealFloatingType();
2706
2707 // x -> y
2708 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2709 // do nothing
2710 } else if (From->getType()->isRealFloatingType()) {
Richard Smithc8d7f582011-11-29 22:48:16 +00002711 From = ImpCastExprToType(From, ElType,
2712 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002713 } else {
2714 assert(From->getType()->isIntegerType());
Richard Smithc8d7f582011-11-29 22:48:16 +00002715 From = ImpCastExprToType(From, ElType,
2716 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002717 }
2718 // y -> _Complex y
Richard Smithc8d7f582011-11-29 22:48:16 +00002719 From = ImpCastExprToType(From, ToType,
2720 isFloatingComplex ? CK_FloatingRealToComplex
2721 : CK_IntegralRealToComplex).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002722
2723 // Case 2. _Complex x -> y
2724 } else {
2725 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2726 assert(FromComplex);
2727
2728 QualType ElType = FromComplex->getElementType();
2729 bool isFloatingComplex = ElType->isRealFloatingType();
2730
2731 // _Complex x -> x
Richard Smithc8d7f582011-11-29 22:48:16 +00002732 From = ImpCastExprToType(From, ElType,
2733 isFloatingComplex ? CK_FloatingComplexToReal
2734 : CK_IntegralComplexToReal,
2735 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002736
2737 // x -> y
2738 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2739 // do nothing
2740 } else if (ToType->isRealFloatingType()) {
Richard Smithc8d7f582011-11-29 22:48:16 +00002741 From = ImpCastExprToType(From, ToType,
2742 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
2743 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002744 } else {
2745 assert(ToType->isIntegerType());
Richard Smithc8d7f582011-11-29 22:48:16 +00002746 From = ImpCastExprToType(From, ToType,
2747 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
2748 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002749 }
2750 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002751 break;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002752
2753 case ICK_Block_Pointer_Conversion: {
Richard Smithc8d7f582011-11-29 22:48:16 +00002754 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
2755 VK_RValue, /*BasePath=*/0, CCK).take();
John McCallf85e1932011-06-15 23:02:42 +00002756 break;
2757 }
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002758
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002759 case ICK_TransparentUnionConversion: {
John Wiegley429bb272011-04-08 18:41:53 +00002760 ExprResult FromRes = Owned(From);
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002761 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00002762 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
2763 if (FromRes.isInvalid())
2764 return ExprError();
2765 From = FromRes.take();
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002766 assert ((ConvTy == Sema::Compatible) &&
2767 "Improper transparent union conversion");
2768 (void)ConvTy;
2769 break;
2770 }
2771
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002772 case ICK_Lvalue_To_Rvalue:
2773 case ICK_Array_To_Pointer:
2774 case ICK_Function_To_Pointer:
2775 case ICK_Qualification:
2776 case ICK_Num_Conversion_Kinds:
David Blaikieb219cfc2011-09-23 05:06:16 +00002777 llvm_unreachable("Improper second standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002778 }
2779
2780 switch (SCS.Third) {
2781 case ICK_Identity:
2782 // Nothing to do.
2783 break;
2784
Sebastian Redl906082e2010-07-20 04:20:21 +00002785 case ICK_Qualification: {
2786 // The qualification keeps the category of the inner expression, unless the
2787 // target type isn't a reference.
John McCall5baba9d2010-08-25 10:28:54 +00002788 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00002789 From->getValueKind() : VK_RValue;
Richard Smithc8d7f582011-11-29 22:48:16 +00002790 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
2791 CK_NoOp, VK, /*BasePath=*/0, CCK).take();
Douglas Gregora9bff302010-02-28 18:30:25 +00002792
Douglas Gregor069a6da2011-03-14 16:13:32 +00002793 if (SCS.DeprecatedStringLiteralToCharPtr &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002794 !getLangOpts().WritableStrings)
Douglas Gregora9bff302010-02-28 18:30:25 +00002795 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2796 << ToType.getNonReferenceType();
2797
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002798 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002799 }
2800
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002801 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002802 llvm_unreachable("Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002803 }
2804
Douglas Gregor47bfcca2012-04-12 20:42:30 +00002805 // If this conversion sequence involved a scalar -> atomic conversion, perform
2806 // that conversion now.
2807 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>())
2808 if (Context.hasSameType(ToAtomic->getValueType(), From->getType()))
2809 From = ImpCastExprToType(From, ToType, CK_NonAtomicToAtomic, VK_RValue, 0,
2810 CCK).take();
2811
John Wiegley429bb272011-04-08 18:41:53 +00002812 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002813}
2814
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002815ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002816 SourceLocation KWLoc,
2817 ParsedType Ty,
2818 SourceLocation RParen) {
2819 TypeSourceInfo *TSInfo;
2820 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002821
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002822 if (!TSInfo)
2823 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002824 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002825}
2826
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002827/// \brief Check the completeness of a type in a unary type trait.
2828///
2829/// If the particular type trait requires a complete type, tries to complete
2830/// it. If completing the type fails, a diagnostic is emitted and false
2831/// returned. If completing the type succeeds or no completion was required,
2832/// returns true.
2833static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S,
2834 UnaryTypeTrait UTT,
2835 SourceLocation Loc,
2836 QualType ArgTy) {
2837 // C++0x [meta.unary.prop]p3:
2838 // For all of the class templates X declared in this Clause, instantiating
2839 // that template with a template argument that is a class template
2840 // specialization may result in the implicit instantiation of the template
2841 // argument if and only if the semantics of X require that the argument
2842 // must be a complete type.
2843 // We apply this rule to all the type trait expressions used to implement
2844 // these class templates. We also try to follow any GCC documented behavior
2845 // in these expressions to ensure portability of standard libraries.
2846 switch (UTT) {
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002847 // is_complete_type somewhat obviously cannot require a complete type.
2848 case UTT_IsCompleteType:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002849 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002850
2851 // These traits are modeled on the type predicates in C++0x
2852 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
2853 // requiring a complete type, as whether or not they return true cannot be
2854 // impacted by the completeness of the type.
2855 case UTT_IsVoid:
2856 case UTT_IsIntegral:
2857 case UTT_IsFloatingPoint:
2858 case UTT_IsArray:
2859 case UTT_IsPointer:
2860 case UTT_IsLvalueReference:
2861 case UTT_IsRvalueReference:
2862 case UTT_IsMemberFunctionPointer:
2863 case UTT_IsMemberObjectPointer:
2864 case UTT_IsEnum:
2865 case UTT_IsUnion:
2866 case UTT_IsClass:
2867 case UTT_IsFunction:
2868 case UTT_IsReference:
2869 case UTT_IsArithmetic:
2870 case UTT_IsFundamental:
2871 case UTT_IsObject:
2872 case UTT_IsScalar:
2873 case UTT_IsCompound:
2874 case UTT_IsMemberPointer:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002875 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002876
2877 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
2878 // which requires some of its traits to have the complete type. However,
2879 // the completeness of the type cannot impact these traits' semantics, and
2880 // so they don't require it. This matches the comments on these traits in
2881 // Table 49.
2882 case UTT_IsConst:
2883 case UTT_IsVolatile:
2884 case UTT_IsSigned:
2885 case UTT_IsUnsigned:
2886 return true;
2887
2888 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002889 // applied to a complete type.
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002890 case UTT_IsTrivial:
Sean Huntfeb375d2011-05-13 00:31:07 +00002891 case UTT_IsTriviallyCopyable:
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002892 case UTT_IsStandardLayout:
2893 case UTT_IsPOD:
2894 case UTT_IsLiteral:
2895 case UTT_IsEmpty:
2896 case UTT_IsPolymorphic:
2897 case UTT_IsAbstract:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002898 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002899
Douglas Gregor5e9392b2011-12-03 18:14:24 +00002900 // These traits require a complete type.
2901 case UTT_IsFinal:
2902
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002903 // These trait expressions are designed to help implement predicates in
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002904 // [meta.unary.prop] despite not being named the same. They are specified
2905 // by both GCC and the Embarcadero C++ compiler, and require the complete
2906 // type due to the overarching C++0x type predicates being implemented
2907 // requiring the complete type.
2908 case UTT_HasNothrowAssign:
2909 case UTT_HasNothrowConstructor:
2910 case UTT_HasNothrowCopy:
2911 case UTT_HasTrivialAssign:
Sean Hunt023df372011-05-09 18:22:59 +00002912 case UTT_HasTrivialDefaultConstructor:
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002913 case UTT_HasTrivialCopy:
2914 case UTT_HasTrivialDestructor:
2915 case UTT_HasVirtualDestructor:
2916 // Arrays of unknown bound are expressly allowed.
2917 QualType ElTy = ArgTy;
2918 if (ArgTy->isIncompleteArrayType())
2919 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
2920
2921 // The void type is expressly allowed.
2922 if (ElTy->isVoidType())
2923 return true;
2924
2925 return !S.RequireCompleteType(
2926 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleycf566412011-04-28 02:06:46 +00002927 }
Chandler Carruth73e0a912011-05-01 07:23:17 +00002928 llvm_unreachable("Type trait not handled by switch");
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002929}
2930
2931static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT,
2932 SourceLocation KeyLoc, QualType T) {
Chandler Carruthd064c702011-05-01 08:41:10 +00002933 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleycf566412011-04-28 02:06:46 +00002934
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002935 ASTContext &C = Self.Context;
2936 switch(UTT) {
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002937 // Type trait expressions corresponding to the primary type category
2938 // predicates in C++0x [meta.unary.cat].
2939 case UTT_IsVoid:
2940 return T->isVoidType();
2941 case UTT_IsIntegral:
2942 return T->isIntegralType(C);
2943 case UTT_IsFloatingPoint:
2944 return T->isFloatingType();
2945 case UTT_IsArray:
2946 return T->isArrayType();
2947 case UTT_IsPointer:
2948 return T->isPointerType();
2949 case UTT_IsLvalueReference:
2950 return T->isLValueReferenceType();
2951 case UTT_IsRvalueReference:
2952 return T->isRValueReferenceType();
2953 case UTT_IsMemberFunctionPointer:
2954 return T->isMemberFunctionPointerType();
2955 case UTT_IsMemberObjectPointer:
2956 return T->isMemberDataPointerType();
2957 case UTT_IsEnum:
2958 return T->isEnumeralType();
Chandler Carruth28eeb382011-05-01 06:11:03 +00002959 case UTT_IsUnion:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002960 return T->isUnionType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002961 case UTT_IsClass:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002962 return T->isClassType() || T->isStructureType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002963 case UTT_IsFunction:
2964 return T->isFunctionType();
2965
2966 // Type trait expressions which correspond to the convenient composition
2967 // predicates in C++0x [meta.unary.comp].
2968 case UTT_IsReference:
2969 return T->isReferenceType();
2970 case UTT_IsArithmetic:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002971 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002972 case UTT_IsFundamental:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002973 return T->isFundamentalType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002974 case UTT_IsObject:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002975 return T->isObjectType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002976 case UTT_IsScalar:
John McCallf85e1932011-06-15 23:02:42 +00002977 // Note: semantic analysis depends on Objective-C lifetime types to be
2978 // considered scalar types. However, such types do not actually behave
2979 // like scalar types at run time (since they may require retain/release
2980 // operations), so we report them as non-scalar.
2981 if (T->isObjCLifetimeType()) {
2982 switch (T.getObjCLifetime()) {
2983 case Qualifiers::OCL_None:
2984 case Qualifiers::OCL_ExplicitNone:
2985 return true;
2986
2987 case Qualifiers::OCL_Strong:
2988 case Qualifiers::OCL_Weak:
2989 case Qualifiers::OCL_Autoreleasing:
2990 return false;
2991 }
2992 }
2993
Chandler Carruthcec0ced2011-05-01 09:29:55 +00002994 return T->isScalarType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002995 case UTT_IsCompound:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002996 return T->isCompoundType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002997 case UTT_IsMemberPointer:
2998 return T->isMemberPointerType();
2999
3000 // Type trait expressions which correspond to the type property predicates
3001 // in C++0x [meta.unary.prop].
3002 case UTT_IsConst:
3003 return T.isConstQualified();
3004 case UTT_IsVolatile:
3005 return T.isVolatileQualified();
3006 case UTT_IsTrivial:
John McCallf85e1932011-06-15 23:02:42 +00003007 return T.isTrivialType(Self.Context);
Sean Huntfeb375d2011-05-13 00:31:07 +00003008 case UTT_IsTriviallyCopyable:
John McCallf85e1932011-06-15 23:02:42 +00003009 return T.isTriviallyCopyableType(Self.Context);
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003010 case UTT_IsStandardLayout:
3011 return T->isStandardLayoutType();
3012 case UTT_IsPOD:
Benjamin Kramer470360d2012-04-28 10:00:33 +00003013 return T.isPODType(Self.Context);
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003014 case UTT_IsLiteral:
3015 return T->isLiteralType();
3016 case UTT_IsEmpty:
3017 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3018 return !RD->isUnion() && RD->isEmpty();
3019 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003020 case UTT_IsPolymorphic:
Chandler Carruth28eeb382011-05-01 06:11:03 +00003021 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3022 return RD->isPolymorphic();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003023 return false;
3024 case UTT_IsAbstract:
Chandler Carruth28eeb382011-05-01 06:11:03 +00003025 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3026 return RD->isAbstract();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003027 return false;
Douglas Gregor5e9392b2011-12-03 18:14:24 +00003028 case UTT_IsFinal:
3029 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3030 return RD->hasAttr<FinalAttr>();
3031 return false;
John Wiegley20c0da72011-04-27 23:09:49 +00003032 case UTT_IsSigned:
3033 return T->isSignedIntegerType();
John Wiegley20c0da72011-04-27 23:09:49 +00003034 case UTT_IsUnsigned:
3035 return T->isUnsignedIntegerType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003036
3037 // Type trait expressions which query classes regarding their construction,
3038 // destruction, and copying. Rather than being based directly on the
3039 // related type predicates in the standard, they are specified by both
3040 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
3041 // specifications.
3042 //
3043 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
3044 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Sean Hunt023df372011-05-09 18:22:59 +00003045 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003046 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3047 // If __is_pod (type) is true then the trait is true, else if type is
3048 // a cv class or union type (or array thereof) with a trivial default
3049 // constructor ([class.ctor]) then the trait is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00003050 if (T.isPODType(Self.Context))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003051 return true;
3052 if (const RecordType *RT =
3053 C.getBaseElementType(T)->getAs<RecordType>())
Sean Hunt023df372011-05-09 18:22:59 +00003054 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDefaultConstructor();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003055 return false;
3056 case UTT_HasTrivialCopy:
3057 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3058 // If __is_pod (type) is true or type is a reference type then
3059 // the trait is true, else if type is a cv class or union type
3060 // with a trivial copy constructor ([class.copy]) then the trait
3061 // is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00003062 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003063 return true;
3064 if (const RecordType *RT = T->getAs<RecordType>())
3065 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
3066 return false;
3067 case UTT_HasTrivialAssign:
3068 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3069 // If type is const qualified or is a reference type then the
3070 // trait is false. Otherwise if __is_pod (type) is true then the
3071 // trait is true, else if type is a cv class or union type with
3072 // a trivial copy assignment ([class.copy]) then the trait is
3073 // true, else it is false.
3074 // Note: the const and reference restrictions are interesting,
3075 // given that const and reference members don't prevent a class
3076 // from having a trivial copy assignment operator (but do cause
3077 // errors if the copy assignment operator is actually used, q.v.
3078 // [class.copy]p12).
3079
3080 if (C.getBaseElementType(T).isConstQualified())
3081 return false;
John McCallf85e1932011-06-15 23:02:42 +00003082 if (T.isPODType(Self.Context))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003083 return true;
3084 if (const RecordType *RT = T->getAs<RecordType>())
3085 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
3086 return false;
3087 case UTT_HasTrivialDestructor:
3088 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3089 // If __is_pod (type) is true or type is a reference type
3090 // then the trait is true, else if type is a cv class or union
3091 // type (or array thereof) with a trivial destructor
3092 // ([class.dtor]) then the trait is true, else it is
3093 // false.
John McCallf85e1932011-06-15 23:02:42 +00003094 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003095 return true;
John McCallf85e1932011-06-15 23:02:42 +00003096
3097 // Objective-C++ ARC: autorelease types don't require destruction.
3098 if (T->isObjCLifetimeType() &&
3099 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
3100 return true;
3101
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003102 if (const RecordType *RT =
3103 C.getBaseElementType(T)->getAs<RecordType>())
3104 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
3105 return false;
3106 // TODO: Propagate nothrowness for implicitly declared special members.
3107 case UTT_HasNothrowAssign:
3108 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3109 // If type is const qualified or is a reference type then the
3110 // trait is false. Otherwise if __has_trivial_assign (type)
3111 // is true then the trait is true, else if type is a cv class
3112 // or union type with copy assignment operators that are known
3113 // not to throw an exception then the trait is true, else it is
3114 // false.
3115 if (C.getBaseElementType(T).isConstQualified())
3116 return false;
3117 if (T->isReferenceType())
3118 return false;
John McCallf85e1932011-06-15 23:02:42 +00003119 if (T.isPODType(Self.Context) || T->isObjCLifetimeType())
3120 return true;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003121 if (const RecordType *RT = T->getAs<RecordType>()) {
3122 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
3123 if (RD->hasTrivialCopyAssignment())
3124 return true;
3125
3126 bool FoundAssign = false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003127 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redlf8aca862010-09-14 23:40:14 +00003128 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
3129 Sema::LookupOrdinaryName);
3130 if (Self.LookupQualifiedName(Res, RD)) {
Douglas Gregord41679d2011-10-12 15:40:49 +00003131 Res.suppressDiagnostics();
Sebastian Redlf8aca862010-09-14 23:40:14 +00003132 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
3133 Op != OpEnd; ++Op) {
Douglas Gregord41679d2011-10-12 15:40:49 +00003134 if (isa<FunctionTemplateDecl>(*Op))
3135 continue;
3136
Sebastian Redlf8aca862010-09-14 23:40:14 +00003137 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
3138 if (Operator->isCopyAssignmentOperator()) {
3139 FoundAssign = true;
3140 const FunctionProtoType *CPT
3141 = Operator->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +00003142 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3143 if (!CPT)
3144 return false;
Richard Smith7a614d82011-06-11 17:19:42 +00003145 if (CPT->getExceptionSpecType() == EST_Delayed)
3146 return false;
3147 if (!CPT->isNothrow(Self.Context))
3148 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003149 }
3150 }
3151 }
Douglas Gregord41679d2011-10-12 15:40:49 +00003152
Richard Smith7a614d82011-06-11 17:19:42 +00003153 return FoundAssign;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003154 }
3155 return false;
3156 case UTT_HasNothrowCopy:
3157 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3158 // If __has_trivial_copy (type) is true then the trait is true, else
3159 // if type is a cv class or union type with copy constructors that are
3160 // known not to throw an exception then the trait is true, else it is
3161 // false.
John McCallf85e1932011-06-15 23:02:42 +00003162 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003163 return true;
3164 if (const RecordType *RT = T->getAs<RecordType>()) {
3165 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3166 if (RD->hasTrivialCopyConstructor())
3167 return true;
3168
3169 bool FoundConstructor = false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003170 unsigned FoundTQs;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003171 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl5f4e8992010-09-13 21:10:20 +00003172 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003173 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00003174 // A template constructor is never a copy constructor.
3175 // FIXME: However, it may actually be selected at the actual overload
3176 // resolution point.
3177 if (isa<FunctionTemplateDecl>(*Con))
3178 continue;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003179 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3180 if (Constructor->isCopyConstructor(FoundTQs)) {
3181 FoundConstructor = true;
3182 const FunctionProtoType *CPT
3183 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +00003184 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3185 if (!CPT)
3186 return false;
Richard Smith7a614d82011-06-11 17:19:42 +00003187 if (CPT->getExceptionSpecType() == EST_Delayed)
3188 return false;
Sebastian Redl60618fa2011-03-12 11:50:43 +00003189 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redl751025d2010-09-13 22:02:47 +00003190 // For now, we'll be conservative and assume that they can throw.
Richard Smith7a614d82011-06-11 17:19:42 +00003191 if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1)
3192 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003193 }
3194 }
3195
Richard Smith7a614d82011-06-11 17:19:42 +00003196 return FoundConstructor;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003197 }
3198 return false;
3199 case UTT_HasNothrowConstructor:
3200 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3201 // If __has_trivial_constructor (type) is true then the trait is
3202 // true, else if type is a cv class or union type (or array
3203 // thereof) with a default constructor that is known not to
3204 // throw an exception then the trait is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00003205 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003206 return true;
3207 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
3208 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Hunt023df372011-05-09 18:22:59 +00003209 if (RD->hasTrivialDefaultConstructor())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003210 return true;
3211
Sebastian Redl751025d2010-09-13 22:02:47 +00003212 DeclContext::lookup_const_iterator Con, ConEnd;
3213 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
3214 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00003215 // FIXME: In C++0x, a constructor template can be a default constructor.
3216 if (isa<FunctionTemplateDecl>(*Con))
3217 continue;
Sebastian Redl751025d2010-09-13 22:02:47 +00003218 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3219 if (Constructor->isDefaultConstructor()) {
3220 const FunctionProtoType *CPT
3221 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +00003222 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3223 if (!CPT)
3224 return false;
Richard Smith7a614d82011-06-11 17:19:42 +00003225 if (CPT->getExceptionSpecType() == EST_Delayed)
3226 return false;
Sebastian Redl751025d2010-09-13 22:02:47 +00003227 // TODO: check whether evaluating default arguments can throw.
3228 // For now, we'll be conservative and assume that they can throw.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00003229 return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
Sebastian Redl751025d2010-09-13 22:02:47 +00003230 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003231 }
3232 }
3233 return false;
3234 case UTT_HasVirtualDestructor:
3235 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3236 // If type is a class type with a virtual destructor ([class.dtor])
3237 // then the trait is true, else it is false.
3238 if (const RecordType *Record = T->getAs<RecordType>()) {
3239 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redlf8aca862010-09-14 23:40:14 +00003240 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003241 return Destructor->isVirtual();
3242 }
3243 return false;
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003244
3245 // These type trait expressions are modeled on the specifications for the
3246 // Embarcadero C++0x type trait functions:
3247 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
3248 case UTT_IsCompleteType:
3249 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
3250 // Returns True if and only if T is a complete type at the point of the
3251 // function call.
3252 return !T->isIncompleteType();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003253 }
Chandler Carruth83f563c2011-05-01 07:44:17 +00003254 llvm_unreachable("Type trait not covered by switch");
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003255}
3256
3257ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00003258 SourceLocation KWLoc,
3259 TypeSourceInfo *TSInfo,
3260 SourceLocation RParen) {
3261 QualType T = TSInfo->getType();
Chandler Carrutheb65a102011-04-30 10:07:32 +00003262 if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T))
3263 return ExprError();
Sebastian Redl64b45f72009-01-05 20:52:13 +00003264
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003265 bool Value = false;
3266 if (!T->isDependentType())
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00003267 Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003268
3269 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson3292d5c2009-07-07 19:06:02 +00003270 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00003271}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003272
Francois Pichet6ad6f282010-12-07 00:08:36 +00003273ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
3274 SourceLocation KWLoc,
3275 ParsedType LhsTy,
3276 ParsedType RhsTy,
3277 SourceLocation RParen) {
3278 TypeSourceInfo *LhsTSInfo;
3279 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
3280 if (!LhsTSInfo)
3281 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
3282
3283 TypeSourceInfo *RhsTSInfo;
3284 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
3285 if (!RhsTSInfo)
3286 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
3287
3288 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
3289}
3290
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00003291static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
3292 ArrayRef<TypeSourceInfo *> Args,
3293 SourceLocation RParenLoc) {
3294 switch (Kind) {
3295 case clang::TT_IsTriviallyConstructible: {
3296 // C++11 [meta.unary.prop]:
Dmitri Gribenko62348f02012-02-24 20:03:35 +00003297 // is_trivially_constructible is defined as:
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00003298 //
Dmitri Gribenko62348f02012-02-24 20:03:35 +00003299 // is_constructible<T, Args...>::value is true and the variable
3300 // definition for is_constructible, as defined below, is known to call no
3301 // operation that is not trivial.
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00003302 //
3303 // The predicate condition for a template specialization
3304 // is_constructible<T, Args...> shall be satisfied if and only if the
3305 // following variable definition would be well-formed for some invented
3306 // variable t:
3307 //
3308 // T t(create<Args>()...);
3309 if (Args.empty()) {
3310 S.Diag(KWLoc, diag::err_type_trait_arity)
3311 << 1 << 1 << 1 << (int)Args.size();
3312 return false;
3313 }
3314
3315 bool SawVoid = false;
3316 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3317 if (Args[I]->getType()->isVoidType()) {
3318 SawVoid = true;
3319 continue;
3320 }
3321
3322 if (!Args[I]->getType()->isIncompleteType() &&
3323 S.RequireCompleteType(KWLoc, Args[I]->getType(),
3324 diag::err_incomplete_type_used_in_type_trait_expr))
3325 return false;
3326 }
3327
3328 // If any argument was 'void', of course it won't type-check.
3329 if (SawVoid)
3330 return false;
3331
3332 llvm::SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
3333 llvm::SmallVector<Expr *, 2> ArgExprs;
3334 ArgExprs.reserve(Args.size() - 1);
3335 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
3336 QualType T = Args[I]->getType();
3337 if (T->isObjectType() || T->isFunctionType())
3338 T = S.Context.getRValueReferenceType(T);
3339 OpaqueArgExprs.push_back(
Daniel Dunbar96a00142012-03-09 18:35:03 +00003340 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00003341 T.getNonLValueExprType(S.Context),
3342 Expr::getValueKindForType(T)));
3343 ArgExprs.push_back(&OpaqueArgExprs.back());
3344 }
3345
3346 // Perform the initialization in an unevaluated context within a SFINAE
3347 // trap at translation unit scope.
3348 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
3349 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
3350 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3351 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
3352 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
3353 RParenLoc));
3354 InitializationSequence Init(S, To, InitKind,
3355 ArgExprs.begin(), ArgExprs.size());
3356 if (Init.Failed())
3357 return false;
3358
3359 ExprResult Result = Init.Perform(S, To, InitKind,
3360 MultiExprArg(ArgExprs.data(),
3361 ArgExprs.size()));
3362 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
3363 return false;
3364
3365 // The initialization succeeded; not make sure there are no non-trivial
3366 // calls.
3367 return !Result.get()->hasNonTrivialCall(S.Context);
3368 }
3369 }
3370
3371 return false;
3372}
3373
3374ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3375 ArrayRef<TypeSourceInfo *> Args,
3376 SourceLocation RParenLoc) {
3377 bool Dependent = false;
3378 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3379 if (Args[I]->getType()->isDependentType()) {
3380 Dependent = true;
3381 break;
3382 }
3383 }
3384
3385 bool Value = false;
3386 if (!Dependent)
3387 Value = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
3388
3389 return TypeTraitExpr::Create(Context, Context.BoolTy, KWLoc, Kind,
3390 Args, RParenLoc, Value);
3391}
3392
3393ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3394 ArrayRef<ParsedType> Args,
3395 SourceLocation RParenLoc) {
3396 llvm::SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
3397 ConvertedArgs.reserve(Args.size());
3398
3399 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3400 TypeSourceInfo *TInfo;
3401 QualType T = GetTypeFromParser(Args[I], &TInfo);
3402 if (!TInfo)
3403 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
3404
3405 ConvertedArgs.push_back(TInfo);
3406 }
3407
3408 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
3409}
3410
Francois Pichet6ad6f282010-12-07 00:08:36 +00003411static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
3412 QualType LhsT, QualType RhsT,
3413 SourceLocation KeyLoc) {
Chandler Carruthd064c702011-05-01 08:41:10 +00003414 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
3415 "Cannot evaluate traits of dependent types");
Francois Pichet6ad6f282010-12-07 00:08:36 +00003416
3417 switch(BTT) {
John McCalld89d30f2011-01-28 22:02:36 +00003418 case BTT_IsBaseOf: {
Francois Pichet6ad6f282010-12-07 00:08:36 +00003419 // C++0x [meta.rel]p2
John McCalld89d30f2011-01-28 22:02:36 +00003420 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet6ad6f282010-12-07 00:08:36 +00003421 // Base and Derived are not unions and name the same class type without
3422 // regard to cv-qualifiers.
Francois Pichet6ad6f282010-12-07 00:08:36 +00003423
John McCalld89d30f2011-01-28 22:02:36 +00003424 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
3425 if (!lhsRecord) return false;
3426
3427 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
3428 if (!rhsRecord) return false;
3429
3430 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
3431 == (lhsRecord == rhsRecord));
3432
3433 if (lhsRecord == rhsRecord)
3434 return !lhsRecord->getDecl()->isUnion();
3435
3436 // C++0x [meta.rel]p2:
3437 // If Base and Derived are class types and are different types
3438 // (ignoring possible cv-qualifiers) then Derived shall be a
3439 // complete type.
3440 if (Self.RequireCompleteType(KeyLoc, RhsT,
3441 diag::err_incomplete_type_used_in_type_trait_expr))
3442 return false;
3443
3444 return cast<CXXRecordDecl>(rhsRecord->getDecl())
3445 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
3446 }
John Wiegley20c0da72011-04-27 23:09:49 +00003447 case BTT_IsSame:
3448 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichetf1872372010-12-08 22:35:30 +00003449 case BTT_TypeCompatible:
3450 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
3451 RhsT.getUnqualifiedType());
John Wiegley20c0da72011-04-27 23:09:49 +00003452 case BTT_IsConvertible:
Douglas Gregor9f361132011-01-27 20:28:01 +00003453 case BTT_IsConvertibleTo: {
3454 // C++0x [meta.rel]p4:
3455 // Given the following function prototype:
3456 //
3457 // template <class T>
3458 // typename add_rvalue_reference<T>::type create();
3459 //
3460 // the predicate condition for a template specialization
3461 // is_convertible<From, To> shall be satisfied if and only if
3462 // the return expression in the following code would be
3463 // well-formed, including any implicit conversions to the return
3464 // type of the function:
3465 //
3466 // To test() {
3467 // return create<From>();
3468 // }
3469 //
3470 // Access checking is performed as if in a context unrelated to To and
3471 // From. Only the validity of the immediate context of the expression
3472 // of the return-statement (including conversions to the return type)
3473 // is considered.
3474 //
3475 // We model the initialization as a copy-initialization of a temporary
3476 // of the appropriate type, which for this expression is identical to the
3477 // return statement (since NRVO doesn't apply).
3478 if (LhsT->isObjectType() || LhsT->isFunctionType())
3479 LhsT = Self.Context.getRValueReferenceType(LhsT);
3480
3481 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorb608b982011-01-28 02:26:04 +00003482 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor9f361132011-01-27 20:28:01 +00003483 Expr::getValueKindForType(LhsT));
3484 Expr *FromPtr = &From;
3485 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
3486 SourceLocation()));
3487
Eli Friedman3add9f02012-01-25 01:05:57 +00003488 // Perform the initialization in an unevaluated context within a SFINAE
3489 // trap at translation unit scope.
3490 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00003491 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3492 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Douglas Gregor9f361132011-01-27 20:28:01 +00003493 InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003494 if (Init.Failed())
Douglas Gregor9f361132011-01-27 20:28:01 +00003495 return false;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00003496
Douglas Gregor9f361132011-01-27 20:28:01 +00003497 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
3498 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
3499 }
Douglas Gregor25d0a0f2012-02-23 07:33:15 +00003500
3501 case BTT_IsTriviallyAssignable: {
3502 // C++11 [meta.unary.prop]p3:
3503 // is_trivially_assignable is defined as:
3504 // is_assignable<T, U>::value is true and the assignment, as defined by
3505 // is_assignable, is known to call no operation that is not trivial
3506 //
3507 // is_assignable is defined as:
3508 // The expression declval<T>() = declval<U>() is well-formed when
3509 // treated as an unevaluated operand (Clause 5).
3510 //
3511 // For both, T and U shall be complete types, (possibly cv-qualified)
3512 // void, or arrays of unknown bound.
3513 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
3514 Self.RequireCompleteType(KeyLoc, LhsT,
3515 diag::err_incomplete_type_used_in_type_trait_expr))
3516 return false;
3517 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
3518 Self.RequireCompleteType(KeyLoc, RhsT,
3519 diag::err_incomplete_type_used_in_type_trait_expr))
3520 return false;
3521
3522 // cv void is never assignable.
3523 if (LhsT->isVoidType() || RhsT->isVoidType())
3524 return false;
3525
3526 // Build expressions that emulate the effect of declval<T>() and
3527 // declval<U>().
3528 if (LhsT->isObjectType() || LhsT->isFunctionType())
3529 LhsT = Self.Context.getRValueReferenceType(LhsT);
3530 if (RhsT->isObjectType() || RhsT->isFunctionType())
3531 RhsT = Self.Context.getRValueReferenceType(RhsT);
3532 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
3533 Expr::getValueKindForType(LhsT));
3534 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
3535 Expr::getValueKindForType(RhsT));
3536
3537 // Attempt the assignment in an unevaluated context within a SFINAE
3538 // trap at translation unit scope.
3539 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
3540 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3541 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
3542 ExprResult Result = Self.BuildBinOp(/*S=*/0, KeyLoc, BO_Assign, &Lhs, &Rhs);
3543 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
3544 return false;
3545
3546 return !Result.get()->hasNonTrivialCall(Self.Context);
3547 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00003548 }
3549 llvm_unreachable("Unknown type trait or not implemented");
3550}
3551
3552ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
3553 SourceLocation KWLoc,
3554 TypeSourceInfo *LhsTSInfo,
3555 TypeSourceInfo *RhsTSInfo,
3556 SourceLocation RParen) {
3557 QualType LhsT = LhsTSInfo->getType();
3558 QualType RhsT = RhsTSInfo->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003559
John McCalld89d30f2011-01-28 22:02:36 +00003560 if (BTT == BTT_TypeCompatible) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003561 if (getLangOpts().CPlusPlus) {
Francois Pichetf1872372010-12-08 22:35:30 +00003562 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
3563 << SourceRange(KWLoc, RParen);
3564 return ExprError();
3565 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00003566 }
3567
3568 bool Value = false;
3569 if (!LhsT->isDependentType() && !RhsT->isDependentType())
3570 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
3571
Francois Pichetf1872372010-12-08 22:35:30 +00003572 // Select trait result type.
3573 QualType ResultType;
3574 switch (BTT) {
Francois Pichetf1872372010-12-08 22:35:30 +00003575 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
John Wiegley20c0da72011-04-27 23:09:49 +00003576 case BTT_IsConvertible: ResultType = Context.BoolTy; break;
3577 case BTT_IsSame: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00003578 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
Douglas Gregor9f361132011-01-27 20:28:01 +00003579 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
Douglas Gregor25d0a0f2012-02-23 07:33:15 +00003580 case BTT_IsTriviallyAssignable: ResultType = Context.BoolTy;
Francois Pichetf1872372010-12-08 22:35:30 +00003581 }
3582
Francois Pichet6ad6f282010-12-07 00:08:36 +00003583 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
3584 RhsTSInfo, Value, RParen,
Francois Pichetf1872372010-12-08 22:35:30 +00003585 ResultType));
Francois Pichet6ad6f282010-12-07 00:08:36 +00003586}
3587
John Wiegley21ff2e52011-04-28 00:16:57 +00003588ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3589 SourceLocation KWLoc,
3590 ParsedType Ty,
3591 Expr* DimExpr,
3592 SourceLocation RParen) {
3593 TypeSourceInfo *TSInfo;
3594 QualType T = GetTypeFromParser(Ty, &TSInfo);
3595 if (!TSInfo)
3596 TSInfo = Context.getTrivialTypeSourceInfo(T);
3597
3598 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
3599}
3600
3601static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
3602 QualType T, Expr *DimExpr,
3603 SourceLocation KeyLoc) {
Chandler Carruthd064c702011-05-01 08:41:10 +00003604 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley21ff2e52011-04-28 00:16:57 +00003605
3606 switch(ATT) {
3607 case ATT_ArrayRank:
3608 if (T->isArrayType()) {
3609 unsigned Dim = 0;
3610 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3611 ++Dim;
3612 T = AT->getElementType();
3613 }
3614 return Dim;
John Wiegley21ff2e52011-04-28 00:16:57 +00003615 }
John Wiegleycf566412011-04-28 02:06:46 +00003616 return 0;
3617
John Wiegley21ff2e52011-04-28 00:16:57 +00003618 case ATT_ArrayExtent: {
3619 llvm::APSInt Value;
3620 uint64_t Dim;
Richard Smith282e7e62012-02-04 09:53:13 +00003621 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
3622 Self.PDiag(diag::err_dimension_expr_not_constant_integer),
3623 false).isInvalid())
3624 return 0;
3625 if (Value.isSigned() && Value.isNegative()) {
Daniel Dunbare7d6ca02012-03-09 21:38:22 +00003626 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
3627 << DimExpr->getSourceRange();
Richard Smith282e7e62012-02-04 09:53:13 +00003628 return 0;
John Wiegleycf566412011-04-28 02:06:46 +00003629 }
Richard Smith282e7e62012-02-04 09:53:13 +00003630 Dim = Value.getLimitedValue();
John Wiegley21ff2e52011-04-28 00:16:57 +00003631
3632 if (T->isArrayType()) {
3633 unsigned D = 0;
3634 bool Matched = false;
3635 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3636 if (Dim == D) {
3637 Matched = true;
3638 break;
3639 }
3640 ++D;
3641 T = AT->getElementType();
3642 }
3643
John Wiegleycf566412011-04-28 02:06:46 +00003644 if (Matched && T->isArrayType()) {
3645 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
3646 return CAT->getSize().getLimitedValue();
3647 }
John Wiegley21ff2e52011-04-28 00:16:57 +00003648 }
John Wiegleycf566412011-04-28 02:06:46 +00003649 return 0;
John Wiegley21ff2e52011-04-28 00:16:57 +00003650 }
3651 }
3652 llvm_unreachable("Unknown type trait or not implemented");
3653}
3654
3655ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
3656 SourceLocation KWLoc,
3657 TypeSourceInfo *TSInfo,
3658 Expr* DimExpr,
3659 SourceLocation RParen) {
3660 QualType T = TSInfo->getType();
John Wiegley21ff2e52011-04-28 00:16:57 +00003661
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003662 // FIXME: This should likely be tracked as an APInt to remove any host
3663 // assumptions about the width of size_t on the target.
Chandler Carruthd064c702011-05-01 08:41:10 +00003664 uint64_t Value = 0;
3665 if (!T->isDependentType())
3666 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
3667
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003668 // While the specification for these traits from the Embarcadero C++
3669 // compiler's documentation says the return type is 'unsigned int', Clang
3670 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
3671 // compiler, there is no difference. On several other platforms this is an
3672 // important distinction.
John Wiegley21ff2e52011-04-28 00:16:57 +00003673 return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value,
Chandler Carruth06207f62011-05-01 07:49:26 +00003674 DimExpr, RParen,
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003675 Context.getSizeType()));
John Wiegley21ff2e52011-04-28 00:16:57 +00003676}
3677
John Wiegley55262202011-04-25 06:54:41 +00003678ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003679 SourceLocation KWLoc,
3680 Expr *Queried,
3681 SourceLocation RParen) {
John Wiegley55262202011-04-25 06:54:41 +00003682 // If error parsing the expression, ignore.
3683 if (!Queried)
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003684 return ExprError();
John Wiegley55262202011-04-25 06:54:41 +00003685
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003686 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegley55262202011-04-25 06:54:41 +00003687
3688 return move(Result);
3689}
3690
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003691static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
3692 switch (ET) {
3693 case ET_IsLValueExpr: return E->isLValue();
3694 case ET_IsRValueExpr: return E->isRValue();
3695 }
3696 llvm_unreachable("Expression trait not covered by switch");
3697}
3698
John Wiegley55262202011-04-25 06:54:41 +00003699ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003700 SourceLocation KWLoc,
3701 Expr *Queried,
3702 SourceLocation RParen) {
John Wiegley55262202011-04-25 06:54:41 +00003703 if (Queried->isTypeDependent()) {
3704 // Delay type-checking for type-dependent expressions.
3705 } else if (Queried->getType()->isPlaceholderType()) {
3706 ExprResult PE = CheckPlaceholderExpr(Queried);
3707 if (PE.isInvalid()) return ExprError();
3708 return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen);
3709 }
3710
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003711 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf7ef0002011-05-01 08:48:19 +00003712
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003713 return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value,
3714 RParen, Context.BoolTy));
John Wiegley55262202011-04-25 06:54:41 +00003715}
3716
Richard Trieudd225092011-09-15 21:56:47 +00003717QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCallf89e55a2010-11-18 06:31:45 +00003718 ExprValueKind &VK,
3719 SourceLocation Loc,
3720 bool isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003721 assert(!LHS.get()->getType()->isPlaceholderType() &&
3722 !RHS.get()->getType()->isPlaceholderType() &&
John McCallea4aba02011-06-30 17:15:34 +00003723 "placeholders should have been weeded out by now");
3724
3725 // The LHS undergoes lvalue conversions if this is ->*.
3726 if (isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003727 LHS = DefaultLvalueConversion(LHS.take());
3728 if (LHS.isInvalid()) return QualType();
John McCallea4aba02011-06-30 17:15:34 +00003729 }
3730
3731 // The RHS always undergoes lvalue conversions.
Richard Trieudd225092011-09-15 21:56:47 +00003732 RHS = DefaultLvalueConversion(RHS.take());
3733 if (RHS.isInvalid()) return QualType();
John McCallea4aba02011-06-30 17:15:34 +00003734
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003735 const char *OpSpelling = isIndirect ? "->*" : ".*";
3736 // C++ 5.5p2
3737 // The binary operator .* [p3: ->*] binds its second operand, which shall
3738 // be of type "pointer to member of T" (where T is a completely-defined
3739 // class type) [...]
Richard Trieudd225092011-09-15 21:56:47 +00003740 QualType RHSType = RHS.get()->getType();
3741 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00003742 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003743 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieudd225092011-09-15 21:56:47 +00003744 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003745 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00003746 }
Douglas Gregore7450f52009-03-24 19:52:54 +00003747
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003748 QualType Class(MemPtr->getClass(), 0);
3749
Douglas Gregor7d520ba2010-10-13 20:41:14 +00003750 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
3751 // member pointer points must be completely-defined. However, there is no
3752 // reason for this semantic distinction, and the rule is not enforced by
3753 // other compilers. Therefore, we do not check this property, as it is
3754 // likely to be considered a defect.
Sebastian Redl59fc2692010-04-10 10:14:54 +00003755
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003756 // C++ 5.5p2
3757 // [...] to its first operand, which shall be of class T or of a class of
3758 // which T is an unambiguous and accessible base class. [p3: a pointer to
3759 // such a class]
Richard Trieudd225092011-09-15 21:56:47 +00003760 QualType LHSType = LHS.get()->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003761 if (isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003762 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
3763 LHSType = Ptr->getPointeeType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003764 else {
3765 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieudd225092011-09-15 21:56:47 +00003766 << OpSpelling << 1 << LHSType
Douglas Gregor849b2432010-03-31 17:46:05 +00003767 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003768 return QualType();
3769 }
3770 }
3771
Richard Trieudd225092011-09-15 21:56:47 +00003772 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00003773 // If we want to check the hierarchy, we need a complete type.
Richard Trieudd225092011-09-15 21:56:47 +00003774 if (RequireCompleteType(Loc, LHSType, PDiag(diag::err_bad_memptr_lhs)
Sebastian Redl17e1d352010-04-23 17:18:26 +00003775 << OpSpelling << (int)isIndirect)) {
3776 return QualType();
3777 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003778 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00003779 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00003780 // FIXME: Would it be useful to print full ambiguity paths, or is that
3781 // overkill?
Richard Trieudd225092011-09-15 21:56:47 +00003782 if (!IsDerivedFrom(LHSType, Class, Paths) ||
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003783 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
3784 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieudd225092011-09-15 21:56:47 +00003785 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003786 return QualType();
3787 }
Eli Friedman3005efe2010-01-16 00:00:48 +00003788 // Cast LHS to type of use.
3789 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00003790 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Sebastian Redl906082e2010-07-20 04:20:21 +00003791
John McCallf871d0c2010-08-07 06:22:56 +00003792 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003793 BuildBasePathArray(Paths, BasePath);
Richard Trieudd225092011-09-15 21:56:47 +00003794 LHS = ImpCastExprToType(LHS.take(), UseType, CK_DerivedToBase, VK,
3795 &BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003796 }
3797
Richard Trieudd225092011-09-15 21:56:47 +00003798 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00003799 // Diagnose use of pointer-to-member type which when used as
3800 // the functional cast in a pointer-to-member expression.
3801 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
3802 return QualType();
3803 }
John McCallf89e55a2010-11-18 06:31:45 +00003804
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003805 // C++ 5.5p2
3806 // The result is an object or a function of the type specified by the
3807 // second operand.
3808 // The cv qualifiers are the union of those in the pointer and the left side,
3809 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003810 QualType Result = MemPtr->getPointeeType();
Richard Trieudd225092011-09-15 21:56:47 +00003811 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCallf89e55a2010-11-18 06:31:45 +00003812
Douglas Gregor6b4df912011-01-26 16:40:18 +00003813 // C++0x [expr.mptr.oper]p6:
3814 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003815 // ill-formed if the second operand is a pointer to member function with
3816 // ref-qualifier &. In a ->* expression or in a .* expression whose object
3817 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor6b4df912011-01-26 16:40:18 +00003818 // is a pointer to member function with ref-qualifier &&.
3819 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
3820 switch (Proto->getRefQualifier()) {
3821 case RQ_None:
3822 // Do nothing
3823 break;
3824
3825 case RQ_LValue:
Richard Trieudd225092011-09-15 21:56:47 +00003826 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
Douglas Gregor6b4df912011-01-26 16:40:18 +00003827 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieudd225092011-09-15 21:56:47 +00003828 << RHSType << 1 << LHS.get()->getSourceRange();
Douglas Gregor6b4df912011-01-26 16:40:18 +00003829 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003830
Douglas Gregor6b4df912011-01-26 16:40:18 +00003831 case RQ_RValue:
Richard Trieudd225092011-09-15 21:56:47 +00003832 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor6b4df912011-01-26 16:40:18 +00003833 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieudd225092011-09-15 21:56:47 +00003834 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor6b4df912011-01-26 16:40:18 +00003835 break;
3836 }
3837 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003838
John McCallf89e55a2010-11-18 06:31:45 +00003839 // C++ [expr.mptr.oper]p6:
3840 // The result of a .* expression whose second operand is a pointer
3841 // to a data member is of the same value category as its
3842 // first operand. The result of a .* expression whose second
3843 // operand is a pointer to a member function is a prvalue. The
3844 // result of an ->* expression is an lvalue if its second operand
3845 // is a pointer to data member and a prvalue otherwise.
John McCall864c0412011-04-26 20:42:42 +00003846 if (Result->isFunctionType()) {
John McCallf89e55a2010-11-18 06:31:45 +00003847 VK = VK_RValue;
John McCall864c0412011-04-26 20:42:42 +00003848 return Context.BoundMemberTy;
3849 } else if (isIndirect) {
John McCallf89e55a2010-11-18 06:31:45 +00003850 VK = VK_LValue;
John McCall864c0412011-04-26 20:42:42 +00003851 } else {
Richard Trieudd225092011-09-15 21:56:47 +00003852 VK = LHS.get()->getValueKind();
John McCall864c0412011-04-26 20:42:42 +00003853 }
John McCallf89e55a2010-11-18 06:31:45 +00003854
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003855 return Result;
3856}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003857
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003858/// \brief Try to convert a type to another according to C++0x 5.16p3.
3859///
3860/// This is part of the parameter validation for the ? operator. If either
3861/// value operand is a class type, the two operands are attempted to be
3862/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003863/// It returns true if the program is ill-formed and has already been diagnosed
3864/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003865static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
3866 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00003867 bool &HaveConversion,
3868 QualType &ToType) {
3869 HaveConversion = false;
3870 ToType = To->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003871
3872 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00003873 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003874 // C++0x 5.16p3
3875 // The process for determining whether an operand expression E1 of type T1
3876 // can be converted to match an operand expression E2 of type T2 is defined
3877 // as follows:
3878 // -- If E2 is an lvalue:
John McCall7eb0a9e2010-11-24 05:12:34 +00003879 bool ToIsLvalue = To->isLValue();
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00003880 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003881 // E1 can be converted to match E2 if E1 can be implicitly converted to
3882 // type "lvalue reference to T2", subject to the constraint that in the
3883 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003884 QualType T = Self.Context.getLValueReferenceType(ToType);
3885 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003886
Douglas Gregorb70cf442010-03-26 20:14:36 +00003887 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3888 if (InitSeq.isDirectReferenceBinding()) {
3889 ToType = T;
3890 HaveConversion = true;
3891 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003892 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003893
Douglas Gregorb70cf442010-03-26 20:14:36 +00003894 if (InitSeq.isAmbiguous())
3895 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003896 }
John McCallb1bdc622010-02-25 01:37:24 +00003897
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003898 // -- If E2 is an rvalue, or if the conversion above cannot be done:
3899 // -- if E1 and E2 have class type, and the underlying class types are
3900 // the same or one is a base class of the other:
3901 QualType FTy = From->getType();
3902 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003903 const RecordType *FRec = FTy->getAs<RecordType>();
3904 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003905 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00003906 Self.IsDerivedFrom(FTy, TTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003907 if (FRec && TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00003908 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003909 // E1 can be converted to match E2 if the class of T2 is the
3910 // same type as, or a base class of, the class of T1, and
3911 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00003912 if (FRec == TRec || FDerivedFromT) {
3913 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003914 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3915 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003916 if (InitSeq) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003917 HaveConversion = true;
3918 return false;
3919 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003920
Douglas Gregorb70cf442010-03-26 20:14:36 +00003921 if (InitSeq.isAmbiguous())
3922 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003923 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003924 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003925
Douglas Gregorb70cf442010-03-26 20:14:36 +00003926 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003927 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003928
Douglas Gregorb70cf442010-03-26 20:14:36 +00003929 // -- Otherwise: E1 can be converted to match E2 if E1 can be
3930 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003931 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00003932 // an rvalue).
3933 //
3934 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
3935 // to the array-to-pointer or function-to-pointer conversions.
3936 if (!TTy->getAs<TagType>())
3937 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003938
Douglas Gregorb70cf442010-03-26 20:14:36 +00003939 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3940 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003941 HaveConversion = !InitSeq.Failed();
Douglas Gregorb70cf442010-03-26 20:14:36 +00003942 ToType = TTy;
3943 if (InitSeq.isAmbiguous())
3944 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3945
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003946 return false;
3947}
3948
3949/// \brief Try to find a common type for two according to C++0x 5.16p5.
3950///
3951/// This is part of the parameter validation for the ? operator. If either
3952/// value operand is a class type, overload resolution is used to find a
3953/// conversion to a common type.
John Wiegley429bb272011-04-08 18:41:53 +00003954static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth82214a82011-02-18 23:54:50 +00003955 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00003956 Expr *Args[2] = { LHS.get(), RHS.get() };
Chandler Carruth82214a82011-02-18 23:54:50 +00003957 OverloadCandidateSet CandidateSet(QuestionLoc);
3958 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
3959 CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003960
3961 OverloadCandidateSet::iterator Best;
Chandler Carruth82214a82011-02-18 23:54:50 +00003962 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley429bb272011-04-08 18:41:53 +00003963 case OR_Success: {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003964 // We found a match. Perform the conversions on the arguments and move on.
John Wiegley429bb272011-04-08 18:41:53 +00003965 ExprResult LHSRes =
3966 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
3967 Best->Conversions[0], Sema::AA_Converting);
3968 if (LHSRes.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003969 break;
John Wiegley429bb272011-04-08 18:41:53 +00003970 LHS = move(LHSRes);
3971
3972 ExprResult RHSRes =
3973 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
3974 Best->Conversions[1], Sema::AA_Converting);
3975 if (RHSRes.isInvalid())
3976 break;
3977 RHS = move(RHSRes);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003978 if (Best->Function)
Eli Friedman5f2987c2012-02-02 03:46:19 +00003979 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003980 return false;
John Wiegley429bb272011-04-08 18:41:53 +00003981 }
3982
Douglas Gregor20093b42009-12-09 23:02:17 +00003983 case OR_No_Viable_Function:
Chandler Carruth82214a82011-02-18 23:54:50 +00003984
3985 // Emit a better diagnostic if one of the expressions is a null pointer
3986 // constant and the other is a pointer type. In this case, the user most
3987 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00003988 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00003989 return true;
3990
3991 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00003992 << LHS.get()->getType() << RHS.get()->getType()
3993 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003994 return true;
3995
Douglas Gregor20093b42009-12-09 23:02:17 +00003996 case OR_Ambiguous:
Chandler Carruth82214a82011-02-18 23:54:50 +00003997 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley429bb272011-04-08 18:41:53 +00003998 << LHS.get()->getType() << RHS.get()->getType()
3999 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00004000 // FIXME: Print the possible common types by printing the return types of
4001 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004002 break;
4003
Douglas Gregor20093b42009-12-09 23:02:17 +00004004 case OR_Deleted:
David Blaikieb219cfc2011-09-23 05:06:16 +00004005 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004006 }
4007 return true;
4008}
4009
Sebastian Redl76458502009-04-17 16:30:52 +00004010/// \brief Perform an "extended" implicit conversion as returned by
4011/// TryClassUnification.
John Wiegley429bb272011-04-08 18:41:53 +00004012static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00004013 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley429bb272011-04-08 18:41:53 +00004014 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00004015 SourceLocation());
John Wiegley429bb272011-04-08 18:41:53 +00004016 Expr *Arg = E.take();
4017 InitializationSequence InitSeq(Self, Entity, Kind, &Arg, 1);
4018 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&Arg, 1));
Douglas Gregorb70cf442010-03-26 20:14:36 +00004019 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00004020 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004021
John Wiegley429bb272011-04-08 18:41:53 +00004022 E = Result;
Sebastian Redl76458502009-04-17 16:30:52 +00004023 return false;
4024}
4025
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004026/// \brief Check the operands of ?: under C++ semantics.
4027///
4028/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
4029/// extension. In this case, LHS == Cond. (But they're not aliases.)
John Wiegley429bb272011-04-08 18:41:53 +00004030QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCall56ca35d2011-02-17 10:25:35 +00004031 ExprValueKind &VK, ExprObjectKind &OK,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004032 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00004033 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
4034 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004035
4036 // C++0x 5.16p1
4037 // The first expression is contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00004038 if (!Cond.get()->isTypeDependent()) {
4039 ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
4040 if (CondRes.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004041 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00004042 Cond = move(CondRes);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004043 }
4044
John McCallf89e55a2010-11-18 06:31:45 +00004045 // Assume r-value.
4046 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00004047 OK = OK_Ordinary;
John McCallf89e55a2010-11-18 06:31:45 +00004048
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004049 // Either of the arguments dependent?
John Wiegley429bb272011-04-08 18:41:53 +00004050 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004051 return Context.DependentTy;
4052
4053 // C++0x 5.16p2
4054 // If either the second or the third operand has type (cv) void, ...
John Wiegley429bb272011-04-08 18:41:53 +00004055 QualType LTy = LHS.get()->getType();
4056 QualType RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004057 bool LVoid = LTy->isVoidType();
4058 bool RVoid = RTy->isVoidType();
4059 if (LVoid || RVoid) {
4060 // ... then the [l2r] conversions are performed on the second and third
4061 // operands ...
John Wiegley429bb272011-04-08 18:41:53 +00004062 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
4063 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
4064 if (LHS.isInvalid() || RHS.isInvalid())
4065 return QualType();
4066 LTy = LHS.get()->getType();
4067 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004068
4069 // ... and one of the following shall hold:
4070 // -- The second or the third operand (but not both) is a throw-
4071 // expression; the result is of the type of the other and is an rvalue.
John Wiegley429bb272011-04-08 18:41:53 +00004072 bool LThrow = isa<CXXThrowExpr>(LHS.get());
4073 bool RThrow = isa<CXXThrowExpr>(RHS.get());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004074 if (LThrow && !RThrow)
4075 return RTy;
4076 if (RThrow && !LThrow)
4077 return LTy;
4078
4079 // -- Both the second and third operands have type void; the result is of
4080 // type void and is an rvalue.
4081 if (LVoid && RVoid)
4082 return Context.VoidTy;
4083
4084 // Neither holds, error.
4085 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
4086 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley429bb272011-04-08 18:41:53 +00004087 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004088 return QualType();
4089 }
4090
4091 // Neither is void.
4092
4093 // C++0x 5.16p3
4094 // Otherwise, if the second and third operand have different types, and
4095 // either has (cv) class type, and attempt is made to convert each of those
4096 // operands to the other.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004097 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004098 (LTy->isRecordType() || RTy->isRecordType())) {
4099 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
4100 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00004101 QualType L2RType, R2LType;
4102 bool HaveL2R, HaveR2L;
John Wiegley429bb272011-04-08 18:41:53 +00004103 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004104 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00004105 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004106 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004107
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004108 // If both can be converted, [...] the program is ill-formed.
4109 if (HaveL2R && HaveR2L) {
4110 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley429bb272011-04-08 18:41:53 +00004111 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004112 return QualType();
4113 }
4114
4115 // If exactly one conversion is possible, that conversion is applied to
4116 // the chosen operand and the converted operands are used in place of the
4117 // original operands for the remainder of this section.
4118 if (HaveL2R) {
John Wiegley429bb272011-04-08 18:41:53 +00004119 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004120 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00004121 LTy = LHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004122 } else if (HaveR2L) {
John Wiegley429bb272011-04-08 18:41:53 +00004123 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004124 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00004125 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004126 }
4127 }
4128
4129 // C++0x 5.16p4
John McCallf89e55a2010-11-18 06:31:45 +00004130 // If the second and third operands are glvalues of the same value
4131 // category and have the same type, the result is of that type and
4132 // value category and it is a bit-field if the second or the third
4133 // operand is a bit-field, or if both are bit-fields.
John McCall09431682010-11-18 19:01:18 +00004134 // We only extend this to bitfields, not to the crazy other kinds of
4135 // l-values.
Douglas Gregor1927b1f2010-04-01 22:47:07 +00004136 bool Same = Context.hasSameType(LTy, RTy);
John McCallf89e55a2010-11-18 06:31:45 +00004137 if (Same &&
John Wiegley429bb272011-04-08 18:41:53 +00004138 LHS.get()->isGLValue() &&
4139 LHS.get()->getValueKind() == RHS.get()->getValueKind() &&
4140 LHS.get()->isOrdinaryOrBitFieldObject() &&
4141 RHS.get()->isOrdinaryOrBitFieldObject()) {
4142 VK = LHS.get()->getValueKind();
4143 if (LHS.get()->getObjectKind() == OK_BitField ||
4144 RHS.get()->getObjectKind() == OK_BitField)
John McCall09431682010-11-18 19:01:18 +00004145 OK = OK_BitField;
John McCallf89e55a2010-11-18 06:31:45 +00004146 return LTy;
Fariborz Jahanian3911a1a2010-09-25 01:08:05 +00004147 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004148
4149 // C++0x 5.16p5
4150 // Otherwise, the result is an rvalue. If the second and third operands
4151 // do not have the same type, and either has (cv) class type, ...
4152 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
4153 // ... overload resolution is used to determine the conversions (if any)
4154 // to be applied to the operands. If the overload resolution fails, the
4155 // program is ill-formed.
4156 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
4157 return QualType();
4158 }
4159
4160 // C++0x 5.16p6
4161 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
4162 // conversions are performed on the second and third operands.
John Wiegley429bb272011-04-08 18:41:53 +00004163 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
4164 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
4165 if (LHS.isInvalid() || RHS.isInvalid())
4166 return QualType();
4167 LTy = LHS.get()->getType();
4168 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004169
4170 // After those conversions, one of the following shall hold:
4171 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00004172 // is of that type. If the operands have class type, the result
4173 // is a prvalue temporary of the result type, which is
4174 // copy-initialized from either the second operand or the third
4175 // operand depending on the value of the first operand.
4176 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
4177 if (LTy->isRecordType()) {
4178 // The operands have class type. Make a temporary copy.
4179 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004180 ExprResult LHSCopy = PerformCopyInitialization(Entity,
4181 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00004182 LHS);
Douglas Gregorb65a4582010-05-19 23:40:50 +00004183 if (LHSCopy.isInvalid())
4184 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004185
4186 ExprResult RHSCopy = PerformCopyInitialization(Entity,
4187 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00004188 RHS);
Douglas Gregorb65a4582010-05-19 23:40:50 +00004189 if (RHSCopy.isInvalid())
4190 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004191
John Wiegley429bb272011-04-08 18:41:53 +00004192 LHS = LHSCopy;
4193 RHS = RHSCopy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00004194 }
4195
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004196 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00004197 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004198
Douglas Gregorfb4a5432010-05-18 22:42:18 +00004199 // Extension: conditional operator involving vector types.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004200 if (LTy->isVectorType() || RTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00004201 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00004202
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004203 // -- The second and third operands have arithmetic or enumeration type;
4204 // the usual arithmetic conversions are performed to bring them to a
4205 // common type, and the result is of that type.
4206 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
4207 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00004208 if (LHS.isInvalid() || RHS.isInvalid())
4209 return QualType();
4210 return LHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004211 }
4212
4213 // -- The second and third operands have pointer type, or one has pointer
4214 // type and the other is a null pointer constant; pointer conversions
4215 // and qualification conversions are performed to bring them to their
4216 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00004217 // -- The second and third operands have pointer to member type, or one has
4218 // pointer to member type and the other is a null pointer constant;
4219 // pointer to member conversions and qualification conversions are
4220 // performed to bring them to a common type, whose cv-qualification
4221 // shall match the cv-qualification of either the second or the third
4222 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004223 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004224 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004225 isSFINAEContext()? 0 : &NonStandardCompositeType);
4226 if (!Composite.isNull()) {
4227 if (NonStandardCompositeType)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004228 Diag(QuestionLoc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004229 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
4230 << LTy << RTy << Composite
John Wiegley429bb272011-04-08 18:41:53 +00004231 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004232
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004233 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004234 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004235
Douglas Gregor1927b1f2010-04-01 22:47:07 +00004236 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00004237 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
4238 if (!Composite.isNull())
4239 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004240
Chandler Carruth7ef93242011-02-19 00:13:59 +00004241 // Check if we are using a null with a non-pointer type.
John Wiegley429bb272011-04-08 18:41:53 +00004242 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth7ef93242011-02-19 00:13:59 +00004243 return QualType();
4244
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004245 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00004246 << LHS.get()->getType() << RHS.get()->getType()
4247 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004248 return QualType();
4249}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004250
4251/// \brief Find a merged pointer type and convert the two expressions to it.
4252///
Douglas Gregor20b3e992009-08-24 17:42:35 +00004253/// This finds the composite pointer type (or member pointer type) for @p E1
4254/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
4255/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004256/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004257///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004258/// \param Loc The location of the operator requiring these two expressions to
4259/// be converted to the composite pointer type.
4260///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004261/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
4262/// a non-standard (but still sane) composite type to which both expressions
4263/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
4264/// will be set true.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004265QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004266 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004267 bool *NonStandardCompositeType) {
4268 if (NonStandardCompositeType)
4269 *NonStandardCompositeType = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004270
David Blaikie4e4d0842012-03-11 07:00:24 +00004271 assert(getLangOpts().CPlusPlus && "This function assumes C++");
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004272 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004273
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00004274 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
4275 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00004276 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004277
4278 // C++0x 5.9p2
4279 // Pointer conversions and qualification conversions are performed on
4280 // pointer operands to bring them to their composite pointer type. If
4281 // one operand is a null pointer constant, the composite pointer type is
4282 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00004283 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004284 if (T2->isMemberPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00004285 E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004286 else
John Wiegley429bb272011-04-08 18:41:53 +00004287 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004288 return T2;
4289 }
Douglas Gregorce940492009-09-25 04:25:58 +00004290 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004291 if (T1->isMemberPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00004292 E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004293 else
John Wiegley429bb272011-04-08 18:41:53 +00004294 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004295 return T1;
4296 }
Mike Stump1eb44332009-09-09 15:08:12 +00004297
Douglas Gregor20b3e992009-08-24 17:42:35 +00004298 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00004299 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
4300 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004301 return QualType();
4302
4303 // Otherwise, of one of the operands has type "pointer to cv1 void," then
4304 // the other has type "pointer to cv2 T" and the composite pointer type is
4305 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
4306 // Otherwise, the composite pointer type is a pointer type similar to the
4307 // type of one of the operands, with a cv-qualification signature that is
4308 // the union of the cv-qualification signatures of the operand types.
4309 // In practice, the first part here is redundant; it's subsumed by the second.
4310 // What we do here is, we build the two possible composite types, and try the
4311 // conversions in both directions. If only one works, or if the two composite
4312 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00004313 // FIXME: extended qualifiers?
Chris Lattner5f9e2722011-07-23 10:55:15 +00004314 typedef SmallVector<unsigned, 4> QualifierVector;
Sebastian Redla439e6f2009-11-16 21:03:45 +00004315 QualifierVector QualifierUnion;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004316 typedef SmallVector<std::pair<const Type *, const Type *>, 4>
Sebastian Redla439e6f2009-11-16 21:03:45 +00004317 ContainingClassVector;
4318 ContainingClassVector MemberOfClass;
4319 QualType Composite1 = Context.getCanonicalType(T1),
4320 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004321 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00004322 do {
4323 const PointerType *Ptr1, *Ptr2;
4324 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
4325 (Ptr2 = Composite2->getAs<PointerType>())) {
4326 Composite1 = Ptr1->getPointeeType();
4327 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004328
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004329 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004330 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004331 if (NonStandardCompositeType &&
4332 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4333 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004334
Douglas Gregor20b3e992009-08-24 17:42:35 +00004335 QualifierUnion.push_back(
4336 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
4337 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
4338 continue;
4339 }
Mike Stump1eb44332009-09-09 15:08:12 +00004340
Douglas Gregor20b3e992009-08-24 17:42:35 +00004341 const MemberPointerType *MemPtr1, *MemPtr2;
4342 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
4343 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
4344 Composite1 = MemPtr1->getPointeeType();
4345 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004346
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004347 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004348 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004349 if (NonStandardCompositeType &&
4350 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4351 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004352
Douglas Gregor20b3e992009-08-24 17:42:35 +00004353 QualifierUnion.push_back(
4354 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
4355 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
4356 MemPtr2->getClass()));
4357 continue;
4358 }
Mike Stump1eb44332009-09-09 15:08:12 +00004359
Douglas Gregor20b3e992009-08-24 17:42:35 +00004360 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00004361
Douglas Gregor20b3e992009-08-24 17:42:35 +00004362 // Cannot unwrap any more types.
4363 break;
4364 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00004365
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004366 if (NeedConstBefore && NonStandardCompositeType) {
4367 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004368 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004369 // requirements of C++ [conv.qual]p4 bullet 3.
4370 for (unsigned I = 0; I != NeedConstBefore; ++I) {
4371 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
4372 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
4373 *NonStandardCompositeType = true;
4374 }
4375 }
4376 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004377
Douglas Gregor20b3e992009-08-24 17:42:35 +00004378 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00004379 ContainingClassVector::reverse_iterator MOC
4380 = MemberOfClass.rbegin();
4381 for (QualifierVector::reverse_iterator
4382 I = QualifierUnion.rbegin(),
4383 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00004384 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00004385 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00004386 if (MOC->first && MOC->second) {
4387 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00004388 Composite1 = Context.getMemberPointerType(
4389 Context.getQualifiedType(Composite1, Quals),
4390 MOC->first);
4391 Composite2 = Context.getMemberPointerType(
4392 Context.getQualifiedType(Composite2, Quals),
4393 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00004394 } else {
4395 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00004396 Composite1
4397 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
4398 Composite2
4399 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00004400 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004401 }
4402
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004403 // Try to convert to the first composite pointer type.
4404 InitializedEntity Entity1
4405 = InitializedEntity::InitializeTemporary(Composite1);
4406 InitializationKind Kind
4407 = InitializationKind::CreateCopy(Loc, SourceLocation());
4408 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
4409 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00004410
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004411 if (E1ToC1 && E2ToC1) {
4412 // Conversion to Composite1 is viable.
4413 if (!Context.hasSameType(Composite1, Composite2)) {
4414 // Composite2 is a different type from Composite1. Check whether
4415 // Composite2 is also viable.
4416 InitializedEntity Entity2
4417 = InitializedEntity::InitializeTemporary(Composite2);
4418 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4419 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4420 if (E1ToC2 && E2ToC2) {
4421 // Both Composite1 and Composite2 are viable and are different;
4422 // this is an ambiguity.
4423 return QualType();
4424 }
4425 }
4426
4427 // Convert E1 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00004428 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00004429 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004430 if (E1Result.isInvalid())
4431 return QualType();
4432 E1 = E1Result.takeAs<Expr>();
4433
4434 // Convert E2 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00004435 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00004436 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004437 if (E2Result.isInvalid())
4438 return QualType();
4439 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004440
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004441 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004442 }
4443
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004444 // Check whether Composite2 is viable.
4445 InitializedEntity Entity2
4446 = InitializedEntity::InitializeTemporary(Composite2);
4447 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4448 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4449 if (!E1ToC2 || !E2ToC2)
4450 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004451
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004452 // Convert E1 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00004453 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00004454 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004455 if (E1Result.isInvalid())
4456 return QualType();
4457 E1 = E1Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004458
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004459 // Convert E2 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00004460 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00004461 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004462 if (E2Result.isInvalid())
4463 return QualType();
4464 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004465
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004466 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004467}
Anders Carlsson165a0a02009-05-17 18:41:29 +00004468
John McCall60d7b3a2010-08-24 06:29:42 +00004469ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor19cc1c72010-11-01 21:10:29 +00004470 if (!E)
4471 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004472
John McCallf85e1932011-06-15 23:02:42 +00004473 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
4474
4475 // If the result is a glvalue, we shouldn't bind it.
4476 if (!E->isRValue())
Anders Carlsson089c2602009-08-15 23:41:35 +00004477 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004478
John McCallf85e1932011-06-15 23:02:42 +00004479 // In ARC, calls that return a retainable type can return retained,
4480 // in which case we have to insert a consuming cast.
David Blaikie4e4d0842012-03-11 07:00:24 +00004481 if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00004482 E->getType()->isObjCRetainableType()) {
4483
4484 bool ReturnsRetained;
4485
4486 // For actual calls, we compute this by examining the type of the
4487 // called value.
4488 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
4489 Expr *Callee = Call->getCallee()->IgnoreParens();
4490 QualType T = Callee->getType();
4491
4492 if (T == Context.BoundMemberTy) {
4493 // Handle pointer-to-members.
4494 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
4495 T = BinOp->getRHS()->getType();
4496 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
4497 T = Mem->getMemberDecl()->getType();
4498 }
4499
4500 if (const PointerType *Ptr = T->getAs<PointerType>())
4501 T = Ptr->getPointeeType();
4502 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
4503 T = Ptr->getPointeeType();
4504 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
4505 T = MemPtr->getPointeeType();
4506
4507 const FunctionType *FTy = T->getAs<FunctionType>();
4508 assert(FTy && "call to value not of function type?");
4509 ReturnsRetained = FTy->getExtInfo().getProducesResult();
4510
4511 // ActOnStmtExpr arranges things so that StmtExprs of retainable
4512 // type always produce a +1 object.
4513 } else if (isa<StmtExpr>(E)) {
4514 ReturnsRetained = true;
4515
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004516 // We hit this case with the lambda conversion-to-block optimization;
4517 // we don't want any extra casts here.
4518 } else if (isa<CastExpr>(E) &&
4519 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
4520 return Owned(E);
4521
John McCallf85e1932011-06-15 23:02:42 +00004522 // For message sends and property references, we try to find an
4523 // actual method. FIXME: we should infer retention by selector in
4524 // cases where we don't have an actual method.
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004525 } else {
4526 ObjCMethodDecl *D = 0;
4527 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
4528 D = Send->getMethodDecl();
Patrick Beardeb382ec2012-04-19 00:25:12 +00004529 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
4530 D = BoxedExpr->getBoxingMethod();
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004531 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
4532 D = ArrayLit->getArrayWithObjectsMethod();
4533 } else if (ObjCDictionaryLiteral *DictLit
4534 = dyn_cast<ObjCDictionaryLiteral>(E)) {
4535 D = DictLit->getDictWithObjectsMethod();
4536 }
John McCallf85e1932011-06-15 23:02:42 +00004537
4538 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCallfc4b1912011-08-03 07:02:44 +00004539
4540 // Don't do reclaims on performSelector calls; despite their
4541 // return type, the invoked method doesn't necessarily actually
4542 // return an object.
4543 if (!ReturnsRetained &&
4544 D && D->getMethodFamily() == OMF_performSelector)
4545 return Owned(E);
John McCallf85e1932011-06-15 23:02:42 +00004546 }
4547
John McCall567c5862011-11-14 19:53:16 +00004548 // Don't reclaim an object of Class type.
4549 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
4550 return Owned(E);
4551
John McCall7e5e5f42011-07-07 06:58:02 +00004552 ExprNeedsCleanups = true;
4553
John McCall33e56f32011-09-10 06:18:15 +00004554 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
4555 : CK_ARCReclaimReturnedObject);
John McCall7e5e5f42011-07-07 06:58:02 +00004556 return Owned(ImplicitCastExpr::Create(Context, E->getType(), ck, E, 0,
4557 VK_RValue));
John McCallf85e1932011-06-15 23:02:42 +00004558 }
4559
David Blaikie4e4d0842012-03-11 07:00:24 +00004560 if (!getLangOpts().CPlusPlus)
John McCallf85e1932011-06-15 23:02:42 +00004561 return Owned(E);
Douglas Gregor51326552009-12-24 18:51:59 +00004562
Peter Collingbourneb4ab8432012-01-26 03:33:51 +00004563 // Search for the base element type (cf. ASTContext::getBaseElementType) with
4564 // a fast path for the common case that the type is directly a RecordType.
4565 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
4566 const RecordType *RT = 0;
4567 while (!RT) {
4568 switch (T->getTypeClass()) {
4569 case Type::Record:
4570 RT = cast<RecordType>(T);
4571 break;
4572 case Type::ConstantArray:
4573 case Type::IncompleteArray:
4574 case Type::VariableArray:
4575 case Type::DependentSizedArray:
4576 T = cast<ArrayType>(T)->getElementType().getTypePtr();
4577 break;
4578 default:
4579 return Owned(E);
4580 }
4581 }
Mike Stump1eb44332009-09-09 15:08:12 +00004582
Richard Smith76f3f692012-02-22 02:04:18 +00004583 // That should be enough to guarantee that this type is complete, if we're
4584 // not processing a decltype expression.
Jeffrey Yasskinb7ee2e52011-01-27 19:17:54 +00004585 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Richard Smith213d70b2012-02-18 04:13:32 +00004586 if (RD->isInvalidDecl() || RD->isDependentContext())
John McCall86ff3082010-02-04 22:26:26 +00004587 return Owned(E);
Richard Smith76f3f692012-02-22 02:04:18 +00004588
4589 bool IsDecltype = ExprEvalContexts.back().IsDecltype;
4590 CXXDestructorDecl *Destructor = IsDecltype ? 0 : LookupDestructor(RD);
John McCallf85e1932011-06-15 23:02:42 +00004591
John McCallf85e1932011-06-15 23:02:42 +00004592 if (Destructor) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00004593 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00004594 CheckDestructorAccess(E->getExprLoc(), Destructor,
4595 PDiag(diag::err_access_dtor_temp)
4596 << E->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00004597 DiagnoseUseOfDecl(Destructor, E->getExprLoc());
John McCallf85e1932011-06-15 23:02:42 +00004598
Richard Smith76f3f692012-02-22 02:04:18 +00004599 // If destructor is trivial, we can avoid the extra copy.
4600 if (Destructor->isTrivial())
4601 return Owned(E);
Richard Smith213d70b2012-02-18 04:13:32 +00004602
John McCall80ee6e82011-11-10 05:35:25 +00004603 // We need a cleanup, but we don't need to remember the temporary.
John McCallf85e1932011-06-15 23:02:42 +00004604 ExprNeedsCleanups = true;
Richard Smith76f3f692012-02-22 02:04:18 +00004605 }
Richard Smith213d70b2012-02-18 04:13:32 +00004606
4607 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
Richard Smith76f3f692012-02-22 02:04:18 +00004608 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
4609
4610 if (IsDecltype)
4611 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
4612
4613 return Owned(Bind);
Anders Carlssondef11992009-05-30 20:36:53 +00004614}
4615
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004616ExprResult
John McCall4765fa02010-12-06 08:20:24 +00004617Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregor90f93822009-12-22 22:17:25 +00004618 if (SubExpr.isInvalid())
4619 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004620
John McCall4765fa02010-12-06 08:20:24 +00004621 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregor90f93822009-12-22 22:17:25 +00004622}
4623
John McCall80ee6e82011-11-10 05:35:25 +00004624Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
4625 assert(SubExpr && "sub expression can't be null!");
4626
Eli Friedmand2cce132012-02-02 23:15:15 +00004627 CleanupVarDeclMarking();
4628
John McCall80ee6e82011-11-10 05:35:25 +00004629 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
4630 assert(ExprCleanupObjects.size() >= FirstCleanup);
4631 assert(ExprNeedsCleanups || ExprCleanupObjects.size() == FirstCleanup);
4632 if (!ExprNeedsCleanups)
4633 return SubExpr;
4634
4635 ArrayRef<ExprWithCleanups::CleanupObject> Cleanups
4636 = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
4637 ExprCleanupObjects.size() - FirstCleanup);
4638
4639 Expr *E = ExprWithCleanups::Create(Context, SubExpr, Cleanups);
4640 DiscardCleanupsInEvaluationContext();
4641
4642 return E;
4643}
4644
John McCall4765fa02010-12-06 08:20:24 +00004645Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004646 assert(SubStmt && "sub statement can't be null!");
4647
Eli Friedmand2cce132012-02-02 23:15:15 +00004648 CleanupVarDeclMarking();
4649
John McCallf85e1932011-06-15 23:02:42 +00004650 if (!ExprNeedsCleanups)
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004651 return SubStmt;
4652
4653 // FIXME: In order to attach the temporaries, wrap the statement into
4654 // a StmtExpr; currently this is only used for asm statements.
4655 // This is hacky, either create a new CXXStmtWithTemporaries statement or
4656 // a new AsmStmtWithTemporaries.
4657 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
4658 SourceLocation(),
4659 SourceLocation());
4660 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
4661 SourceLocation());
John McCall4765fa02010-12-06 08:20:24 +00004662 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004663}
4664
Richard Smith76f3f692012-02-22 02:04:18 +00004665/// Process the expression contained within a decltype. For such expressions,
4666/// certain semantic checks on temporaries are delayed until this point, and
4667/// are omitted for the 'topmost' call in the decltype expression. If the
4668/// topmost call bound a temporary, strip that temporary off the expression.
4669ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
4670 ExpressionEvaluationContextRecord &Rec = ExprEvalContexts.back();
4671 assert(Rec.IsDecltype && "not in a decltype expression");
4672
4673 // C++11 [expr.call]p11:
4674 // If a function call is a prvalue of object type,
4675 // -- if the function call is either
4676 // -- the operand of a decltype-specifier, or
4677 // -- the right operand of a comma operator that is the operand of a
4678 // decltype-specifier,
4679 // a temporary object is not introduced for the prvalue.
4680
4681 // Recursively rebuild ParenExprs and comma expressions to strip out the
4682 // outermost CXXBindTemporaryExpr, if any.
4683 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4684 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
4685 if (SubExpr.isInvalid())
4686 return ExprError();
4687 if (SubExpr.get() == PE->getSubExpr())
4688 return Owned(E);
4689 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.take());
4690 }
4691 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4692 if (BO->getOpcode() == BO_Comma) {
4693 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
4694 if (RHS.isInvalid())
4695 return ExprError();
4696 if (RHS.get() == BO->getRHS())
4697 return Owned(E);
4698 return Owned(new (Context) BinaryOperator(BO->getLHS(), RHS.take(),
4699 BO_Comma, BO->getType(),
4700 BO->getValueKind(),
4701 BO->getObjectKind(),
4702 BO->getOperatorLoc()));
4703 }
4704 }
4705
4706 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
4707 if (TopBind)
4708 E = TopBind->getSubExpr();
4709
4710 // Disable the special decltype handling now.
4711 Rec.IsDecltype = false;
4712
4713 // Perform the semantic checks we delayed until this point.
4714 CallExpr *TopCall = dyn_cast<CallExpr>(E);
4715 for (unsigned I = 0, N = Rec.DelayedDecltypeCalls.size(); I != N; ++I) {
4716 CallExpr *Call = Rec.DelayedDecltypeCalls[I];
4717 if (Call == TopCall)
4718 continue;
4719
4720 if (CheckCallReturnType(Call->getCallReturnType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00004721 Call->getLocStart(),
Richard Smith76f3f692012-02-22 02:04:18 +00004722 Call, Call->getDirectCallee()))
4723 return ExprError();
4724 }
4725
4726 // Now all relevant types are complete, check the destructors are accessible
4727 // and non-deleted, and annotate them on the temporaries.
4728 for (unsigned I = 0, N = Rec.DelayedDecltypeBinds.size(); I != N; ++I) {
4729 CXXBindTemporaryExpr *Bind = Rec.DelayedDecltypeBinds[I];
4730 if (Bind == TopBind)
4731 continue;
4732
4733 CXXTemporary *Temp = Bind->getTemporary();
4734
4735 CXXRecordDecl *RD =
4736 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
4737 CXXDestructorDecl *Destructor = LookupDestructor(RD);
4738 Temp->setDestructor(Destructor);
4739
4740 MarkFunctionReferenced(E->getExprLoc(), Destructor);
4741 CheckDestructorAccess(E->getExprLoc(), Destructor,
4742 PDiag(diag::err_access_dtor_temp)
4743 << E->getType());
4744 DiagnoseUseOfDecl(Destructor, E->getExprLoc());
4745
4746 // We need a cleanup, but we don't need to remember the temporary.
4747 ExprNeedsCleanups = true;
4748 }
4749
4750 // Possibly strip off the top CXXBindTemporaryExpr.
4751 return Owned(E);
4752}
4753
John McCall60d7b3a2010-08-24 06:29:42 +00004754ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004755Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallb3d87482010-08-24 05:47:05 +00004756 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00004757 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004758 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004759 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00004760 if (Result.isInvalid()) return ExprError();
4761 Base = Result.get();
Mike Stump1eb44332009-09-09 15:08:12 +00004762
John McCall3c3b7f92011-10-25 17:37:35 +00004763 Result = CheckPlaceholderExpr(Base);
4764 if (Result.isInvalid()) return ExprError();
4765 Base = Result.take();
4766
John McCall9ae2f072010-08-23 23:25:46 +00004767 QualType BaseType = Base->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00004768 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004769 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00004770 // If we have a pointer to a dependent type and are using the -> operator,
4771 // the object type is the type that the pointer points to. We might still
4772 // have enough information about that type to do something useful.
4773 if (OpKind == tok::arrow)
4774 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4775 BaseType = Ptr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004776
John McCallb3d87482010-08-24 05:47:05 +00004777 ObjectType = ParsedType::make(BaseType);
Douglas Gregord4dca082010-02-24 18:44:31 +00004778 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00004779 return Owned(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004780 }
Mike Stump1eb44332009-09-09 15:08:12 +00004781
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004782 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00004783 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004784 // returned, with the original second operand.
4785 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00004786 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00004787 llvm::SmallPtrSet<CanQualType,8> CTypes;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004788 SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00004789 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004790
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004791 while (BaseType->isRecordType()) {
John McCall9ae2f072010-08-23 23:25:46 +00004792 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
4793 if (Result.isInvalid())
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004794 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00004795 Base = Result.get();
4796 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonde699e52009-10-13 22:55:59 +00004797 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCall9ae2f072010-08-23 23:25:46 +00004798 BaseType = Base->getType();
John McCallc4e83212009-09-30 01:01:30 +00004799 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00004800 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00004801 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00004802 for (unsigned i = 0; i < Locations.size(); i++)
4803 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00004804 return ExprError();
4805 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004806 }
Mike Stump1eb44332009-09-09 15:08:12 +00004807
Douglas Gregor1d7049a2012-01-12 16:11:24 +00004808 if (BaseType->isPointerType() || BaseType->isObjCObjectPointerType())
Douglas Gregor31658df2009-11-20 19:58:21 +00004809 BaseType = BaseType->getPointeeType();
4810 }
Mike Stump1eb44332009-09-09 15:08:12 +00004811
Douglas Gregor1d7049a2012-01-12 16:11:24 +00004812 // Objective-C properties allow "." access on Objective-C pointer types,
4813 // so adjust the base type to the object type itself.
4814 if (BaseType->isObjCObjectPointerType())
4815 BaseType = BaseType->getPointeeType();
4816
4817 // C++ [basic.lookup.classref]p2:
4818 // [...] If the type of the object expression is of pointer to scalar
4819 // type, the unqualified-id is looked up in the context of the complete
4820 // postfix-expression.
4821 //
4822 // This also indicates that we could be parsing a pseudo-destructor-name.
4823 // Note that Objective-C class and object types can be pseudo-destructor
4824 // expressions or normal member (ivar or property) access expressions.
4825 if (BaseType->isObjCObjectOrInterfaceType()) {
4826 MayBePseudoDestructor = true;
4827 } else if (!BaseType->isRecordType()) {
John McCallb3d87482010-08-24 05:47:05 +00004828 ObjectType = ParsedType();
Douglas Gregord4dca082010-02-24 18:44:31 +00004829 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00004830 return Owned(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00004831 }
Mike Stump1eb44332009-09-09 15:08:12 +00004832
Douglas Gregorcefc3af2012-04-16 07:05:22 +00004833 // The object type must be complete (or dependent), or
4834 // C++11 [expr.prim.general]p3:
4835 // Unlike the object expression in other contexts, *this is not required to
4836 // be of complete type for purposes of class member access (5.2.5) outside
4837 // the member function body.
Douglas Gregor03c57052009-11-17 05:17:33 +00004838 if (!BaseType->isDependentType() &&
Douglas Gregorcefc3af2012-04-16 07:05:22 +00004839 !isThisOutsideMemberFunctionBody(BaseType) &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004840 RequireCompleteType(OpLoc, BaseType,
Douglas Gregor03c57052009-11-17 05:17:33 +00004841 PDiag(diag::err_incomplete_member_access)))
4842 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004843
Douglas Gregorc68afe22009-09-03 21:38:09 +00004844 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004845 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00004846 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00004847 // type C (or of pointer to a class type C), the unqualified-id is looked
4848 // up in the scope of class C. [...]
John McCallb3d87482010-08-24 05:47:05 +00004849 ObjectType = ParsedType::make(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00004850 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004851}
4852
John McCall60d7b3a2010-08-24 06:29:42 +00004853ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCall9ae2f072010-08-23 23:25:46 +00004854 Expr *MemExpr) {
Douglas Gregor77549082010-02-24 21:29:12 +00004855 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCall9ae2f072010-08-23 23:25:46 +00004856 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
4857 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregor849b2432010-03-31 17:46:05 +00004858 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004859
Douglas Gregor77549082010-02-24 21:29:12 +00004860 return ActOnCallExpr(/*Scope*/ 0,
John McCall9ae2f072010-08-23 23:25:46 +00004861 MemExpr,
Douglas Gregor77549082010-02-24 21:29:12 +00004862 /*LPLoc*/ ExpectedLParenLoc,
John McCallf312b1e2010-08-26 23:41:50 +00004863 MultiExprArg(),
Douglas Gregor77549082010-02-24 21:29:12 +00004864 /*RPLoc*/ ExpectedLParenLoc);
4865}
Douglas Gregord4dca082010-02-24 18:44:31 +00004866
Eli Friedmane0dbedf2012-01-25 04:29:24 +00004867static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie91ec7892011-12-16 16:03:09 +00004868 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedmane0dbedf2012-01-25 04:29:24 +00004869 if (Base->hasPlaceholderType()) {
4870 ExprResult result = S.CheckPlaceholderExpr(Base);
4871 if (result.isInvalid()) return true;
4872 Base = result.take();
4873 }
4874 ObjectType = Base->getType();
4875
David Blaikie91ec7892011-12-16 16:03:09 +00004876 // C++ [expr.pseudo]p2:
4877 // The left-hand side of the dot operator shall be of scalar type. The
4878 // left-hand side of the arrow operator shall be of pointer to scalar type.
4879 // This scalar type is the object type.
Eli Friedmane0dbedf2012-01-25 04:29:24 +00004880 // Note that this is rather different from the normal handling for the
4881 // arrow operator.
David Blaikie91ec7892011-12-16 16:03:09 +00004882 if (OpKind == tok::arrow) {
4883 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4884 ObjectType = Ptr->getPointeeType();
4885 } else if (!Base->isTypeDependent()) {
4886 // The user wrote "p->" when she probably meant "p."; fix it.
4887 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4888 << ObjectType << true
4889 << FixItHint::CreateReplacement(OpLoc, ".");
4890 if (S.isSFINAEContext())
4891 return true;
4892
4893 OpKind = tok::period;
4894 }
4895 }
4896
4897 return false;
4898}
4899
John McCall60d7b3a2010-08-24 06:29:42 +00004900ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00004901 SourceLocation OpLoc,
4902 tok::TokenKind OpKind,
4903 const CXXScopeSpec &SS,
4904 TypeSourceInfo *ScopeTypeInfo,
4905 SourceLocation CCLoc,
4906 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004907 PseudoDestructorTypeStorage Destructed,
John McCall2d9f5fa2011-02-25 05:21:17 +00004908 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004909 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004910
Eli Friedman8c9fe202012-01-25 04:35:06 +00004911 QualType ObjectType;
David Blaikie91ec7892011-12-16 16:03:09 +00004912 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4913 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004914
Douglas Gregorb57fb492010-02-24 22:38:50 +00004915 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00004916 if (getLangOpts().MicrosoftMode && ObjectType->isVoidType())
Nico Weber2d757ec2012-01-23 06:08:16 +00004917 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Nico Weberdf1be862012-01-23 05:50:57 +00004918 else
4919 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
4920 << ObjectType << Base->getSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00004921 return ExprError();
4922 }
4923
4924 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004925 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb57fb492010-02-24 22:38:50 +00004926 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004927 if (DestructedTypeInfo) {
4928 QualType DestructedType = DestructedTypeInfo->getType();
4929 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004930 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCallf85e1932011-06-15 23:02:42 +00004931 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
4932 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
4933 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
4934 << ObjectType << DestructedType << Base->getSourceRange()
4935 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004936
John McCallf85e1932011-06-15 23:02:42 +00004937 // Recover by setting the destructed type to the object type.
4938 DestructedType = ObjectType;
4939 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004940 DestructedTypeStart);
John McCallf85e1932011-06-15 23:02:42 +00004941 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4942 } else if (DestructedType.getObjCLifetime() !=
4943 ObjectType.getObjCLifetime()) {
4944
4945 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
4946 // Okay: just pretend that the user provided the correctly-qualified
4947 // type.
4948 } else {
4949 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
4950 << ObjectType << DestructedType << Base->getSourceRange()
4951 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
4952 }
4953
4954 // Recover by setting the destructed type to the object type.
4955 DestructedType = ObjectType;
4956 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
4957 DestructedTypeStart);
4958 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4959 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004960 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00004961 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004962
Douglas Gregorb57fb492010-02-24 22:38:50 +00004963 // C++ [expr.pseudo]p2:
4964 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
4965 // form
4966 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004967 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb57fb492010-02-24 22:38:50 +00004968 //
4969 // shall designate the same scalar type.
4970 if (ScopeTypeInfo) {
4971 QualType ScopeType = ScopeTypeInfo->getType();
4972 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00004973 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004974
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004975 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00004976 diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00004977 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004978 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004979
Douglas Gregorb57fb492010-02-24 22:38:50 +00004980 ScopeType = QualType();
4981 ScopeTypeInfo = 0;
4982 }
4983 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004984
John McCall9ae2f072010-08-23 23:25:46 +00004985 Expr *Result
4986 = new (Context) CXXPseudoDestructorExpr(Context, Base,
4987 OpKind == tok::arrow, OpLoc,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00004988 SS.getWithLocInContext(Context),
John McCall9ae2f072010-08-23 23:25:46 +00004989 ScopeTypeInfo,
4990 CCLoc,
4991 TildeLoc,
4992 Destructed);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004993
Douglas Gregorb57fb492010-02-24 22:38:50 +00004994 if (HasTrailingLParen)
John McCall9ae2f072010-08-23 23:25:46 +00004995 return Owned(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004996
John McCall9ae2f072010-08-23 23:25:46 +00004997 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor77549082010-02-24 21:29:12 +00004998}
4999
John McCall60d7b3a2010-08-24 06:29:42 +00005000ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00005001 SourceLocation OpLoc,
5002 tok::TokenKind OpKind,
5003 CXXScopeSpec &SS,
5004 UnqualifiedId &FirstTypeName,
5005 SourceLocation CCLoc,
5006 SourceLocation TildeLoc,
5007 UnqualifiedId &SecondTypeName,
5008 bool HasTrailingLParen) {
Douglas Gregor77549082010-02-24 21:29:12 +00005009 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5010 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
5011 "Invalid first type name in pseudo-destructor");
5012 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5013 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
5014 "Invalid second type name in pseudo-destructor");
5015
Eli Friedman8c9fe202012-01-25 04:35:06 +00005016 QualType ObjectType;
David Blaikie91ec7892011-12-16 16:03:09 +00005017 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5018 return ExprError();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005019
5020 // Compute the object type that we should use for name lookup purposes. Only
5021 // record types and dependent types matter.
John McCallb3d87482010-08-24 05:47:05 +00005022 ParsedType ObjectTypePtrForLookup;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005023 if (!SS.isSet()) {
John McCall2d9f5fa2011-02-25 05:21:17 +00005024 if (ObjectType->isRecordType())
5025 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallb3d87482010-08-24 05:47:05 +00005026 else if (ObjectType->isDependentType())
5027 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005028 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005029
5030 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb57fb492010-02-24 22:38:50 +00005031 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00005032 QualType DestructedType;
5033 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005034 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00005035 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005036 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00005037 SecondTypeName.StartLocation,
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +00005038 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005039 if (!T &&
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005040 ((SS.isSet() && !computeDeclContext(SS, false)) ||
5041 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005042 // The name of the type being destroyed is a dependent name, and we
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005043 // couldn't find anything useful in scope. Just store the identifier and
5044 // it's location, and we'll perform (qualified) name lookup again at
5045 // template instantiation time.
5046 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
5047 SecondTypeName.StartLocation);
5048 } else if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005049 Diag(SecondTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00005050 diag::err_pseudo_dtor_destructor_non_type)
5051 << SecondTypeName.Identifier << ObjectType;
5052 if (isSFINAEContext())
5053 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005054
Douglas Gregor77549082010-02-24 21:29:12 +00005055 // Recover by assuming we had the right type all along.
5056 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00005057 } else
Douglas Gregor77549082010-02-24 21:29:12 +00005058 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00005059 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00005060 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00005061 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00005062 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5063 TemplateId->getTemplateArgs(),
5064 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00005065 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara55d23c92012-02-06 14:41:24 +00005066 TemplateId->TemplateKWLoc,
Douglas Gregor059101f2011-03-02 00:47:37 +00005067 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00005068 TemplateId->TemplateNameLoc,
5069 TemplateId->LAngleLoc,
5070 TemplateArgsPtr,
5071 TemplateId->RAngleLoc);
5072 if (T.isInvalid() || !T.get()) {
5073 // Recover by assuming we had the right type all along.
5074 DestructedType = ObjectType;
5075 } else
5076 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00005077 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005078
5079 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb57fb492010-02-24 22:38:50 +00005080 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005081 if (!DestructedType.isNull()) {
5082 if (!DestructedTypeInfo)
5083 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00005084 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005085 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5086 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005087
Douglas Gregorb57fb492010-02-24 22:38:50 +00005088 // Convert the name of the scope type (the type prior to '::') into a type.
5089 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00005090 QualType ScopeType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005091 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor77549082010-02-24 21:29:12 +00005092 FirstTypeName.Identifier) {
5093 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005094 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00005095 FirstTypeName.StartLocation,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00005096 S, &SS, true, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00005097 if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005098 Diag(FirstTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00005099 diag::err_pseudo_dtor_destructor_non_type)
5100 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005101
Douglas Gregorb57fb492010-02-24 22:38:50 +00005102 if (isSFINAEContext())
5103 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005104
Douglas Gregorb57fb492010-02-24 22:38:50 +00005105 // Just drop this type. It's unnecessary anyway.
5106 ScopeType = QualType();
5107 } else
5108 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00005109 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00005110 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00005111 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00005112 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5113 TemplateId->getTemplateArgs(),
5114 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00005115 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara55d23c92012-02-06 14:41:24 +00005116 TemplateId->TemplateKWLoc,
Douglas Gregor059101f2011-03-02 00:47:37 +00005117 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00005118 TemplateId->TemplateNameLoc,
5119 TemplateId->LAngleLoc,
5120 TemplateArgsPtr,
5121 TemplateId->RAngleLoc);
5122 if (T.isInvalid() || !T.get()) {
5123 // Recover by dropping this type.
5124 ScopeType = QualType();
5125 } else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005126 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00005127 }
5128 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005129
Douglas Gregorb4a418f2010-02-24 23:02:30 +00005130 if (!ScopeType.isNull() && !ScopeTypeInfo)
5131 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
5132 FirstTypeName.StartLocation);
5133
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005134
John McCall9ae2f072010-08-23 23:25:46 +00005135 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00005136 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005137 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00005138}
5139
David Blaikie91ec7892011-12-16 16:03:09 +00005140ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5141 SourceLocation OpLoc,
5142 tok::TokenKind OpKind,
5143 SourceLocation TildeLoc,
5144 const DeclSpec& DS,
5145 bool HasTrailingLParen) {
Eli Friedman8c9fe202012-01-25 04:35:06 +00005146 QualType ObjectType;
David Blaikie91ec7892011-12-16 16:03:09 +00005147 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5148 return ExprError();
5149
5150 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
5151
5152 TypeLocBuilder TLB;
5153 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
5154 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
5155 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
5156 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
5157
5158 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
5159 0, SourceLocation(), TildeLoc,
5160 Destructed, HasTrailingLParen);
5161}
5162
John Wiegley429bb272011-04-08 18:41:53 +00005163ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Eli Friedman3f01c8a2012-03-01 01:30:04 +00005164 CXXConversionDecl *Method,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005165 bool HadMultipleCandidates) {
Eli Friedman23f02672012-03-01 04:01:32 +00005166 if (Method->getParent()->isLambda() &&
5167 Method->getConversionType()->isBlockPointerType()) {
5168 // This is a lambda coversion to block pointer; check if the argument
5169 // is a LambdaExpr.
5170 Expr *SubE = E;
5171 CastExpr *CE = dyn_cast<CastExpr>(SubE);
5172 if (CE && CE->getCastKind() == CK_NoOp)
5173 SubE = CE->getSubExpr();
5174 SubE = SubE->IgnoreParens();
5175 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
5176 SubE = BE->getSubExpr();
5177 if (isa<LambdaExpr>(SubE)) {
5178 // For the conversion to block pointer on a lambda expression, we
5179 // construct a special BlockLiteral instead; this doesn't really make
5180 // a difference in ARC, but outside of ARC the resulting block literal
5181 // follows the normal lifetime rules for block literals instead of being
5182 // autoreleased.
5183 DiagnosticErrorTrap Trap(Diags);
5184 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
5185 E->getExprLoc(),
5186 Method, E);
5187 if (Exp.isInvalid())
5188 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
5189 return Exp;
5190 }
5191 }
5192
5193
John Wiegley429bb272011-04-08 18:41:53 +00005194 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
5195 FoundDecl, Method);
5196 if (Exp.isInvalid())
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005197 return true;
Eli Friedman772fffa2009-12-09 04:53:56 +00005198
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005199 MemberExpr *ME =
John Wiegley429bb272011-04-08 18:41:53 +00005200 new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
Abramo Bagnara960809e2011-11-16 22:46:05 +00005201 SourceLocation(), Context.BoundMemberTy,
John McCallf89e55a2010-11-18 06:31:45 +00005202 VK_RValue, OK_Ordinary);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005203 if (HadMultipleCandidates)
5204 ME->setHadMultipleCandidates(true);
5205
John McCallf89e55a2010-11-18 06:31:45 +00005206 QualType ResultType = Method->getResultType();
5207 ExprValueKind VK = Expr::getValueKindForType(ResultType);
5208 ResultType = ResultType.getNonLValueExprType(Context);
5209
Eli Friedman5f2987c2012-02-02 03:46:19 +00005210 MarkFunctionReferenced(Exp.get()->getLocStart(), Method);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005211 CXXMemberCallExpr *CE =
John McCallf89e55a2010-11-18 06:31:45 +00005212 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
John Wiegley429bb272011-04-08 18:41:53 +00005213 Exp.get()->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00005214 return CE;
5215}
5216
Sebastian Redl2e156222010-09-10 20:55:43 +00005217ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
5218 SourceLocation RParen) {
Richard Smithe6975e92012-04-17 00:58:00 +00005219 CanThrowResult CanThrow = canThrow(Operand);
Sebastian Redl2e156222010-09-10 20:55:43 +00005220 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
Richard Smithe6975e92012-04-17 00:58:00 +00005221 CanThrow, KeyLoc, RParen));
Sebastian Redl2e156222010-09-10 20:55:43 +00005222}
5223
5224ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
5225 Expr *Operand, SourceLocation RParen) {
5226 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl02bc21a2010-09-10 20:55:37 +00005227}
5228
John McCallf6a16482010-12-04 03:47:34 +00005229/// Perform the conversions required for an expression used in a
5230/// context that ignores the result.
John Wiegley429bb272011-04-08 18:41:53 +00005231ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall3c3b7f92011-10-25 17:37:35 +00005232 if (E->hasPlaceholderType()) {
5233 ExprResult result = CheckPlaceholderExpr(E);
5234 if (result.isInvalid()) return Owned(E);
5235 E = result.take();
5236 }
5237
John McCalla878cda2010-12-02 02:07:15 +00005238 // C99 6.3.2.1:
5239 // [Except in specific positions,] an lvalue that does not have
5240 // array type is converted to the value stored in the
5241 // designated object (and is no longer an lvalue).
John McCalle6d134b2011-06-27 21:24:11 +00005242 if (E->isRValue()) {
5243 // In C, function designators (i.e. expressions of function type)
5244 // are r-values, but we still want to do function-to-pointer decay
5245 // on them. This is both technically correct and convenient for
5246 // some clients.
David Blaikie4e4d0842012-03-11 07:00:24 +00005247 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
John McCalle6d134b2011-06-27 21:24:11 +00005248 return DefaultFunctionArrayConversion(E);
5249
5250 return Owned(E);
5251 }
John McCalla878cda2010-12-02 02:07:15 +00005252
John McCallf6a16482010-12-04 03:47:34 +00005253 // Otherwise, this rule does not apply in C++, at least not for the moment.
David Blaikie4e4d0842012-03-11 07:00:24 +00005254 if (getLangOpts().CPlusPlus) return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00005255
5256 // GCC seems to also exclude expressions of incomplete enum type.
5257 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
5258 if (!T->getDecl()->isComplete()) {
5259 // FIXME: stupid workaround for a codegen bug!
John Wiegley429bb272011-04-08 18:41:53 +00005260 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
5261 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00005262 }
5263 }
5264
John Wiegley429bb272011-04-08 18:41:53 +00005265 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
5266 if (Res.isInvalid())
5267 return Owned(E);
5268 E = Res.take();
5269
John McCall85515d62010-12-04 12:29:11 +00005270 if (!E->getType()->isVoidType())
5271 RequireCompleteType(E->getExprLoc(), E->getType(),
5272 diag::err_incomplete_type);
John Wiegley429bb272011-04-08 18:41:53 +00005273 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00005274}
5275
John Wiegley429bb272011-04-08 18:41:53 +00005276ExprResult Sema::ActOnFinishFullExpr(Expr *FE) {
5277 ExprResult FullExpr = Owned(FE);
5278
5279 if (!FullExpr.get())
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00005280 return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00005281
John Wiegley429bb272011-04-08 18:41:53 +00005282 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregord0937222010-12-13 22:49:22 +00005283 return ExprError();
5284
Douglas Gregor5e3a8be2011-12-15 00:53:32 +00005285 // Top-level message sends default to 'id' when we're in a debugger.
David Blaikie4e4d0842012-03-11 07:00:24 +00005286 if (getLangOpts().DebuggerCastResultToId &&
Douglas Gregor5e3a8be2011-12-15 00:53:32 +00005287 FullExpr.get()->getType() == Context.UnknownAnyTy &&
5288 isa<ObjCMessageExpr>(FullExpr.get())) {
5289 FullExpr = forceUnknownAnyToType(FullExpr.take(), Context.getObjCIdType());
5290 if (FullExpr.isInvalid())
5291 return ExprError();
5292 }
5293
John McCallfb8721c2011-04-10 19:13:55 +00005294 FullExpr = CheckPlaceholderExpr(FullExpr.take());
5295 if (FullExpr.isInvalid())
5296 return ExprError();
Douglas Gregor353ee242011-03-07 02:05:23 +00005297
John Wiegley429bb272011-04-08 18:41:53 +00005298 FullExpr = IgnoredValueConversions(FullExpr.take());
5299 if (FullExpr.isInvalid())
5300 return ExprError();
5301
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005302 CheckImplicitConversions(FullExpr.get(), FullExpr.get()->getExprLoc());
John McCall4765fa02010-12-06 08:20:24 +00005303 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson165a0a02009-05-17 18:41:29 +00005304}
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00005305
5306StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
5307 if (!FullStmt) return StmtError();
5308
John McCall4765fa02010-12-06 08:20:24 +00005309 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00005310}
Francois Pichet1e862692011-05-06 20:48:22 +00005311
Douglas Gregorba0513d2011-10-25 01:33:02 +00005312Sema::IfExistsResult
5313Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
5314 CXXScopeSpec &SS,
5315 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet1e862692011-05-06 20:48:22 +00005316 DeclarationName TargetName = TargetNameInfo.getName();
5317 if (!TargetName)
Douglas Gregor3896fc52011-10-24 22:31:10 +00005318 return IER_DoesNotExist;
Douglas Gregorba0513d2011-10-25 01:33:02 +00005319
Douglas Gregor3896fc52011-10-24 22:31:10 +00005320 // If the name itself is dependent, then the result is dependent.
5321 if (TargetName.isDependentName())
5322 return IER_Dependent;
Douglas Gregorba0513d2011-10-25 01:33:02 +00005323
Francois Pichet1e862692011-05-06 20:48:22 +00005324 // Do the redeclaration lookup in the current scope.
5325 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
5326 Sema::NotForRedeclaration);
Douglas Gregor3896fc52011-10-24 22:31:10 +00005327 LookupParsedName(R, S, &SS);
Francois Pichet1e862692011-05-06 20:48:22 +00005328 R.suppressDiagnostics();
Douglas Gregor3896fc52011-10-24 22:31:10 +00005329
5330 switch (R.getResultKind()) {
5331 case LookupResult::Found:
5332 case LookupResult::FoundOverloaded:
5333 case LookupResult::FoundUnresolvedValue:
5334 case LookupResult::Ambiguous:
5335 return IER_Exists;
5336
5337 case LookupResult::NotFound:
5338 return IER_DoesNotExist;
5339
5340 case LookupResult::NotFoundInCurrentInstantiation:
5341 return IER_Dependent;
5342 }
David Blaikie7530c032012-01-17 06:56:22 +00005343
5344 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet1e862692011-05-06 20:48:22 +00005345}
Douglas Gregorba0513d2011-10-25 01:33:02 +00005346
Douglas Gregor65019ac2011-10-25 03:44:56 +00005347Sema::IfExistsResult
5348Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
5349 bool IsIfExists, CXXScopeSpec &SS,
5350 UnqualifiedId &Name) {
Douglas Gregorba0513d2011-10-25 01:33:02 +00005351 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Douglas Gregor65019ac2011-10-25 03:44:56 +00005352
5353 // Check for unexpanded parameter packs.
5354 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
5355 collectUnexpandedParameterPacks(SS, Unexpanded);
5356 collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
5357 if (!Unexpanded.empty()) {
5358 DiagnoseUnexpandedParameterPacks(KeywordLoc,
5359 IsIfExists? UPPC_IfExists
5360 : UPPC_IfNotExists,
5361 Unexpanded);
5362 return IER_Error;
5363 }
5364
Douglas Gregorba0513d2011-10-25 01:33:02 +00005365 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
5366}